Awesome Cursor Rules Collection

Showing 949-960 of 1033 matches

TypeScript
You are an expert in Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Shadcn UI, Radix UI, and TailwindCSS.

Key Principles

- Write concise, technical responses with accurate TypeScript examples.
- Use functional, declarative programming. Avoid classes.
- Prefer iteration and modularization over duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading).
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.
- Use the Receive an Object, Return an Object (RORO) pattern.

JavaScript/TypeScript

- Use "function" keyword for pure functions. Omit semicolons.
- Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use maps.
- File structure: Exported component, subcomponents, helpers, static content, types.
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).

Error Handling and Validation

- Prioritize error handling and edge cases:
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Consider using custom error types or error factories for consistent error handling.

React/Next.js

- Use functional components and TypeScript interfaces.
- Use declarative JSX.
- Use function, not const, for components.
- Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
- Implement responsive design with Tailwind CSS.
- Use mobile-first approach for responsive design.
- Place static content and interfaces at file end.
- Use content variables for static content outside render functions.
- Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
- Use Zod for form validation.
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: WebP format, size data, lazy loading.
- Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
- Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
- Use useActionState with react-hook-form for form validation.
- Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
- Use next-safe-action for all server actions:
  - Implement type-safe server actions with proper validation.
  - Utilize the `action` function from next-safe-action for creating actions.
  - Define input schemas using Zod for robust type checking and validation.
  - Handle errors gracefully and return appropriate responses.
  - Use import type { ActionResponse } from '@/types/actions'
  - Ensure all server actions return the ActionResponse type
  - Implement consistent error handling and success responses using ActionResponse

Key Conventions

1. Rely on Next.js App Router for state changes.
2. Prioritize Web Vitals (LCP, CLS, FID).
3. Minimize 'use client' usage:
   - Prefer server components and Next.js SSR features.
   - Use 'use client' only for Web API access in small components.
   - Avoid using 'use client' for data fetching or state management.

Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
css
java
javascript
mdx
nestjs
next.js
radix-ui
react
+5 more
alfredmouelle/alfredmouelle

Used in 1 repository

TypeScript
# Expert Senior Developer Guidelines

## Overview

As an expert senior developer, you specialize in modern web development with deep expertise in:

- **TypeScript**
- **React 19**
- **Next.js 15 (App Router)**
- **Vercel AI SDK**
- **Shadcn UI**
- **Radix UI**
- **Tailwind CSS**
- **Zustand**
- **React Query**
- **ZSA Actions**
- **Drizzle ORM**

---

## Project Structure

src/
├── app/ # Routes and UI logic
│ ├── api/ # API routes, webhooks
│ ├── components/ # Shared UI components
│ └── lib/ # Custom libraries and utilities
├── server/ # Server-side code
│ ├── db/ # Database config and schema
│ ├── use-cases/ # Business logic
│ └── data-access/ # Database access functions
├── public/ # Static files like images
└── styles/ # Global styles and Tailwind config

---

## Key Architectural Rules

1. **Do not access the `data-access` layer directly** from server components or actions.
2. **Always use `use-cases`** for database operations.
3. `Use-cases` must only interact with the database via **`data-access` functions**.

---

## Development Process

### Request Analysis

1. **Determine task type** (e.g., code creation, debugging, architecture, etc.).
2. Identify **languages and frameworks** involved.
3. Note explicit and implicit requirements.
4. Define the **core problem** and desired outcome.
5. Consider the **project context and constraints**.

### Solution Planning

1. Break down the solution into **logical steps**.
2. Ensure **modularity and reusability**.
3. Identify necessary **files and dependencies**.
4. Evaluate **alternative approaches**.
5. Plan for **testing and validation**.

### Implementation Strategy

1. Use appropriate **design patterns**.
2. Optimize for **performance and error handling**.
3. Ensure **accessibility compliance**.
4. Verify alignment with **best practices**.

---

## Code Style and Structure

### General Principles

- Write **concise, readable TypeScript code**.
- Use **functional and declarative programming patterns**.
- Follow the **DRY principle** (Don’t Repeat Yourself).
- Use **early returns** for better readability.
- Structure components logically:
  - Exports
  - Subcomponents
  - Helpers
  - Types

### Naming Conventions

- Use **descriptive names** (e.g., `isLoading`, `hasError`).
- Prefix event handlers with `handle` (e.g., `handleClick`).
- Use **lowercase-dash format** for directories (e.g., `components/auth-wizard`).
- Favor **named exports** for components.

### TypeScript Best Practices

- Use TypeScript for **all code**.
- Prefer **interfaces** over `type`.
- Avoid `enum`; use **`const` maps** instead.
- Implement **type safety** and inference.
- Use the `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 **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 properties like `data`, `method`, and `action`.
- Implement **URL state management** with `nuqs`.
- Minimize **client-side state**.

---

## Data Fetching

### General Guidelines

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

### Example: Cached Route Handler

```ts
export const dynamic = "force-static";

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

---

## Vercel AI SDK Integration

### Core Concepts

Use the Vercel AI SDK to build AI-powered streaming text and chat UIs. Key packages:

- `ai` - Core functionality and streaming utilities.
- `@ai-sdk/[provider]` - Model provider integrations (e.g., OpenAI).
- React hooks for UI components.

### Example: Chat UI Implementation

```tsx
"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="mx-auto flex w-full max-w-md flex-col py-24">
      {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 mb-8 w-full max-w-md rounded border border-gray-300 p-2 shadow-xl"
          value={input}
          placeholder="Say something..."
          onChange={handleInputChange}
        />
      </form>
    </div>
  );
}
```

## Technology Implementation Guidelines

### Database (Drizzle ORM)

Define database schema using Drizzle ORM for structured and type-safe queries.

```typescript
// server/db/schema/users.ts
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  createdAt: timestamp("created_at").defaultNow(),
});
```

### Data Access Layer

Encapsulate database queries in reusable functions.

```typescript
// server/data-access/users.ts
export async function findUserById(id: string) {
  return db.query.users.findFirst({
    where: eq(users.id, id),
  });
}
```

### Use Cases Layer

Define business logic in use cases, leveraging data access functions.

```typescript
// server/use-cases/users.ts
import { findUserById, updateUser } from "../data-access/users";

export async function updateUserProfile(userId: string, data: UpdateUserData) {
  const user = await findUserById(userId);
  if (!user) throw new Error("User not found");
  return updateUser(userId, data);
}
```

### State Management

Use Zustand for state management.

```typescript
// lib/stores/useAuthStore.ts
interface AuthStore {
  user: User | null;
  setUser: (user: User | null) => void;
}

export const useAuthStore = create<AuthStore>()(
  persist(
    (set) => ({
      user: null,
      setUser: (user) => set({ user }),
    }),
    { name: "auth-store" },
  ),
);
```

### Server State (React Query)

```typescript
// hooks/useUsers.ts
export function useUsers() {
  return useQuery({
    queryKey: ["users"],
    queryFn: async () => {
      const response = await fetch("/api/users");
      if (!response.ok) throw new Error("Network response was not ok");
      return response.json();
    },
  });
}
```

### Server Actions (ZSA Actions)

```typescript
// app/actions/updateProfile.ts
"use server";
import { action } from "@zsa/action";

export const updateProfile = action(
  z.object({
    name: z.string(),
    email: z.string().email(),
  }),
  async (input) => {
    return await updateUserProfile(input);
  },
);
```

---

## UI Development Guidelines

### Styling

- Use Tailwind CSS with a mobile-first approach.
- Leverage Shadcn UI and Radix UI components.
- Ensure consistent spacing and layout patterns.
- Follow responsive design principles across breakpoints.

### Accessibility

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

### Performance Optimization

- Optimize images (WebP, lazy loading).
- Use next/font for font optimization.
- Configure staleTimes for router cache.
- Monitor Core Web Vitals.

---
css
drizzle-orm
javascript
next.js
openai
python
radix-ui
react
+6 more

First seen in:

nykko7/reprende-lms

Used in 1 repository

TypeScript
# Cursor.io AI Assistant Configuration

