npm package: @renderkit/editor
Description: AI-powered React component editor for Next.js - edit your components with natural language in development mode. Requires @renderkit/editor-service to be running.
Author: Jesse Halpern
Latest version: 1.3.1

# RenderKit Editor

> AI-powered React component editor for Next.js - chat with your UI in development mode

## Overview

RenderKit Editor is a development tool that lets you interact with your React components using natural language. Click any component in your Next.js app and chat with an AI agent to make changes, add features, or refactor code - all while your app is running.

## Features

- 💬 **Chat Interface**: Natural conversation with AI about your components
- 🎯 **Click-to-Select**: Click any component in your Next.js app to start editing
- 🤖 **AI Agent**: Powered by Claude Agent SDK for intelligent code modifications
- 🔍 **Smart Detection**: Automatically finds exact component locations in your source code
- 📍 **Source Maps**: Works with both Server Components and Client Components using Turbopack source maps
- 🎨 **Syntax Highlighting**: Beautiful code preview with theme-aware syntax highlighting
- 📜 **Task History**: Track all changes made by the AI agent
- 🔄 **Hot Reload**: See changes immediately in your browser
- 🛡️ **Safe**: Only works in development mode

## Architecture

The package is split into two parts:

1. **@renderkit/editor** (this package): Client-side React components and UI
2. **@renderkit/editor-service**: Background service that handles file operations, AI processing, and code analysis

The client communicates with the service via HTTP/WebSocket on port 3456.

## Installation

```bash
npm install @renderkit/editor
# or
pnpm add @renderkit/editor
# or
yarn add @renderkit/editor
```

## Setup

### 1. Start the AI Editor Service

The AI editor requires a background service to handle file operations and AI processing. The service is located in the `packages/editor-service` directory of this monorepo.

**Environment Variables**

Create a `.env` file in the service directory:

```env
ANTHROPIC_API_KEY=sk-ant-api03-...
NODE_ENV=development
NEXT_PUBLIC_AI_EDITOR_ENABLED=true
```

**Run the Service**

```bash
cd packages/editor-service
pnpm install
pnpm dev
```

The service will start on port 3456 by default.

### 2. Add to Your Next.js App

Wrap your root layout with the `AIEditorProvider`:

```tsx
// app/layout.tsx
import { AIEditorProvider } from "@renderkit/editor";
import "@renderkit/editor/styles";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <AIEditorProvider theme="dark">
          {children}
        </AIEditorProvider>
      </body>
    </html>
  );
}
```

That's it! No API routes needed - the package communicates directly with the service.

## Usage

### Basic Chat Workflow

1. **Enable AI Editor**: Press `Ctrl+Shift+E` (or `Cmd+Shift+E` on Mac)
2. **Open Chat Panel**: Click the chat button in the bottom-right corner
3. **Select Component**: Click the component selector tool and click any component
4. **Chat**: Describe what you want to change, add, or refactor
5. **Apply**: The AI agent will make the changes automatically

### Example Prompts

**Simple Changes**
```
"Change the button color to blue"
"Add a shadow to this card"
"Make the heading text larger"
```

**Adding Features**
```
"Add a loading state to this button"
"Add error handling to this form"
"Make this component responsive"
```

**Refactoring**
```
"Extract this form into a separate component"
"Convert this to use TypeScript"
"Add proper prop types to this component"
```

## API Reference

### Client Components

#### `AIEditorProvider`

Main provider component that wraps your app.

```tsx
import { AIEditorProvider } from "@renderkit/editor";

<AIEditorProvider theme="dark" | "light">
  {children}
</AIEditorProvider>
```

**Props:**
- `theme?: "dark" | "light"` - UI theme (default: "dark")
- `children: ReactNode` - Your app content

#### `ChatPanel`

Standalone chat panel component for advanced use cases.

```tsx
import { ChatPanel } from "@renderkit/editor";

<ChatPanel
  isExpanded={true}
  onToggle={() => {}}
  activeTool={null}
  onToolChange={(tool) => {}}
  attachedContext={null}
  onClearContext={() => {}}
  theme="dark"
/>
```

