npm package: @mijull/naturalui-editor
Description: Drop-in visual UI editor for React applications with AI-powered modifications
Latest version: 0.2.6

# Natural UI Editor

Drop-in visual UI editor for React applications with AI-powered modifications. Click any component, describe changes in natural language, and create pull requests instantly.

## Features

- 🎯 **Visual Component Selection** - Click any element to inspect and edit
- 🤖 **AI-Powered Modifications** - Describe changes in natural language
- 📝 **Live Code Preview** - See diffs before applying
- 🔄 **Direct File Writing** - Changes apply immediately with HMR
- 🚀 **GitHub Integration** - Create PRs directly from the UI
- ⚡ **Zero Config** - Works with any React + Vite project

## Installation

```bash
npm install @mijull/naturalui-editor
```

**Requirements:**
- Tailwind CSS 3+ or 4+ (must be installed in your project)
- Vite 5+, 6+, or 7+
- React 18+ or 19+

**For cloud deployment** (to enable `__debugSource`):
```bash
npm install -D @babel/plugin-transform-react-jsx
```

## Quick Start

### 1. Install and Configure Tailwind CSS (if not already installed)

```bash
npm install -D tailwindcss @tailwindcss/vite
```

Add Tailwind to your `vite.config.ts`:
```ts
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
  plugins: [react(), tailwindcss()]
})
```

Add to your main CSS file (`src/index.css`):
```css
@import "tailwindcss";
@source "../node_modules/@mijull/naturalui-editor/src/**/*.{ts,tsx}";
@import "../node_modules/@mijull/naturalui-editor/src/index.css";
```

This tells Tailwind to:
1. Load Tailwind base styles
2. Scan the Natural UI Editor source files for Tailwind classes
3. Import the editor's custom CSS (inspector highlights, etc.)

### 2. Initialize Configuration

```bash
npx natural-ui init
```

This creates `.env` and `.env.example` files.

### 3. Configure API Keys and GitHub

Update `.env`:
```env
VITE_GEMINI_API_KEY=your_gemini_api_key_here
VITE_GITHUB_TOKEN=your_github_token_here
VITE_GITHUB_OWNER=your-username
VITE_GITHUB_REPO=your-repo-name
VITE_GITHUB_BASE_BRANCH=main
```

- Get Gemini API key: https://aistudio.google.com/apikey
- Get GitHub token: https://github.com/settings/tokens (needs `repo` scope)

### 4. Configure Vite (For Local Dev Only)

For local development, no special configuration needed:

```ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  plugins: [react(), tailwindcss()],
});
```

**For Cloud Deployment** (to enable `__debugSource` on deployed apps):

1. Install Babel plugin:
   ```bash
   npm install -D @babel/plugin-transform-react-jsx-development
   ```

2. Update `vite.config.ts`:
   ```ts
   export default defineConfig({
     plugins: [
       react({
         babel: {
           plugins: [
             ['@babel/plugin-transform-react-jsx', { development: true, runtime: 'automatic' }]
           ]
         }
       }),
       tailwindcss()
     ],
   });
   ```

### 5. Add Component to Your App

```tsx
import { NaturalUIEditor } from '@mijull/naturalui-editor';

function App() {
  return (
    <>
      <YourApp />
      {import.meta.env.DEV && <NaturalUIEditor />}
    </>
  );
}
```

## Usage

### Local Development

1. Start your dev server: `npm run dev`
2. Click the **"Edit UI"** button (bottom right)
3. Hover over elements to see their source location
4. Click an element to open the editor
5. Describe your changes in natural language
6. Preview the AI-generated diff
7. Apply changes or create a PR

### Cloud Deployment (for non-technical users)

For production-like environments where non-technical users can make changes:

1. **Deploy with Dev Build**: Configure your project to deploy with `__debugSource` enabled
2. **User Workflow**:
   - User visits deployed app
   - Clicks element → describes changes
   - Clicks **"Preview in Cloud"**
   - Branch is created, Vercel/Netlify auto-deploys
   - Reviews changes on preview URL (~60s)
   - Either **"Create PR"** or **"Discard & Delete Branch"**