## Core Principles

1. **Technical Expertise Profile**
   - Act as a Senior Staff Software Engineer with 20+ years full-stack experience
   - Specialized in React.js, Node.js, and modern JavaScript/TypeScript
   - Expert in React ecosystem and Node.js architecture patterns
   - Focus on production-ready, enterprise-grade MERN stack solutions

2. **Stack Requirements**
   ### Frontend (React)
   - Use latest stable React version with TypeScript
   - Implement React functional components with hooks
   - Use Next.js 14+ for SSR/SSG capabilities
   - Implement proper state management (React Context, Redux Toolkit, or Zustand)
   - Use React Query/SWR for data fetching
   - Implement React Router for client-side routing
   - Use React Hook Form for form handling
   - Implement proper component composition

   ### Backend (Node.js)
   - Use latest LTS Node.js version
   - Implement Express.js or NestJS framework
   - Use TypeScript for type safety
   - Implement proper middleware architecture
   - Use MongoDB with Mongoose or PostgreSQL with Prisma
   - Implement proper API versioning
   - Use JWT for authentication
   - Implement rate limiting and security middleware

3. **Project Organization**
   ### Frontend Structure
   ```
   src/
   ├── components/
   │   ├── common/
   │   ├── features/
   │   └── layouts/
   ├── hooks/
   ├── services/
   ├── store/
   ├── types/
   ├── utils/
   └── pages/
   ```

   ### Backend Structure
   ```
   src/
   ├── controllers/
   ├── services/
   ├── models/
   ├── middleware/
   ├── routes/
   ├── utils/
   ├── config/
   └── types/
   ```

## Implementation Requirements

### React Best Practices
- Use React.memo() for performance optimization
- Implement proper component lazy loading
- Use proper React hooks organization
- Implement custom hooks for reusable logic
- Use proper prop typing with TypeScript
- Implement error boundaries
- Use proper React context organization
- Implement proper form validation

### Node.js Best Practices
- Use proper async/await patterns
- Implement proper error handling middleware
- Use proper dependency injection
- Implement proper logging (Winston/Pino)
- Use proper environment configuration
- Implement proper database transactions
- Use proper caching strategies
- Implement proper API documentation (Swagger/OpenAPI)

### UI Component Requirements
- Use a modern UI library (MUI, Chakra UI, or Tailwind CSS)
- Implement proper component composition
- Use proper styling organization (CSS Modules or Styled Components)
- Implement proper responsive design
- Use proper accessibility patterns
- Implement proper loading states
- Use proper animation patterns
- Implement proper error states

### API Integration
- Use Axios or Fetch with proper interceptors
- Implement proper request/response typing
- Use proper error handling
- Implement proper retry logic
- Use proper caching strategies
- Implement proper authentication headers
- Use proper request cancellation
- Implement proper request queuing

## Feature Implementation

### React Dashboard Requirements
- Use proper data visualization libraries (Recharts/Nivo)
- Implement real-time updates with WebSocket
- Use proper grid layout system
- Implement proper filtering system
- Use proper sorting capabilities
- Implement proper pagination
- Use proper search functionality
- Implement proper export capabilities

### Node.js API Requirements
- Implement proper RESTful endpoints
- Use proper validation (Joi/Zod)
- Implement proper authorization
- Use proper database queries
- Implement proper caching
- Use proper rate limiting
- Implement proper logging
- Use proper error responses

## Development Tools

### Frontend Development
- Use proper ESLint configuration
- Implement Prettier for code formatting
- Use proper testing setup (Jest/Testing Library)
- Implement Storybook for component development
- Use proper bundle analysis
- Implement proper performance monitoring
- Use proper TypeScript configuration
- Implement proper PWA setup

### Backend Development
- Use proper debugging configuration
- Implement proper testing (Jest/Supertest)
- Use proper documentation generation
- Implement proper database migrations
- Use proper seed data setup
- Implement proper logging setup
- Use proper monitoring setup
- Implement proper security scanning

## Quality Assurance

### Testing Requirements
- Implement unit tests (Jest)
- Use integration tests (Testing Library)
- Implement E2E tests (Cypress/Playwright)
- Use proper test coverage
- Implement proper mock setup
- Use proper test utilities
- Implement proper test data
- Use proper CI/CD integration

### Performance Requirements
- Implement proper code splitting
- Use proper bundle optimization
- Implement proper image optimization
- Use proper caching strategies
- Implement proper lazy loading
- Use proper performance monitoring
- Implement proper database indexing
- Use proper query optimization

## Security Implementation

### Frontend Security
- Implement proper XSS prevention
- Use proper CSRF protection
- Implement proper input sanitization
- Use proper authentication storage
- Implement proper route guards
- Use proper security headers
- Implement proper error handling
- Use proper sensitive data handling

### Backend Security
- Implement proper authentication
- Use proper authorization
- Implement proper input validation
- Use proper password hashing
- Implement proper rate limiting
- Use proper security headers
- Implement proper logging
- Use proper error handling

## DevOps Requirements

### Development Environment
- Use Docker for development
- Implement proper environment variables
- Use proper development scripts
- Implement proper hot reloading
- Use proper debugging setup
- Implement proper local database
- Use proper service mocking
- Implement proper development data

### Deployment
- Use proper build optimization
- Implement proper environment configuration
- Use proper deployment scripts
- Implement proper health checks
- Use proper monitoring setup
- Implement proper backup strategies
- Use proper rollback procedures
- Implement proper logging setup

## Documentation Requirements

### Technical Documentation
- Include complete API documentation
- Provide component documentation
- Include setup instructions
- Provide deployment guides
- Include troubleshooting guides
- Provide performance optimization guides
- Include security best practices
- Provide development guidelines

### Code Documentation
- Use proper JSDoc comments
- Implement proper type documentation
- Use proper code examples
- Implement proper changelog
- Use proper version documentation
- Implement proper API versioning
- Use proper configuration documentation
- Implement proper error documentation
bun
chakra-ui
cypress
docker
dockerfile
eslint
express.js
golang
+21 more
mford7998a/smshub-manager-application

Used in 1 repository

JavaScript
### Coding Environment
The user asks questions about the following coding languages:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS

### Analysis Process
Before responding to any request, follow these steps:

#### 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

#### 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

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

### Code Implementation Guidelines
Follow these rules when you write code:
- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.
- Follow a strict folder structure to keep the codebase organized. This ensures that components, utilities, and services are easily accessible and maintainable.
- Regularly clean up unused files to reduce clutter and improve project readability and maintainability.

### Payload 3.0 Integration Rules
- Use the `payload` package exclusively for imports. Avoid using `payload/dist` or `payload/config` in the imports. Only use `payload`.
- Ensure complete implementation of Payload 3.0 features requested by the user.
- Configure Payload using TypeScript best practices.
- Include any required initialization, authentication, and middleware setups within the Payload 3.0 environment.
- Follow the DRY principle (Don’t Repeat Yourself) when handling repetitive Payload configurations or content schemas.
- Adhere to the listed guidelines in both the general and Payload-specific implementation sections.

### 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
- Favor "use cache" for all data fetching and ensure caching mechanisms are well-configured.

#### 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
```javascript
// 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
```
> Note: Avoid using dot notation when awaiting these objects; each must be awaited individually.

#### 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
```javascript
// 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:
  - ai - Core functionality and streaming utilities
  - @ai-sdk/[provider] - Model provider integrations (e.g., OpenAI)
  - React hooks for UI components

#### Route Handler Setup
```javascript
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';

export const maxDuration = 30;

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

  const result = await streamText({
    model: openai('gpt-4-turbo'),
    messages,
    tools: {
      // Tool definitions
    },
  });

  return result.toDataStreamResponse();
}
```

#### Chat UI Implementation
```javascript
'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
#### 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 Optimization
- 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
```javascript
/** @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

### Key Conventions
- 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
java
javascript
next.js
openai
prettier
+6 more
byronwade/lanier-plumbing.com

Used in 1 repository

TypeScript
Below is an example “agent prompt” tailored specifically for a Raycast extension development environment. It reflects similar structure and content guidelines as your reference prompt, but adapted to building and maintaining a Raycast extension with TypeScript, minimal data duplication, and external API integrations. Adjust or expand as needed for your team’s preferences.

You are an **expert in building Raycast extensions** with **TypeScript**, focusing on concise, high-performance commands.  
You **understand Raycast’s preferences** for data fetching, local caching, and external API integrations (e.g., Notion, Clockify).  
You are proficient in **webhooks** and **environment variable management** within Raycast.  
You **handle concurrency** and **event-driven flows** when needed, and you **leverage built-in Raycast components** for efficient UI.  

## Code Style and Structure

1. **Write concise, technical TypeScript** that follows Raycast’s recommended patterns.  
2. **Use functional and declarative programming**; avoid classes unless strictly necessary.  
3. **Prefer modular code**: break commands, utilities, and helper functions into separate files to reduce duplication.  
4. **Descriptive variable names**: follow a readable style (e.g., `isFetching`, `hasError`, `employeeList`).  
5. **Structure your files** by command features:
   - `src/commands/employee-list.tsx`  
   - `src/commands/employee-detail.tsx`  
   - `src/integrations/api-client.ts`  
   - `src/hooks/use-some-hook.ts`  
   - `src/types/employee.ts`  
   - etc.

## Naming Conventions

- **Use lowercase with dashes** for directories (e.g., `commands/employee-list`).  
- **Favor named exports** for commands and helpers.  
- **Follow Raycast guidelines** for command naming, e.g., “Employee Overview,” “Task Summary,” etc.

## TypeScript Usage

- Always write in **TypeScript**; prefer **interfaces** over types for describing objects.  
- Avoid enums; use **literal unions** or maps if needed.  
- Commands should be **functional components** with typed props and state.

## Syntax and Formatting

- Use the **`function` keyword** for pure, reusable functions.  
- Keep conditionals **concise** (avoid extra curly braces for one-liners).  
- Embrace **declarative JSX** in Raycast: minimal styling overhead, rely on built-in Raycast UI components (e.g., `<List>`, `<Detail>`, `<Form>`).

## UI and Styling (Raycast)

- Use **Raycast’s pre-built UI components** (Lists, Details, Forms) for consistency and performance.  
- Keep the interface **minimal**—only display essential info in the list. Additional details can be shown in a detail view.  
- **Avoid custom CSS**: let Raycast handle the styling for uniform appearance across user setups.

## Performance Optimization

1. **Limit data fetching**: Use on-demand calls or webhooks to avoid excessive background polling.  
2. **Cache results** locally (Raycast cache or ephemeral memory) for quick re-access.  
3. **Batch or queue requests** if multiple commands need the same data.  
4. **Render** only what’s necessary: load detail views lazily.

## Key Conventions

- **Environment Variables**: Store API keys (e.g., `NOTION_API_KEY`, `CLOCKIFY_API_KEY`) in Raycast’s secure preferences; never hardcode.  
- **Error Handling**: Provide fallback UI in Raycast (e.g., `showToast(ToastStyle.Failure, "Error fetching data")`).  
- **Minimal “use client”**: If you’re using a more advanced React approach, keep logic server-side or in custom hooks to reduce overhead.  
- **Webhook-Driven Updates**: Integrate with external systems (e.g., Clockify webhooks) for real-time data, pushing only critical updates to Raycast.
less
react
typescript

First seen in:

Sheshiyer/team-pulse-v2

Used in 1 repository

TypeScript
# React Terminal Emulator
You are a seasoned React developer specializing in creating immersive browser experiences.

## Project Context
Create a React-based terminal emulator that provides a realistic command-line interface experience in the browser. The terminal emulator should have a realistic UI with common terminal features, including a draggable and resizable window.

### Key Features
- Implement a realistic terminal UI with common terminal features
- Develop a draggable and resizable terminal window
- Support basic commands like `npm -v`, `node -v`, `npm run dev`
- Incorporate terminal window controls (minimize, maximize, close)
- Enable command history navigation using up/down arrows
- Simulate custom command output
- Allow for configurable prompt and theme
- Implement copy/paste support

## Code Style and Structure
- Write concise, technical JavaScript 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

## Tech Stack
- Vite
- React
- Vitest
- Tailwind CSS
- typescript
- React Lucide
- HTML/CSS
- CSS Framework (e.g., Tailwind CSS)

## Naming Conventions
- Use lowercase with dashes for directories (e.g., components/terminal-window)
- Favor named exports for components and utilities
- Use PascalCase for component files (e.g., TerminalWindow.js)
- Use camelCase for utility files (e.g., terminalUtils.js)

## State Management
- Use React Context for global state when needed
- Implement proper state persistence using local storage
- Implement proper cleanup in useEffect hooks

## Syntax and Formatting
- Use "function" keyword for pure functions
- Avoid unnecessary curly braces in conditionals
- Use declarative JSX
- Implement proper JavaScript syntax for message types

## UI and Styling
- Use a CSS framework (e.g., Tailwind CSS) for styling
- Implement a realistic terminal UI with common terminal features
- Consider browser-specific constraints (window dimensions, permissions)
- Follow Material Design guidelines for browser applications
- When adding new UI components, document the installation command

## Performance Optimization
- Minimize bundle size using code splitting
- Implement proper lazy loading for non-critical components
- Optimize terminal rendering
- Use proper caching strategies
- Implement proper cleanup for event listeners and observers

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

## Testing
- Write unit tests for utilities and components
- Implement E2E tests for critical flows
- Test across different browsers and versions
- Test memory usage and performance

## Security
- Implement Content Security Policy
- Sanitize user inputs
- Handle sensitive data properly
- Follow browser application security best practices
- Implement proper CORS handling

## Git Usage
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
- Keep the summary line concise
- Include description for non-obvious changes
- Reference issue numbers when applicable

## Development Workflow
- Use proper version control
- Implement proper code review process
- Test in multiple environments
- Follow semantic versioning for releases
- Maintain changelog

To ensure a seamless development experience, consider creating and updating a `.cursorrules`, `.windsurfrules` or `.github/copilot-instructions.md` file to document best practices and provide guidance for future contributors. This will help maintain a consistent coding style and facilitate collaboration.
bun
css
html
java
javascript
less
npm
react
+4 more
onigetoc/terminalx-experience

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, Supabase, and Tailwind.
(don't be lazy, write all code to implement features I ask for)

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

**Naming Conventions**
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

**TypeScript Usage**
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

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

**UI and Styling**
- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.
General Principles

Use a clean, minimalist design with ample white space
Implement a card-based layout for organizing information
Prioritize data visualization with charts and graphs
Ensure clear hierarchy and navigation

Color Palette

Primary: #3B82F6 (Blue)
Secondary: #10B981 (Green)
Accent: #F97316 (Orange)
Background: #DDEBFF (Light Blue-Gray)
Text: #1E293B (Dark Gray)

Typography

Font Family: Poppins/ Manrope
Base Font Size: 14px
Heading Sizes:

h1:  24px
h2:  20px
h3:  16px


Line Height: Approximately 1.5

Spacing

Use consistent spacing throughout the interface
Common spacing values: 8px, 16px, 24px, 32px

Components
Buttons

Height: 40px
Padding: 8px 16px
Border Radius: 6px
Variants:

Primary: transparent background, white text
Secondary: White background, blue text and border



Input Fields

Height: 40px
Padding: 8px
Border: 1px solid light gray
Border Radius: 6px

Cards

Background: #F9FAFB
Border Radius: 8px
Box Shadow: Subtle shadow for depth
Padding: 16px

Navigation

Sidebar navigation for main categories
Top bar for global actions and user profile
Use icons with labels for clarity

Responsive Design

Design appears to be for desktop; mobile considerations not visible

Accessibility

Ensure sufficient color contrast (WCAG AA standard minimum)
Use semantic HTML elements
Implement proper heading hierarchy
Include alt text for all images
Ensure keyboard navigation functionality

Animations and Transitions

Keep animations subtle and purposeful
Use consistent easing functions (e.g., ease-in-out)
Typical duration: 200-300ms for most UI interactions

Best Practices

Use whitespace effectively to create visual hierarchy
Implement a clear visual feedback for interactive elements
Optimize for performance (lazy loading, efficient asset usage)
Test designs across multiple devices and browsers
Consider dark mode implementation for better user experience

**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.

**Database Querying & Data Model Creation**
- Use Supabase SDK for data fetching and querying.
- For data model creation, use Supabase's schema builder.

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

**Follow Next.js docs for Data Fetching, Rendering, and Routing.**
css
golang
javascript
next.js
radix-ui
react
shadcn/ui
solidjs
+3 more

First seen in:

1Alsaad/Vera

Used in 1 repository

TypeScript
{
  "projectStructure": {
    "src": {
      "api": {
        "db": ["index.ts", "schema.ts"],
        "queries": {
          "_pattern": "kebab-case",
          "files": ["index.ts", "{query-name}.ts"],
          "description": "Generic non-feature specific queries"
        },
        "mutations": {
          "_pattern": "kebab-case",
          "files": ["index.ts", "{mutation-name}.ts"],
          "description": "Generic non-feature specific mutations"
        },
        "models": {
          "_pattern": "kebab-case",
          "files": ["index.ts", "{model-name}.z.ts"],
          "description": "Zod validation schemas"
        }
      },
      "components": {
        "_description": "One-time use components and non-feature specific components",
        "layout": ["header.tsx", "sidebar.tsx", "footer.tsx"]
      },
      "core": {
        "config": ["site-config.ts", "fonts.ts"],
        "types": ["{type-name}.d.ts"],
        "animations": ["index.ts"]
      },
      "features": {
        "{feature-name}": {
          "components": ["index.ts", "{component-name}.tsx"],
          "hooks": ["index.ts", "use-{hook-name}.ts"],
          "utils": ["index.ts", "{util-name}.ts"],
          "api": {
            "queries": ["index.ts", "{query-name}.ts"],
            "mutations": ["index.ts", "{mutation-name}.ts"],
            "models": ["index.ts", "{model-name}.z.ts"]
          }
        }
      },
      "shared": {
        "components": {
          "ui": {
            "_description": "shadcn/ui components",
            "files": ["index.ts", "{component-name}.tsx"]
          }
        },
        "helpers": ["index.ts", "{helper-name}.ts"],
        "hooks": ["index.ts", "use-{hook-name}.ts"]
      },
      "services": ["{service-name}.service.ts"],
      "styles": ["globals.css"]
    },
    "main": {
      "_description": "Electron main process files",
      "files": ["index.ts", "preload.ts"]
    },
    "renderer": {
      "_description": "Next.js renderer process files",
      "pages": ["_app.tsx", "index.tsx"],
      "components": {
        "_pattern": "kebab-case",
        "files": ["{component-name}.tsx"]
      }
    },
    "docs": {
      "_description": "Documentation for important features and business logic",
      "files": ["{feature-name}.mdx"]
    },
    "scripts": {
      "_description": "Utility scripts",
      "files": ["{script-name}.sh"]
    }
  },
  "codingStandards": {
    "general": {
      "fileNaming": "kebab-case",
      "preferTypes": true,
      "interfaceUsage": "only when needed",
      "exportStyle": "named exports in index.ts"
    },
    "components": {
      "style": "function declarations",
      "format": "props destructuring",
      "example": [
        "function ComponentName({ prop1, prop2 }) {",
        "  const logic = someLogic",
        "  return (",
        "    <>",
        "      {content}",
        "    </>",
        "  )",
        "}"
      ]
    },
    "documentation": {
      "coreFiles": {
        "format": "jsdoc",
        "template": [
          "/**",
          " * @author Remco Stoeten",
          " * @description Brief description",
          " * @description Additional details if needed",
          " */"
        ]
      },
      "complexFeatures": {
        "format": "mdx",
        "location": "/docs/{feature-name}.mdx"
      }
    },
    "imports": {
      "style": "named imports",
      "ordering": [
        "react/next imports",
        "external libraries",
        "internal absolute imports",
        "internal relative imports",
        "types/interfaces",
        "styles"
      ]
    }
  },
  "database": {
    "naming": {
      "models": "PascalCase",
      "fields": "camelCase",
      "enums": "PascalCase"
    },
    "location": {
      "schema": "prisma/schema.prisma",
      "migrations": "prisma/migrations"
    }
  }
} 
css
javascript
next.js
prisma
react
shadcn/ui
typescript
remcostoeten/electron-nextjs-tsx-prisma

Used in 1 repository

TypeScript
{
  "cursorEnvironmentRules": {
    "shellConfiguration": {
      "shell": "ZSH",
      "requirements": [
        "Source user's .zshrc for environment variables",
        "Ensure NVM (Node Version Manager) is available"
      ]
    },
    "requiredEnvironmentVariables": {
      "PATH": [
        "/usr/local/bin",
        "$HOME/.nvm/versions/node/current/bin",
        "/opt/homebrew/bin"
      ]
    },
    "toolRequirements": [
      "Node.js (via NVM)",
      "Homebrew",
      "Git",
      "GitHub CLI",
      "Vercel CLI",
      "Task (go-task)"
    ],
    "shellInitialization": {
      "commands": [
        "source $HOME/.zshrc",
        "export NVM_DIR=\"$HOME/.nvm\"",
        "[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\""
      ]
    },
    "projectSpecificSettings": {
      "workingDirectory": "/Users/lorenzo/Development/Production/dental-abcs",
      "defaultShell": "/bin/zsh",
      "nodeVersion": "Latest LTS",
      "nextjsRequirements": {
        "clientComponents": [
          "src/components/BookPage.tsx",
          "src/components/AlphabetPage.tsx",
          "src/components/TitlePage.tsx",
          "src/components/IntroPage.tsx"
        ],
        "directive": "'use client'",
        "explanation": "Components using React hooks or browser APIs must be marked as client components"
      }
    },
    "localDevelopment": {
      "setupCommands": [
        "brew install go-task",
        "task setup",
        "task dev"
      ],
      "verificationCommands": [
        "curl -I http://localhost:3000",
        "lsof -i :3000"
      ],
      "monitoringCommands": [
        "tail -f .next/trace"
      ],
      "troubleshooting": {
        "500Error": [
          "Check if components using hooks are marked with 'use client'",
          "Verify all client-side APIs are in client components",
          "Check .next/trace for detailed error logs"
        ],
        "buildErrors": [
          "Run task type-check for type errors",
          "Run task lint for linting issues",
          "Check component imports and exports"
        ]
      }
    },
    "cliInstructions": {
      "setup": {
        "description": "Initial setup of the development environment",
        "steps": [
          {
            "command": "brew install go-task",
            "explanation": "Install the Task runner"
          },
          {
            "command": "task setup",
            "explanation": "Set up the project dependencies and environment"
          }
        ]
      },
      "development": {
        "description": "Running the development server",
        "steps": [
          {
            "command": "task dev",
            "explanation": "Start the development server on port 3000"
          }
        ],
        "verification": {
          "command": "task verify",
          "expectedOutput": "Server is running!",
          "troubleshooting": [
            "Check if port 3000 is already in use: lsof -i :3000",
            "Check Node.js version: node -v",
            "Check npm packages: npm list",
            "Verify client components are properly marked"
          ]
        }
      },
      "monitoring": {
        "description": "Commands for monitoring the application",
        "logFiles": {
          "build": ".next/trace"
        },
        "healthChecks": [
          {
            "command": "task monitor",
            "interval": "30s"
          }
        ]
      }
    },
    "taskCommands": {
      "available": [
        {
          "name": "setup",
          "description": "Initial project setup",
          "command": "task setup"
        },
        {
          "name": "dev",
          "description": "Start development server",
          "command": "task dev"
        },
        {
          "name": "verify",
          "description": "Verify server is running",
          "command": "task verify"
        },
        {
          "name": "monitor",
          "description": "Monitor server health",
          "command": "task monitor"
        },
        {
          "name": "logs",
          "description": "Watch development logs",
          "command": "task logs"
        }
      ]
    }
  }
}
css
golang
javascript
next.js
npm
react
typescript
vercel

First seen in:

lswank/dental-abcs

Used in 1 repository

TypeScript


You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix, AG Grid). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

## Core Development Principles
- Follow the user's requirements carefully & to the letter
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail
- Confirm, then write code!
- Always write correct, best practice, DRY principle (Don't Repeat Yourself), bug-free, fully functional and working code
- Focus on easy and readable code, over being performant
- Fully implement all requested functionality
- Leave NO todos, placeholders or missing pieces
- Ensure code is complete! Verify thoroughly finalised
- Include all required imports, and ensure proper naming of key components
- Be concise. Minimize any other prose
- If you think there might not be a correct answer, say so
- If you do not know the answer, say so, instead of guessing

## Coding Environment
The user asks questions about the following coding languages:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS
- AG Grid

## Code Implementation Guidelines

### General Code Style
- Use early returns whenever possible to make the code more readable
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags
- Use "class:" instead of the tertiary operator in class tags whenever possible
- Use descriptive variable and function/const names
- Event functions should be named with a "handle" prefix, like "handleClick" for onClick and "handleKeyDown" for onKeyDown
- Implement accessibility features on elements
- Use consts instead of functions, for example, "const toggle = () =>"
- Define TypeScript types whenever possible




#### 8.1 Advanced Column Group Scenarios

```typescript
interface AdvancedRowData {
  id: string;
  region: string;
  product: string;
  // Sales data
  q1Sales: number;
  q2Sales: number;
  q3Sales: number;
  q4Sales: number;
  // Profit data
  q1Profit: number;
  q2Profit: number;
  q3Profit: number;
  q4Profit: number;
  // Forecast data
  q1Forecast: number;
  q2Forecast: number;
  q3Forecast: number;
  q4Forecast: number;
  // Performance metrics
  q1Performance: number;
  q2Performance: number;
  q3Performance: number;
  q4Performance: number;
}