#### `ControlPill`

Floating control button for toggling the editor.

```tsx
import { ControlPill } from "@renderkit/editor";

<ControlPill
  isEditorEnabled={true}
  onToggle={() => {}}
  theme="dark"
/>
```

### Types

```tsx
import type {
  SourceLocation,
  ElementContext,
  ChatPanelProps,
  ControlPillProps,
  AttachedContext,
  ToolType,
  TaskHistoryItem,
} from "@renderkit/editor";
```

### Service Configuration

```tsx
import { getServiceUrl, buildServiceUrl } from "@renderkit/editor";

// Get the service base URL (auto-detects localhost or deployed)
const serviceUrl = getServiceUrl(); // "http://localhost:3456"

// Build full endpoint URL
const endpoint = buildServiceUrl("api/chat"); // "http://localhost:3456/api/chat"
```

## How It Works

### 1. Component Detection
Uses React Fiber's `_debugStack` to capture component hierarchy and location when you click an element.

### 2. Source Mapping
Resolves compiled positions to original source using Turbopack source maps. This works for both Server Components and Client Components.

### 3. AI Agent
The service runs a Claude Agent (via Claude Agent SDK) that can:
- Read and analyze your source code
- Make precise edits using AST parsing (Babel)
- Understand context from previous changes
- Handle multi-step tasks autonomously

### 4. Live Updates
Changes are written to your source files, and Next.js's hot reload automatically updates the browser.

## Service Architecture

The `@renderkit/editor-service` package handles:

- **File Operations**: Reading and writing source files safely
- **Source Map Resolution**: Mapping compiled code positions to original source
- **AST Parsing**: Using Babel to analyze and modify code precisely
- **AI Processing**: Running Claude Agent SDK with access to your codebase
- **WebSocket Streaming**: Real-time chat updates and tool execution feedback

## Requirements

- **Next.js**: 15.0.0 or higher
- **React**: 18.0.0 or higher
- **Node.js**: 18.0.0 or higher
- **Anthropic API Key**: Required for AI functionality
- **AI Editor Service**: Must be running on port 3456

## Development Only

This package is designed for development only. The service will refuse to run in production (`NODE_ENV=production`), and all file operations are restricted to your project directory.

## Configuration

### Service URL

By default, the package auto-detects the service URL:
- **Local development**: `http://localhost:3456`
- **Deployed**: `https://${hostname}:3456`

You can override this by setting `NEXT_PUBLIC_AI_EDITOR_SERVICE_URL` in your environment variables.

### Keyboard Shortcuts

- `Ctrl+Shift+E` / `Cmd+Shift+E` - Toggle AI Editor
- `Ctrl+Enter` / `Cmd+Enter` - Send chat message

## Troubleshooting

### Service Connection Issues

Make sure the AI editor service is running:
```bash
cd packages/editor-service
pnpm dev
```

Check the console for errors connecting to `http://localhost:3456`.

### Component Not Detected

- Ensure you're running Next.js dev server (`npm run dev`)
- Only React components are selectable (not plain HTML)
- Server Components and Client Components are both supported

### Source Mapping Issues

- Ensure `.next/dev/` directory exists with source maps
- Turbopack generates `.map` files automatically in development
- Check that your component has valid `_debugStack` in React Fiber

### API Key Issues

- Verify `ANTHROPIC_API_KEY` is set in the service's `.env` file
- Restart the service after adding environment variables
- Check service logs for authentication errors

## Examples

Check out the demo apps in the monorepo:
- `apps/dashboard` - Full-featured example with the AI editor
- `demos/blog` - Blog demo with AI editor
- `demos/e-commerce` - E-commerce demo with AI editor

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT © Jesse Halpern

## Links

- [GitHub Repository](https://github.com/anon-dot-com/next-ai-editor)
- [Issue Tracker](https://github.com/anon-dot-com/next-ai-editor/issues)
- [Anthropic API](https://www.anthropic.com)
- [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk)