npm package: @m0rphic/jsx-render
Description: Dynamic JSX rendering with Tailwind CSS - render AI-generated UI safely
Author: m0rphic
Latest version: 0.1.2

# @m0rphic/jsx-render

Dynamic JSX generation with Claude AI and Tailwind CSS. Generate personalized, adaptive UI components based on user behavior.

## Features

- **AI-Powered UI Generation**: Use Claude to generate React components dynamically
- **Tailwind CSS Styling**: Full support for Tailwind utility classes
- **Behavior-Based Personalization**: Track user behavior and generate personalized UIs
- **Safe Rendering**: Secure JSX rendering with validation and sanitization
- **React Hooks & Components**: Easy-to-use React integration
- **TypeScript First**: Full type safety throughout

## Installation

```bash
npm install @m0rphic/jsx-render
# or
pnpm add @m0rphic/jsx-render
# or
yarn add @m0rphic/jsx-render
```

## Quick Start

### 1. Basic Usage

```tsx
import { generateUI, renderJSX } from '@m0rphic/jsx-render';

// Generate UI with Claude
const result = await generateUI('Create a login form with email and password fields');

// Render to React
const LoginForm = () => {
  const handlers = {
    handleSubmit: (e) => {
      e.preventDefault();
      console.log('Form submitted');
    },
  };

  return renderJSX(result.ui, { handlers });
};
```

### 2. React Integration

```tsx
import {
  AdaptiveUIProvider,
  GeneratedUI,
} from '@m0rphic/jsx-render/react';

function App() {
  const handlers = {
    handleLogin: () => console.log('Login clicked'),
    handleSignup: () => console.log('Signup clicked'),
  };

  return (
    <AdaptiveUIProvider
      userId="user-123"
      handlers={handlers}
      enableTracking={true}
    >
      <GeneratedUI
        prompt="Create a hero section for a crypto wallet app"
        personalized={true}
        cacheKey="hero-section"
      />
    </AdaptiveUIProvider>
  );
}
```

### 3. With Behavior Tracking

```tsx
import {
  useBehaviorTracking,
  useGeneratedUI,
} from '@m0rphic/jsx-render/react';

function Dashboard() {
  const { profile, trackFeature } = useBehaviorTracking({
    userId: 'user-123',
    autoTrack: true,
  });

  const { ui, isLoading } = useGeneratedUI({
    prompt: 'Create a dashboard with quick actions',
    userBehavior: profile,
  });

  if (isLoading) return <div>Loading...</div>;

  return <div onClick={() => trackFeature('dashboard-view')}>{ui}</div>;
}
```

## Core Concepts

### JSX Element Structure

The SDK uses a structured JSON format to represent JSX elements:

```typescript
interface JSXElement {
  tag: string;           // HTML tag or component name
  className?: string;    // Tailwind CSS classes
  props?: object;        // HTML/React props
  handlers?: object;     // Event handler references
  children?: JSXChildren; // Nested elements or text
}
```

Example:

```json
{
  "tag": "div",
  "className": "flex flex-col gap-4 p-6 bg-white rounded-xl shadow-lg",
  "children": [
    {
      "tag": "h1",
      "className": "text-2xl font-bold text-gray-900",
      "children": "Welcome"
    },
    {
      "tag": "button",
      "className": "px-4 py-2 bg-blue-500 text-white rounded-lg",
      "handlers": { "onClick": "handleClick" },
      "children": "Get Started"
    }
  ]
}
```

### Security

The renderer includes multiple security layers:

1. **Tag Whitelist**: Only allowed HTML tags can be rendered
2. **Prop Blacklist**: Dangerous props like `dangerouslySetInnerHTML` are blocked
3. **Class Validation**: Tailwind classes are validated against patterns
4. **Handler References**: Event handlers are referenced by name, not code

### User Behavior Profile

Track and use behavior data for personalization:

```typescript
interface UserBehaviorProfile {
  userId: string;
  preferences: {
    colorScheme: 'light' | 'dark' | 'system';
    fontSize: 'small' | 'medium' | 'large';
    reducedMotion: boolean;
    locale: string;
  };
  patterns: {
    primaryDevice: 'mobile' | 'tablet' | 'desktop';
    navigationStyle: 'keyboard' | 'mouse' | 'touch';
    avgSessionDuration: number;
  };
  featureUsage: {
    topFeatures: Array<{ featureId: string; usageCount: number }>;
  };
}
```

## API Reference

### Core Functions

#### `generateUI(prompt, userBehavior?, options?)`

Generate UI using Claude.

```typescript
const result = await generateUI(
  'Create a settings panel',
  userBehavior,
  { model: 'claude-sonnet-4-20250514' }
);
```

#### `renderJSX(element, options?)`

Render a JSX element structure to React.

```typescript
const reactElement = renderJSX(jsxElement, {
  handlers: { handleClick: () => {} },
  components: { CustomCard: MyCardComponent },
});
```

#### `validateElement(element, options?)`

Validate a JSX element structure.

```typescript
const result = validateElement(jsxElement);
if (!result.valid) {
  console.error(result.errors);
}
```

### React Hooks

#### `useGeneratedUI(options)`

Hook for generating and rendering UI.

```typescript
const { ui, isLoading, error, regenerate, refine } = useGeneratedUI({
  prompt: 'Create a form',
  userBehavior: profile,
  cacheKey: 'my-form',
});
```

#### `useBehaviorTracking(options)`

Hook for tracking user behavior.

```typescript
const { profile, trackFeature, trackClick, updatePreferences } = useBehaviorTracking({
  userId: 'user-123',
  autoTrack: true,
});
```

### React Components

#### `<AdaptiveUIProvider>`

Context provider for adaptive UI.

```tsx
<AdaptiveUIProvider
  userId="user-123"
  handlers={handlers}
  components={components}
  enableTracking={true}
>
  {children}
</AdaptiveUIProvider>
```

#### `<GeneratedUI>`

Component that renders AI-generated UI.

```tsx
<GeneratedUI
  prompt="Create a navbar"
  personalized={true}
  loading={<Skeleton />}
  error={(e) => <Error message={e.message} />}
  fallback={<DefaultNavbar />}
/>
```

#### `<JSXRenderer>`

Component that renders a JSX element structure.

```tsx
<JSXRenderer
  element={jsxElement}
  handlers={handlers}
  validateClasses={true}
/>
```

#### `<Tracked>`

Wrapper for tracking interactions.

```tsx
<Tracked featureId="signup-button" trackClicks={true}>
  <button>Sign Up</button>
</Tracked>
```

## Tool Schema

The SDK provides a Claude Tool schema for UI generation:

```typescript
import { generateUITool, getTools } from '@m0rphic/jsx-render';

// Use in Claude API calls
const response = await anthropic.messages.create({
  model: 'claude-sonnet-4-20250514',
  tools: [generateUITool],
  tool_choice: { type: 'tool', name: 'generate_ui' },
  messages: [{ role: 'user', content: 'Create a button' }],
});
```

## Design System Integration

Configure your design system:

```typescript
const designSystem = {
  colors: {
    primary: 'blue-500',
    secondary: 'gray-500',
    accent: 'purple-500',
  },
  borderRadius: 'lg',
  typography: {
    fontFamily: 'Inter',
    headingWeight: 'bold',
  },
};

await generateUI('Create a card', undefined, { designSystem });
```

## Examples

See the [examples](./examples) directory for complete usage examples:

- Basic generation
- React integration
- Behavior tracking
- A/B testing variants
- Design system usage

## Environment Variables

```env
ANTHROPIC_API_KEY=your-api-key
```

## License

MIT