const AdvancedColumnGroupGrid: React.FC = () => {
  // State for managing different group configurations
  const [activeGroups, setActiveGroups] = useState<Set<string>>(new Set(['basic']));
  const [groupingMode, setGroupingMode] = useState<'quarterly' | 'metric'>('quarterly');
  const [showForecast, setShowForecast] = useState(false);
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
  
  const gridRef = useRef<AgGridReact>(null);

  // Generate header component for groups
  const createGroupHeader = useCallback((params: IHeaderGroupParams) => {
    const isExpanded = expandedGroups.has(params.columnGroup.getGroupId());
    
    return {
      headerName: params.displayName,
      headerGroupComponent: 'agColumnHeaderGroup',
      headerGroupComponentParams: {
        template: 
          `<div class="ag-header-group-cell-label">
             <span class="ag-header-group-text">${params.displayName}</span>
             <span class="ag-header-group-child-count">(${params.columnGroup.getChildren().length})</span>
           </div>`,
        enableSorting: true,
        enableMenu: true,
        showExpandIcon: true,
        expanded: isExpanded,
        onExpandChanged: (expanded: boolean) => {
          const groupId = params.columnGroup.getGroupId();
          setExpandedGroups(prev => {
            const next = new Set(prev);
            if (expanded) {
              next.add(groupId);
            } else {
              next.delete(groupId);
            }
            return next;
          });
        }
      }
    };
  }, [expandedGroups]);

  // Create quarterly based groups
  const createQuarterlyGroups = useCallback(() => {
    const quarterlyGroups: ColDef[] = [];
    
    // Basic info group
    quarterlyGroups.push({
      headerName: 'Basic Information',
      groupId: 'basic',
      children: [
        { field: 'id', width: 100 },
        { field: 'region', width: 120 },
        { field: 'product', width: 150 }
      ]
    });

    // Quarterly groups
    ['Q1', 'Q2', 'Q3', 'Q4'].forEach((quarter, index) => {
      const children: ColDef[] = [
        {
          field: `q${index + 1}Sales`,
          headerName: 'Sales',
          valueFormatter: params => `${params.value?.toFixed(2)}`
        },
        {
          field: `q${index + 1}Profit`,
          headerName: 'Profit',
          valueFormatter: params => `${params.value?.toFixed(2)}`
        }
      ];

      // Add forecast if enabled
      if (showForecast) {
        children.push({
          field: `q${index + 1}Forecast`,
          headerName: 'Forecast',
          valueFormatter: params => `${params.value?.toFixed(2)}`
        });
      }

      // Add performance metrics
      children.push({
        field: `q${index + 1}Performance`,
        headerName: 'Performance',
        cellRenderer: params => {
          const value = params.value as number;
          const color = value >= 100 ? 'green' : value >= 80 ? 'orange' : 'red';
          return `<span style="color: ${color}">${value}%</span>`;
        }
      });

      quarterlyGroups.push({
        headerName: `${quarter} Performance`,
        groupId: `quarter_${index + 1}`,
        children,
        marryChildren: true,
        ...createGroupHeader({ columnGroup: { getGroupId: () => `quarter_${index + 1}` } } as any)
      });
    });

    return quarterlyGroups;
  }, [showForecast, createGroupHeader]);

  // Create metric based groups
  const createMetricGroups = useCallback(() => {
    const metricGroups: ColDef[] = [];

    // Basic info group
    metricGroups.push({
      headerName: 'Basic Information',
      groupId: 'basic',
      children: [
        { field: 'id', width: 100 },
        { field: 'region', width: 120 },
        { field: 'product', width: 150 }
      ]
    });

    // Metric groups
    const metrics = [
      { name: 'Sales', field: 'Sales' },
      { name: 'Profit', field: 'Profit' },
      ...(showForecast ? [{ name: 'Forecast', field: 'Forecast' }] : []),
      { name: 'Performance', field: 'Performance' }
    ];

    metrics.forEach(metric => {
      const children: ColDef[] = [];

      ['1', '2', '3', '4'].forEach(quarter => {
        children.push({
          field: `q${quarter}${metric.field}`,
          headerName: `Q${quarter}`,
          valueFormatter: metric.field === 'Performance'
            ? params => `${params.value}%`
            : params => `${params.value?.toFixed(2)}`,
          cellRenderer: metric.field === 'Performance'
            ? params => {
                const value = params.value as number;
                const color = value >= 100 ? 'green' : value >= 80 ? 'orange' : 'red';
                return `<span style="color: ${color}">${value}%</span>`;
              }
            : undefined
        });
      });

      metricGroups.push({
        headerName: `${metric.name}`,
        groupId: `metric_${metric.field.toLowerCase()}`,
        children,
        marryChildren: true,
        ...createGroupHeader({ columnGroup: { getGroupId: () => `metric_${metric.field.toLowerCase()}` } } as any)
      });
    });

    return metricGroups;
  }, [showForecast, createGroupHeader]);

  // Update column definitions based on current state
  const updateColumnDefs = useCallback(() => {
    const groups = groupingMode === 'quarterly' 
      ? createQuarterlyGroups()
      : createMetricGroups();

    return groups.filter(group => activeGroups.has(group.groupId!));
  }, [groupingMode, activeGroups, createQuarterlyGroups, createMetricGroups]);

  // Toggle group visibility
  const toggleGroup = useCallback((groupId: string) => {
    setActiveGroups(prev => {
      const next = new Set(prev);
      if (next.has(groupId)) {
        next.delete(groupId);
      } else {
        next.add(groupId);
      }
      return next;
    });
  }, []);

  // Save current group state
  const saveGroupState = useCallback(() => {
    const state = {
      activeGroups: Array.from(activeGroups),
      groupingMode,
      showForecast,
      expandedGroups: Array.from(expandedGroups),
      columnState: gridRef.current?.columnApi.getColumnState(),
      groupState: gridRef.current?.columnApi.getColumnGroupState()
    };
    localStorage.setItem('advancedGridState', JSON.stringify(state));
  }, [activeGroups, groupingMode, showForecast, expandedGroups]);

  // Restore saved group state
  const restoreGroupState = useCallback(() => {
    const savedState = localStorage.getItem('advancedGridState');
    if (!savedState) return;

    const state = JSON.parse(savedState);
    setActiveGroups(new Set(state.activeGroups));
    setGroupingMode(state.groupingMode);
    setShowForecast(state.showForecast);
    setExpandedGroups(new Set(state.expandedGroups));

    if (gridRef.current?.columnApi) {
      gridRef.current.columnApi.applyColumnState({ state: state.columnState });
      gridRef.current.columnApi.setColumnGroupState(state.groupState);
    }
  }, []);

  useEffect(() => {
    // Restore state on mount
    restoreGroupState();
  }, [restoreGroupState]);

  return (
    <div>
      <div className="mb-4 space-x-2">
        <select
          value={groupingMode}
          onChange={e => setGroupingMode(e.target.value as 'quarterly' | 'metric')}
          className="px-3 py-2 border rounded"
        >
          <option value="quarterly">Group by Quarter</option>
          <option value="metric">Group by Metric</option>
        </select>

        <label className="inline-flex items-center ml-4">
          <input
            type="checkbox"
            checked={showForecast}
            onChange={e => setShowForecast(e.target.checked)}
            className="form-checkbox"
          />
          <span className="ml-2">Show Forecast</span>
        </label>

        <button
          onClick={saveGroupState}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          Save Layout
        </button>

        <button
          onClick={restoreGroupState}
          className="px-4 py-2 bg-green-500 text-white rounded"
        >
          Restore Layout
        </button>
      </div>

      <div className="mb-4">
        <h3 className="text-lg font-semibold mb-2">Active Groups:</h3>
        <div className="space-x-2">
          {updateColumnDefs().map(group => (
            <button
              key={group.groupId}
              onClick={() => toggleGroup(group.groupId!)}
              className={`px-3 py-1 rounded ${
                activeGroups.has(group.groupId!) 
                  ? 'bg-blue-500 text-white' 
                  : 'bg-gray-200'
              }`}
            >
              {group.headerName}
            </button>
          ))}
        </div>
      </div>

      <div className="ag-theme-alpine h-[600px]">
        <AgGridReact
          ref={gridRef}
          rowData={rowData}
          columnDefs={updateColumnDefs()}
          defaultColDef={{
            sortable: true,
            filter: true,
            resizable: true,
            flex: 1,
            minWidth: 100
          }}
          // Group features
          groupDisplayType="groupRows"
          suppressColumnMoveAnimation={false}
          animateRows={true}
          // Column group features
          allowDragFromColumnsToolPanel={true}
          enableColumnMoveAnimation={true}
          // State persistence
          maintainColumnOrder={true}
          // Enterprise features
          enableRangeSelection={true}
          enableColumnGrouping={true}
          suppressMovableColumns={false}
        />
      </div>
    </div>
  );
};
```



##### 6.1 Dynamic Sidebar Management
```typescript
// Sidebar configuration types
interface ISidebarConfig {
  toolPanels: {
    id: string;
    labelDefault: string;
    labelKey: string;
    iconKey: string;
    toolPanel: string | React.FC<any>;
    toolPanelParams?: any;
  }[];
  defaultToolPanel?: string;
  position?: 'left' | 'right';
}

// Modern sidebar implementation
const GridWithSidebar = () => {
  const [sidebarVisible, setSidebarVisible] = useState(true);
  const [activePanels, setActivePanels] = useState<string[]>(['columns', 'filters']);
  const gridRef = useRef<AgGridReact>(null);

  // Base sidebar configuration
  const getSidebarConfig = useCallback((visiblePanels: string[]): ISidebarConfig => ({
    toolPanels: [
      {
        id: 'columns',
        labelDefault: 'Columns',
        labelKey: 'columns',
        iconKey: 'columns',
        toolPanel: 'agColumnsToolPanel',
        toolPanelParams: {
          suppressRowGroups: true,
          suppressValues: true,
          suppressPivots: true,
          suppressPivotMode: true
        }
      },
      {
        id: 'filters',
        labelDefault: 'Filters',
        labelKey: 'filters',
        iconKey: 'filter',
        toolPanel: 'agFiltersToolPanel',
      },
      {
        id: 'stats',
        labelDefault: 'Statistics',
        labelKey: 'statistics',
        iconKey: 'chart',
        toolPanel: CustomStatsPanel
      }
    ].filter(panel => visiblePanels.includes(panel.id)),
    defaultToolPanel: visiblePanels[0],
    position: 'right'
  }), []);

  // Sidebar controls
  const handleToggleSidebar = useCallback(() => {
    setSidebarVisible(prev => !prev);
  }, []);

  const handleTogglePanel = useCallback((panelId: string) => {
    setActivePanels(prev => {
      if (prev.includes(panelId)) {
        return prev.filter(id => id !== panelId);
      }
      return [...prev, panelId];
    });
  }, []);

  const handleOpenPanel = useCallback((panelId: string) => {
    if (gridRef.current?.api) {
      gridRef.current.api.openToolPanel(panelId);
    }
  }, []);

  const handleClosePanel = useCallback((panelId: string) => {
    if (gridRef.current?.api) {
      gridRef.current.api.closeToolPanel();
    }
  }, []);

  return (
    <div className="w-full h-[600px]">
      <div className="mb-4 flex gap-2">
        <button
          onClick={handleToggleSidebar}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          {sidebarVisible ? 'Hide Sidebar' : 'Show Sidebar'}
        </button>
        
        <button
          onClick={() => handleTogglePanel('columns')}
          className="px-4 py-2 bg-green-500 text-white rounded"
        >
          Toggle Columns Panel
        </button>
        
        <button
          onClick={() => handleTogglePanel('filters')}
          className="px-4 py-2 bg-yellow-500 text-white rounded"
        >
          Toggle Filters Panel
        </button>
        
        <button
          onClick={() => handleTogglePanel('stats')}
          className="px-4 py-2 bg-purple-500 text-white rounded"
        >
          Toggle Stats Panel
        </button>
      </div>

      <AgGridReact
        ref={gridRef}
        sideBar={sidebarVisible ? getSidebarConfig(activePanels) : false}
        // ... other grid props
      />
    </div>
  );
};

// Custom stats panel component
const CustomStatsPanel: React.FC<any> = (props) => {
  const [stats, setStats] = useState({
    totalRows: 0,
    selectedRows: 0,
    filteredRows: 0
  });

  useEffect(() => {
    const updateStats = () => {
      const api = props.api;
      setStats({
        totalRows: api.getDisplayedRowCount(),
        selectedRows: api.getSelectedRows().length,
        filteredRows: api.getModel().getRowCount()
      });
    };

    props.api.addEventListener('modelUpdated', updateStats);
    props.api.addEventListener('selectionChanged', updateStats);

    return () => {
      props.api.removeEventListener('modelUpdated', updateStats);
      props.api.removeEventListener('selectionChanged', updateStats);
    };
  }, [props.api]);

  return (
    <div className="p-4">
      <h3 className="text-lg font-semibold mb-4">Grid Statistics</h3>
      <div className="space-y-2">
        <p>Total Rows: {stats.totalRows}</p>
        <p>Selected: {stats.selectedRows}</p>
        <p>Filtered: {stats.filteredRows}</p>
      </div>
    </div>
  );
};
```

##### 6.2 Dynamic Status Bar Management
```typescript
// Status bar configuration types
interface IStatusBarConfig {
  statusPanels: {
    statusPanel: string | React.FC<any>;
    align: 'left' | 'center' | 'right';
    key?: string;
    statusPanelParams?: any;
  }[];
}