**Configuration for Cloud Deployment:**

```ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [
          ['@babel/plugin-transform-react-jsx-development', { runtime: 'automatic' }]
        ]
      }
    }),
    tailwindcss()
  ],
});
```

The Babel plugin uses React's development JSX transform which includes `__debugSource` metadata.

## How It Works

### Architecture

The Natural UI Editor uses a **fully client-side architecture** - all GitHub and AI API calls are made directly from the browser:

1. **Source Mapping** - Uses React's `__debugSource` to map DOM elements to source files
2. **Code Fetching** - Fetches source code from GitHub API (or local Vite endpoint in dev)
3. **AI Generation** - Sends context directly to Gemini AI API with your instruction
4. **Live Preview** - Shows diff with Monaco editor
5. **GitHub Operations** - Creates branches, commits, and PRs directly via GitHub REST API from browser

### Local Development Mode

- Changes can optionally be written to local filesystem via Vite dev server
- Hot Module Replacement (HMR) for instant feedback
- Backup files created automatically

### Cloud Deployment Mode

1. **Build Configuration** - Deploy with `keepDebugSource: true` to preserve React's source mapping
2. **Visual Editing** - Non-technical users click elements and describe changes
3. **Branch Creation** - Browser calls GitHub API directly to create branch with changes
4. **Auto-Deploy** - Vercel/Netlify automatically deploys branch preview (~60s)
5. **Review & Approve** - User reviews in real environment
6. **PR or Discard** - Either create PR or delete preview branch

**Key Benefits:**
- No backend required - works on any static host
- Direct API calls from browser (HTTPS)
- Secure for preview/staging environments with proper token scoping
- Works on Vercel, Netlify, GitHub Pages, etc.

## Requirements

- React 18+ or 19+
- Vite 5+, 6+, or 7+
- Node.js 18+ (for development)
- For cloud deployment: Vercel/Netlify with GitHub integration

## Development Mode Only (Local)

The local development tool relies on:
- React's `__debugSource` (only available with dev transforms)
- Vite's dev server for file operations
- Local file system access

## Cloud Deployment Mode

For deployed environments:
- Use `naturalUIPlugin({ keepDebugSource: true })` 
- Build with dev mode: `vite build --mode preview`
- Connect GitHub repo to Vercel/Netlify for auto-deploys
- Optionally set `VITE_VERCEL_TOKEN` for deployment status polling

~~The Natural UI Editor no longer requires a custom Vite plugin.~~ Simply configure the React plugin with `jsxDev: true`:

```ts
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  plugins: [
    react({
      jsxRuntime: 'automatic',
      jsxDev: true, // Preserves React's __debugSource for element mapping
    }),
    tailwindcss(),
  ]
});
```

**Why `jsxDev: true`?**
- Keeps `__debugSource` metadata on React elements
- Required for the editor to map DOM elements to source files
- Safe for preview/staging environments
- Slightly larger bundle size (~5-10% increase)
- Configures esbuild to use `jsxDev: true` (keeps source mapping)
- That's it! All API calls (GitHub, Gemini) are made directly from the browser

## Security Considerations

Since the package makes API calls directly from the browser:

- **GitHub Token** - Include in `.env` (exposed in browser bundle)
  - Only use for preview/staging environments, NOT production
  - Use fine-grained tokens scoped to specific repos
  - Rotate tokens regularly
  
- **Gemini API Key** - Include in `.env` (exposed in browser bundle)
  - Consider usage limits and quotas
  - Monitor API usage

**Best Practices:**
- Only deploy the editor to password-protected preview/staging environments
- Use separate GitHub repos for preview branches
- Set up token restrictions in GitHub (repo-specific, branch protection)
- Monitor GitHub API usage and set alerts

## Tech Stack

- React + TypeScript
- Vite Plugin API
- Google Gemini AI
- Monaco Editor
- Tailwind CSS
- GitHub REST API

## License

MIT

## Contributing

Contributions welcome! Please open an issue or PR.