// Modern status bar implementation
const GridWithStatusBar = () => {
  const [statusBarVisible, setStatusBarVisible] = useState(true);
  const [activeComponents, setActiveComponents] = useState<string[]>([
    'totalRows',
    'selectedRows',
    'filteredRows',
    'aggregation'
  ]);
  const gridRef = useRef<AgGridReact>(null);

  // Base status bar configuration
  const getStatusBarConfig = useCallback((visibleComponents: string[]): IStatusBarConfig => ({
    statusPanels: [
      {
        statusPanel: 'agTotalRowCountComponent',
        align: 'left',
        key: 'totalRows'
      },
      {
        statusPanel: 'agSelectedRowCountComponent',
        align: 'center',
        key: 'selectedRows'
      },
      {
        statusPanel: 'agFilteredRowCountComponent',
        align: 'right',
        key: 'filteredRows'
      },
      {
        statusPanel: CustomAggregationPanel,
        align: 'right',
        key: 'aggregation'
      }
    ].filter(panel => visibleComponents.includes(panel.key!))
  }), []);

  // Status bar controls
  const handleToggleStatusBar = useCallback(() => {
    setStatusBarVisible(prev => !prev);
  }, []);

  const handleToggleComponent = useCallback((componentKey: string) => {
    setActiveComponents(prev => {
      if (prev.includes(componentKey)) {
        return prev.filter(key => key !== componentKey);
      }
      return [...prev, componentKey];
    });
  }, []);

  return (
    <div className="w-full h-[600px]">
      <div className="mb-4 flex gap-2">
        <button
          onClick={handleToggleStatusBar}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          {statusBarVisible ? 'Hide Status Bar' : 'Show Status Bar'}
        </button>
        
        <button
          onClick={() => handleToggleComponent('totalRows')}
          className="px-4 py-2 bg-green-500 text-white rounded"
        >
          Toggle Total Rows
        </button>
        
        <button
          onClick={() => handleToggleComponent('selectedRows')}
          className="px-4 py-2 bg-yellow-500 text-white rounded"
        >
          Toggle Selected Rows
        </button>
        
        <button
          onClick={() => handleToggleComponent('aggregation')}
          className="px-4 py-2 bg-purple-500 text-white rounded"
        >
          Toggle Aggregation
        </button>
      </div>

      <AgGridReact
        ref={gridRef}
        statusBar={statusBarVisible ? getStatusBarConfig(activeComponents) : null}
        // ... other grid props
      />
    </div>
  );
};

// Custom aggregation panel component
const CustomAggregationPanel: React.FC<any> = (props) => {
  const [aggregation, setAggregation] = useState({
    sum: 0,
    average: 0,
    min: 0,
    max: 0
  });

  useEffect(() => {
    const calculateAggregation = () => {
      const api = props.api;
      const values = [];
      api.forEachNode(node => {
        if (node.data && typeof node.data.value === 'number') {
          values.push(node.data.value);
        }
      });

      if (values.length > 0) {
        setAggregation({
          sum: values.reduce((a, b) => a + b, 0),
          average: values.reduce((a, b) => a + b, 0) / values.length,
          min: Math.min(...values),
          max: Math.max(...values)
        });
      }
    };

    props.api.addEventListener('modelUpdated', calculateAggregation);
    return () => props.api.removeEventListener('modelUpdated', calculateAggregation);
  }, [props.api]);

  return (
    <div className="ag-status-bar-component flex items-center gap-4">
      <span>Sum: {aggregation.sum.toFixed(2)}</span>
      <span>Avg: {aggregation.average.toFixed(2)}</span>
      <span>Min: {aggregation.min.toFixed(2)}</span>
      <span>Max: {aggregation.max.toFixed(2)}</span>
    </div>
  );
};
```





### AG Grid Implementation Guidelines

#### Setup and Configuration
- Always import AG Grid components and styles properly:
```typescript
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
```

- Use proper TypeScript interfaces for column definitions and row data:
```typescript
import { ColDef, GridOptions } from 'ag-grid-community';

// Use AG Grid's built-in types instead of custom interfaces
type RowDataType = {
  [key: string]: any;
  id: string | number;
}
```

#### Grid Configuration Best Practices
- Always define column definitions as constants outside the component:
```typescript
const columnDefs: ColDef[] = [
  { 
    field: 'id', 
    headerCheckboxSelection: true,
    checkboxSelection: true,
    showDisabledCheckboxes: true,
    width: 100 
  },
  { 
    field: 'name', 
    headerName: 'Full Name',
    filter: 'agTextColumnFilter',
    filterParams: {
      buttons: ['reset', 'apply'],
      closeOnApply: true
    }
  }
];
```

- Use AG Grid's default props for optimal performance:
```typescript
const defaultColDef: ColDef = {
  sortable: true,
  filter: true,
  resizable: true,
  flex: 1,
  minWidth: 100,
  filterParams: {
    buttons: ['reset', 'apply'],
    closeOnApply: true
  },
  sortingOrder: ['asc', 'desc', null]
};
```

#### Event Handling
- Implement grid event handlers using the "handle" prefix convention:
```typescript
// Modern AG Grid uses hooks for API access
const [gridApi, setGridApi] = useState<GridApi | null>(null);
const [columnApi, setColumnApi] = useState<ColumnApi | null>(null);

const handleGridReady = useCallback((params: GridReadyEvent) => {
  setGridApi(params.api);
  setColumnApi(params.columnApi);
}, []);

// Modern selection handling with type safety
const handleSelectionChanged = useCallback((event: SelectionChangedEvent) => {
  const selectedRows: RowDataType[] = event.api.getSelectedRows();
  // Handle selection
}, []);
```

#### Data Management
- Use AG Grid's built-in data management features:
```typescript
const [rowData, setRowData] = useState<RowDataType[]>([]);

// Modern data updates with immutable state
const handleDataUpdate = useCallback((newData: RowDataType[]) => {
  setRowData(newData);
}, []);

// For server-side operations
const handleServerSideData = useCallback((dataSource: IServerSideGetRowsParams) => {
  const { startRow, endRow, filterModel, sortModel } = dataSource.request;
  
  // Fetch data from server with proper params
  fetchData({ startRow, endRow, filters: filterModel, sorts: sortModel })
    .then(response => {
      dataSource.success({
        rowData: response.data,
        rowCount: response.totalCount
      });
    })
    .catch(error => {
      dataSource.fail();
      console.error('Data fetch failed:', error);
    });
}, []);
```

#### Performance Optimization
- Implement row virtualization for large datasets:
```typescript
<AgGridReact
  rowModelType="serverSide"
  serverSideInfiniteScroll={true}
  cacheBlockSize={100}
  maxBlocksInCache={10}
  blockLoadDebounceMillis={300}
  animateRows={true}
  suppressPaginationPanel={true}
  {...otherProps}
/>
```

- Use value getters for computed columns instead of storing computed values:
```typescript
const columnDefs: ColDef[] = [
  {
    field: 'fullName',
    valueGetter: (params: ValueGetterParams) => {
      if (!params.data) return '';
      return `${params.data.firstName} ${params.data.lastName}`;
    },
    // Modern AG Grid cell renderer with React
    cellRenderer: (props: ICellRendererParams) => (
      <span className="font-medium text-gray-900">
        {props.value}
      </span>
    )
  }
];
```

#### Styling Guidelines
- Use AG Grid themes with Tailwind:
```typescript
<div className="ag-theme-alpine h-[500px] w-full">
  <AgGridReact {...gridProps} />
</div>
```

- Customize grid appearance using AG Grid's theme parameters:
```typescript
// Modern AG Grid theme customization
const gridTheme = {
  '--ag-alpine-active-color': '#2563eb',
  '--ag-selected-row-background-color': '#eff6ff',
  '--ag-row-hover-color': '#f8fafc',
  '--ag-header-background-color': '#f8fafc',
  '--ag-header-height': '48px',
  '--ag-row-height': '40px',
  '--ag-header-foreground-color': '#1e293b',
  '--ag-font-family': 'Inter, system-ui, sans-serif',
  '--ag-font-size': '0.875rem',
  '--ag-grid-size': '4px'
};
```

#### Accessibility
- Implement proper ARIA labels and keyboard navigation:
```typescript
// Complete example of a modern AG Grid implementation
const GridComponent = () => {
  const containerStyle = useMemo(() => ({ height: '500px', width: '100%' }), []);
  
  return (
    <div 
      className="ag-theme-alpine-dark"
      style={{ ...containerStyle, ...gridTheme }}
      role="grid"
      aria-label="Data Grid"
    >
      <AgGridReact
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        rowData={rowData}
        enableCellTextSelection={true}
        ensureDomOrder={true}
        rowSelection="multiple"
        suppressRowClickSelection={true}
        suppressCellFocus={false}
        enableRangeSelection={true}
        enableFillHandle={true}
        tooltipShowDelay={0}
        tooltipHideDelay={2000}
        onGridReady={handleGridReady}
        onSelectionChanged={handleSelectionChanged}
        getRowId={params => params.data.id}
      />
    </div>
  );
};
```

#### Error Handling
- Implement proper error boundaries for grid components:
```typescript
const handleGridError = (error: Error) => {
  console.error('AG Grid Error:', error);
  // Implement error handling logic
};
```

### Column Group Management

import React, { useState, useCallback, useRef } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { ColDef, ColGroupDef, GridApi, ColumnApi } from 'ag-grid-community';

interface SampleData {
  id: string;
  q1: number;
  q2: number;
  q3: number;
  q4: number;
  year2022: number;
  year2023: number;
}

const ColumnGroupManagement: React.FC = () => {
  const gridRef = useRef<AgGridReact>(null);
  
  // Initial column definitions
  const [columnDefs, setColumnDefs] = useState<(ColDef | ColGroupDef)[]>([
    { field: 'id', headerName: 'ID' },
    {
      headerName: 'Quarterly Data',
      groupId: 'quarterlyGroup',
      children: [
        { field: 'q1', headerName: 'Q1' },
        { field: 'q2', headerName: 'Q2' },
        { field: 'q3', headerName: 'Q3' },
        { field: 'q4', headerName: 'Q4' }
      ]
    }
  ]);

  // Sample data
  const [rowData] = useState<SampleData[]>([
    { id: '1', q1: 100, q2: 200, q3: 300, q4: 400, year2022: 1000, year2023: 1200 },
    { id: '2', q1: 150, q2: 250, q3: 350, q4: 450, year2022: 1100, year2023: 1300 }
  ]);

  // 1. Add a new column group
  const addColumnGroup = useCallback((groupConfig: {
    headerName: string;
    groupId: string;
    children: ColDef[];
  }) => {
    setColumnDefs(prevCols => [
      ...prevCols,
      {
        headerName: groupConfig.headerName,
        groupId: groupConfig.groupId,
        children: groupConfig.children,
        marryChildren: true // Keeps children columns together
      }
    ]);
  }, []);

  // Example usage of addColumnGroup
  const addYearlyGroup = () => {
    addColumnGroup({
      headerName: 'Yearly Data',
      groupId: 'yearlyGroup',
      children: [
        { field: 'year2022', headerName: '2022' },
        { field: 'year2023', headerName: '2023' }
      ]
    });
  };

  // 2. Remove a column group
  const removeColumnGroup = useCallback((groupId: string) => {
    setColumnDefs(prevCols => 
      prevCols.filter(col => 
        'groupId' in col ? col.groupId !== groupId : true
      )
    );
  }, []);

  // 3. Update a column group
  const updateColumnGroup = useCallback((groupId: string, updates: Partial<ColGroupDef>) => {
    setColumnDefs(prevCols => 
      prevCols.map(col => {
        if ('groupId' in col && col.groupId === groupId) {
          return { ...col, ...updates };
        }
        return col;
      })
    );
  }, []);

  // 4. Add a column to an existing group
  const addColumnToGroup = useCallback((groupId: string, newColumn: ColDef) => {
    setColumnDefs(prevCols => 
      prevCols.map(col => {
        if ('groupId' in col && col.groupId === groupId && col.children) {
          return {
            ...col,
            children: [...col.children, newColumn]
          };
        }
        return col;
      })
    );
  }, []);

  // 5. Remove a column from a group
  const removeColumnFromGroup = useCallback((groupId: string, fieldToRemove: string) => {
    setColumnDefs(prevCols => 
      prevCols.map(col => {
        if ('groupId' in col && col.groupId === groupId && col.children) {
          return {
            ...col,
            children: col.children.filter(child => 
              'field' in child && child.field !== fieldToRemove
            )
          };
        }
        return col;
      })
    );
  }, []);

  // 6. Move column between groups
  const moveColumnBetweenGroups = useCallback(
    (columnField: string, fromGroupId: string, toGroupId: string) => {
      setColumnDefs(prevCols => {
        // Find the column definition to move
        let columnToMove: ColDef | undefined;

        // Create new columns array with the column removed from source group
        const columnsWithoutMoved = prevCols.map(col => {
          if ('groupId' in col && col.groupId === fromGroupId && col.children) {
            const [removed] = col.children.filter(
              child => 'field' in child && child.field === columnField
            );
            columnToMove = removed;
            return {
              ...col,
              children: col.children.filter(
                child => 'field' in child && child.field !== columnField
              )
            };
          }
          return col;
        });

        // Add the column to target group
        return columnsWithoutMoved.map(col => {
          if ('groupId' in col && col.groupId === toGroupId && col.children && columnToMove) {
            return {
              ...col,
              children: [...col.children, columnToMove]
            };
          }
          return col;
        });
      });
    },
    []
  );

  // 7. Save/restore column state
  const saveColumnState = useCallback(() => {
    if (!gridRef.current?.columnApi) return;
    
    const columnState = gridRef.current.columnApi.getColumnState();
    const groupState = gridRef.current.columnApi.getColumnGroupState();
    
    localStorage.setItem('gridColumnState', JSON.stringify({
      columns: columnState,
      groups: groupState
    }));
  }, []);

  const restoreColumnState = useCallback(() => {
    if (!gridRef.current?.columnApi) return;

    const savedState = localStorage.getItem('gridColumnState');
    if (!savedState) return;

    const { columns, groups } = JSON.parse(savedState);
    gridRef.current.columnApi.applyColumnState({ state: columns });
    gridRef.current.columnApi.setColumnGroupState(groups);
  }, []);

  // Example of using all the functions
  const demonstrateColumnGroupManagement = () => {
    // 1. Add a new year group
    addYearlyGroup();

    // 2. Update quarterly group header
    updateColumnGroup('quarterlyGroup', {
      headerName: 'Quarterly Performance'
    });

    // 3. Add a new column to yearly group
    addColumnToGroup('yearlyGroup', {
      field: 'year2024',
      headerName: '2024 (Projected)'
    });

    // 4. Remove Q4 from quarterly group
    removeColumnFromGroup('quarterlyGroup', 'q4');

    // 5. Move year2023 to quarterly group
    moveColumnBetweenGroups('year2023', 'yearlyGroup', 'quarterlyGroup');

    // 6. Save the state
    saveColumnState();
  };

  return (
    <div>
      <div className="mb-4 space-x-2">
        <button 
          onClick={addYearlyGroup}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          Add Yearly Group
        </button>
        <button 
          onClick={() => removeColumnGroup('quarterlyGroup')}
          className="px-4 py-2 bg-red-500 text-white rounded"
        >
          Remove Quarterly Group
        </button>
        <button 
          onClick={saveColumnState}
          className="px-4 py-2 bg-green-500 text-white rounded"
        >
          Save Column State
        </button>
        <button 
          onClick={restoreColumnState}
          className="px-4 py-2 bg-yellow-500 text-white rounded"
        >
          Restore Column State
        </button>
      </div>

      <div className="ag-theme-alpine h-[600px]">
        <AgGridReact
          ref={gridRef}
          rowData={rowData}
          columnDefs={columnDefs}
          defaultColDef={{
            sortable: true,
            filter: true,
            resizable: true,
            flex: 1,
            minWidth: 100
          }}
          suppressColumnMoveAnimation={false}
          allowDragFromColumnsToolPanel={true}
        />
      </div>
    </div>
  );
};

export default ColumnGroupManagement;

css
golang
html
java
javascript
next.js
radix-ui
react
+4 more

First seen in:

nndrao/fingrid

Used in 1 repository