# Drupal Canvas Integration Plan for API Normalizer

**Date**: 2026-02-04
**Purpose**: Integrate Drupal Canvas to visualize API responses as interactive components
**Revolutionary Concept**: AI agents auto-generate Canvas components from API schemas

---

## Package Audit: Drupal Canvas Ecosystem

### Core Packages

#### 1. `@drupal-canvas/cli` v0.6.2
**Purpose**: CLI tool for managing Canvas components

**Key Features**:
- `canvas scaffold` - Generate component boilerplate
- `canvas validate` - Validate component structure
- `canvas build` - Build components for production
- `canvas upload` - Upload to Drupal
- `canvas download` - Download from Drupal

**Dependencies**:
- `@babel/parser` - Parse JavaScript/JSX
- `@clack/prompts` - Interactive CLI
- `tailwindcss-in-browser` - Tailwind processing
- `lightningcss` - Fast CSS processing
- `axios` - HTTP client for API calls
- `eslint` + `@drupal-canvas/eslint-config` - Linting

**Capabilities**:
- ✅ Scaffold React components
- ✅ Validate component.yml structure
- ✅ Build/bundle components
- ✅ Sync with Drupal via API
- ✅ Tailwind support out-of-the-box

#### 2. `drupal-canvas` v0.1.2
**Purpose**: Utilities and base components for Canvas

**Key Exports**:
- `./jsonapi-client` - JSON:API client
- `./jsonapi-utils` - JSON:API helpers
- `./drupal-utils` - Drupal-specific utilities
- `./FormattedText` - Rich text component
- `./next-image-standalone` - Image optimization
- `./utils` - General utilities

**Dependencies**:
- `@drupal-api-client/json-api-client@^1.3.0` - **JSON:API integration!**
- `jsona@^1.12.1` - JSON:API deserializer
- `clsx` - Conditional classes
- `tailwind-merge` - Merge Tailwind classes

**This is KEY**: Built-in JSON:API client means Canvas components can directly fetch from Drupal!

#### 3. `@drupal-canvas/create` v1.0.0
**Purpose**: Scaffold entire Canvas codebase

**Usage**:
```bash
npx @drupal-canvas/create my-canvas-project
```

Creates:
- Project structure
- Canvas configuration
- Build setup
- Example components

#### 4. `@drupal-canvas/vite-plugin` v0.1.0
**Purpose**: Vite integration for fast development

**Features**:
- Hot module replacement
- Fast builds
- Dev server integration

#### 5. `@drupal-canvas/eslint-config` v0.1.0
**Purpose**: Linting rules for Canvas components

**Enforces**:
- React best practices
- Drupal coding standards
- Accessibility rules

### Related Packages

#### 6. `drupal-jsonapi-params` v3.0.0
**Purpose**: Build JSON:API query parameters

**Usage**:
```javascript
import { DrupalJsonApiParams } from 'drupal-jsonapi-params';

const params = new DrupalJsonApiParams()
  .addFilter('field_status', 'published')
  .addInclude('field_image')
  .addSort('created', 'DESC')
  .getQueryString();
```

#### 7. `twig-drupal-filters` v3.2.0
**Purpose**: Drupal Twig filters for JavaScript

**Filters Available**:
- `drupal_escape` - Escape HTML
- `format_date` - Date formatting
- `t` - Translation
- `url` - URL generation

---

## Current State: api_normalization Module

### What It Has

**Core Functionality**:
- API endpoint normalization
- OpenAPI spec generation (`openapi.yml` - 161KB!)
- E2E testing with Playwright
- Type generation from OpenAPI

**Structure**:
```
api_normalization/
├── openapi.yml (161KB OpenAPI 3.1 spec)
├── src/ (PHP services)
├── templates/ (Twig templates)
├── js/ (JavaScript)
├── css/ (Styles)
├── modules/ (Submodules)
└── tests/ (E2E tests)
```

**Key Features**:
- Normalizes API responses
- Generates OpenAPI specs
- Type-safe API clients
- Extensive testing

### What It's Missing

**No Visual Component Layer**:
- API responses are data only
- No interactive visualization
- No real-time updates
- No component library for API displays

**This is the opportunity!**

---

## Revolutionary Integration: Canvas API Visualizer

### Vision

**Transform API responses into interactive Canvas components automatically**

#### Example Flow:

1. **User makes API call**:
   ```
   GET /api/nodes/article/123
   ```

2. **api_normalizer processes response**:
   ```json
   {
     "data": {
       "type": "node--article",
       "id": "123",
       "attributes": { "title": "Hello", ... }
     }
   }
   ```

3. **Canvas Visualizer Component renders it visually**:
   - Rich card layout
   - Interactive fields
   - Real-time updates
   - Edit-in-place
   - Relationship visualization

4. **AI Agent auto-generates component from schema**:
   - Reads OpenAPI spec
   - Identifies entity type
   - Generates optimal Canvas component
   - Adds interactivity
   - Deploys to Drupal

---

## Proposed Architecture

```
┌─────────────────────────────────────────────────────┐
│ Drupal Site                                         │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Canvas API Visualizer Page                      │ │
│ │ - API endpoint selector                         │ │
│ │ - Real-time component rendering                 │ │
│ │ - Interactive response exploration              │ │
│ └─────────────────────────────────────────────────┘ │
└──────────┬──────────────────────────────────────────┘
           │
           ├── Fetch via JSON:API
           │
┌──────────▼──────────────────────────────────────────┐
│ api_normalization Module                            │
│ ┌─────────────────┐  ┌──────────────────────────┐  │
│ │ Canvas          │  │ API Response             │  │
│ │ Visualizer      │  │ Normalizer               │  │
│ │ Submodule       │  │ (existing)               │  │
│ │                 │  │                          │  │
│ │ - Component lib │  │ - OpenAPI spec (161KB)   │  │
│ │ - Auto-gen      │  │ - Type generation        │  │
│ │ - Rendering     │  │ - Normalization logic    │  │
│ └─────────────────┘  └──────────────────────────┘  │
└──────────┬──────────────────────────────────────────┘
           │
           ├── Component Generation Request
           │
┌──────────▼──────────────────────────────────────────┐
│ AI Agent Swarm                                      │
│ ┌────────────────┐  ┌───────────────────────────┐  │
│ │ canvas-        │  │ drupal-                   │  │
│ │ generator      │  │ documentation             │  │
│ │                │  │                           │  │
│ │ - Read OpenAPI │  │ - Document components     │  │
│ │ - Generate JSX │  │ - Usage examples          │  │
│ │ - Add Tailwind │  │ - Type definitions        │  │
│ │ - Deploy       │  │                           │  │
│ └────────────────┘  └───────────────────────────┘  │
└─────────────────────────────────────────────────────┘
```

---

## Submodule Design: `api_normalizer_canvas`

### Module Structure

```
api_normalization/
└── modules/
    └── api_normalizer_canvas/
        ├── api_normalizer_canvas.info.yml
        ├── api_normalizer_canvas.module
        ├── api_normalizer_canvas.routing.yml
        ├── api_normalizer_canvas.services.yml
        ├── src/
        │   ├── Controller/
        │   │   ├── CanvasVisualizerController.php
        │   │   └── ApiExplorerController.php
        │   ├── Service/
        │   │   ├── CanvasComponentGenerator.php
        │   │   ├── SchemaToCanvasMapper.php
        │   │   └── ComponentRegistry.php
        │   └── Plugin/
        │       └── CanvasVisualizer/
        │           ├── NodeVisualizer.php
        │           ├── TaxonomyVisualizer.php
        │           └── MediaVisualizer.php
        ├── canvas/
        │   ├── canvas.config.mjs
        │   ├── package.json
        │   ├── components/
        │   │   ├── 01-atoms/
        │   │   │   ├── ApiField/
        │   │   │   ├── JsonValue/
        │   │   │   └── RelationshipLink/
        │   │   ├── 02-molecules/
        │   │   │   ├── EntityCard/
        │   │   │   ├── RelationshipList/
        │   │   │   └── ApiResponsePreview/
        │   │   ├── 03-organisms/
        │   │   │   ├── ApiExplorer/
        │   │   │   ├── EntityVisualizer/
        │   │   │   └── SchemaViewer/
        │   │   └── 04-templates/
        │   │       ├── ApiEndpointPage/
        │   │       └── EntityDetailPage/
        │   └── src/
        │       ├── hooks/
        │       │   ├── useJsonApi.ts
        │       │   ├── useApiSchema.ts
        │       │   └── useEntityFetch.ts
        │       └── utils/
        │           ├── jsonapi-helpers.ts
        │           └── schema-parser.ts
        ├── templates/
        │   ├── canvas-visualizer-page.html.twig
        │   └── api-explorer.html.twig
        ├── tests/
        │   └── src/
        │       └── Functional/
        │           └── CanvasVisualizerTest.php
        └── README.md
```

### Key Components

#### 1. **ApiExplorer** (Organism)
**Purpose**: Main UI for exploring APIs visually

**Features**:
- Endpoint selector dropdown
- Method selector (GET, POST, PUT, DELETE)
- Parameter builder (query, headers, body)
- Real-time response visualization
- Schema documentation sidebar

**Props**:
```yaml
endpoints:
  type: array
  description: Available API endpoints
currentEndpoint:
  type: string
  description: Selected endpoint
onResponse:
  type: string
  description: Callback for response data
```

#### 2. **EntityVisualizer** (Organism)
**Purpose**: Visualize Drupal entities (nodes, terms, media)

**Features**:
- Auto-detects entity type from JSON:API response
- Renders appropriate layout (card, list, grid)
- Shows relationships as interactive links
- Field-level editing (if permissions allow)
- Real-time updates via JSON:API

**Props**:
```yaml
entityData:
  type: object
  description: JSON:API entity data
entityType:
  type: string
  description: Entity type (node, taxonomy_term, media)
viewMode:
  type: string
  enum: [card, list, grid, detail]
editable:
  type: boolean
  default: false
```

#### 3. **EntityCard** (Molecule)
**Purpose**: Compact entity display

**Features**:
- Title/label
- Image (if available)
- Summary/teaser
- Metadata (author, date, status)
- Quick actions (view, edit, delete)

#### 4. **SchemaViewer** (Organism)
**Purpose**: Interactive OpenAPI schema explorer

**Features**:
- Schema tree visualization
- Field type indicators
- Required field badges
- Validation rules display
- Example values

---

## AI Agent Integration

### New Agent: `canvas-generator`

**Purpose**: Auto-generate Canvas components from API schemas

**Capabilities**:
1. **Read OpenAPI Spec**
   - Parse `api_normalization/openapi.yml`
   - Extract entity schemas
   - Identify field types

2. **Generate Component Structure**
   ```javascript
   // Input: OpenAPI schema for "node--article"
   {
     "type": "object",
     "properties": {
       "title": { "type": "string" },
       "body": { "type": "object" },
       "field_image": { "$ref": "#/components/schemas/file--file" }
     }
   }

   // Output: React component
   const ArticleCard = ({ entity }) => {
     return (
       <div className="article-card">
         <h2>{entity.attributes.title}</h2>
         {entity.relationships.field_image && (
           <img src={entity.relationships.field_image.data.attributes.uri} />
         )}
         <div dangerouslySetInnerHTML={{ __html: entity.attributes.body.value }} />
       </div>
     );
   };
   ```

3. **Add Styling**
   - Tailwind classes
   - Responsive design
   - Dark mode support
   - Accessibility attributes

4. **Create component.yml**
   ```yaml
   name: ArticleCard
   machineName: articlecard
   status: true
   props:
     properties:
       entity:
         type: object
         description: JSON:API article entity
   ```

5. **Deploy to Canvas**
   ```bash
   canvas build
   canvas upload --component ArticleCard
   ```

### MCP Tools for canvas-generator Agent

Add to Canvas MCP server:

```typescript
{
  name: 'canvas.generateFromSchema',
  description: 'Generate Canvas component from OpenAPI schema',
  inputSchema: {
    type: 'object',
    properties: {
      schemaPath: { type: 'string' },
      entityType: { type: 'string' },
      componentName: { type: 'string' },
      viewMode: { type: 'string', enum: ['card', 'list', 'detail'] }
    }
  }
}
```

---

## Implementation Plan

### Phase 1: Foundation (Week 1)

**Goal**: Set up Canvas infrastructure in api_normalization

**Tasks**:
1. Create `modules/api_normalizer_canvas` submodule
2. Initialize Canvas workspace:
   ```bash
   cd api_normalization/modules/api_normalizer_canvas
   npx @drupal-canvas/create canvas
   ```
3. Install dependencies:
   ```bash
   npm install drupal-canvas drupal-jsonapi-params
   npm install --save-dev @drupal-canvas/cli
   ```
4. Configure Canvas:
   ```javascript
   // canvas.config.mjs
   export default {
     projectRoot: ".",
     components: [
       {
         name: "api-normalizer-canvas",
         root: "components",
         outDir: "dist/canvas",
         package: "@drupal/api-normalizer-canvas"
       }
     ],
     drupal: {
       baseUrl: process.env.DRUPAL_BASE_URL,
       jsonApiEndpoint: "/jsonapi"
     }
   };
   ```
5. Create base component structure (atoms/molecules/organisms/templates)

**Deliverables**:
- ✅ Submodule scaffolded
- ✅ Canvas configured
- ✅ Build system working
- ✅ JSON:API integration ready

### Phase 2: Core Components (Week 2)

**Goal**: Build essential Canvas components

**Tasks**:
1. **Atoms**:
   - `ApiField` - Display any JSON:API field
   - `JsonValue` - Format JSON values
   - `RelationshipLink` - Link to related entities
   - `StatusBadge` - Entity status indicator

2. **Molecules**:
   - `EntityCard` - Compact entity display
   - `FieldGroup` - Grouped fields
   - `RelationshipList` - List of related entities
   - `ApiResponsePreview` - Raw JSON viewer

3. **Organisms**:
   - `EntityVisualizer` - Full entity display
   - `ApiExplorer` - Interactive API explorer
   - `SchemaViewer` - OpenAPI schema viewer

**Deliverables**:
- ✅ 12+ Canvas components
- ✅ Full JSON:API integration
- ✅ Storybook documentation
- ✅ Unit tests

### Phase 3: Agent Integration (Week 3)

**Goal**: AI agents can generate components

**Tasks**:
1. Create `canvas-generator` agent (OSSA manifest)
2. Add MCP tools to Canvas MCP server:
   - `canvas.generateFromSchema`
   - `canvas.analyzeApiResponse`
   - `canvas.suggestComponent`
3. Integrate with api_normalization OpenAPI spec
4. Train agent on component patterns
5. Test auto-generation

**Example Agent Flow**:
```bash
# Agent reads OpenAPI spec
agent-protocol read-schema api_normalization/openapi.yml

# Agent generates component
canvas-generator generate \
  --schema "node--article" \
  --component "ArticleVisualizer" \
  --view-mode "detail"

# Agent builds and deploys
canvas build
canvas upload
```

**Deliverables**:
- ✅ canvas-generator agent operational
- ✅ Auto-generation working
- ✅ Component quality validation
- ✅ Deployment automation

### Phase 4: UI Integration (Week 4)

**Goal**: Integrate Canvas into api_normalization admin UI

**Tasks**:
1. Create Canvas visualizer pages:
   - `/admin/config/services/api-normalizer/canvas-explorer`
   - `/admin/config/services/api-normalizer/canvas-library`
2. Add Canvas rendering to existing pages:
   - Entity view pages (replace Twig with Canvas)
   - API response pages (visualize responses)
3. Create configuration UI:
   - Component selection
   - View mode configuration
   - Field mapping
4. Add Canvas download/upload admin forms

**Deliverables**:
- ✅ Admin UI with Canvas integration
- ✅ Visual API explorer
- ✅ Component library browser
- ✅ Configuration management

### Phase 5: Advanced Features (Week 5)

**Goal**: Real-time updates, editing, relationships

**Tasks**:
1. **Real-time Updates**:
   - WebSocket integration
   - Live entity updates
   - Optimistic UI updates

2. **Inline Editing**:
   - Edit fields in Canvas
   - Auto-save to JSON:API
   - Validation feedback

3. **Relationship Visualization**:
   - Graph view of entity relationships
   - Interactive navigation
   - Lazy loading

4. **Component Variants**:
   - Generate multiple view modes
   - A/B testing
   - User preferences

**Deliverables**:
- ✅ Real-time capable
- ✅ Inline editing working
- ✅ Relationship explorer
- ✅ Advanced component features

---

## Technical Integration Points

### 1. JSON:API Client Integration

```typescript
// useJsonApi.ts
import { DrupalJsonApiParams } from 'drupal-jsonapi-params';

export function useJsonApi(entityType: string, entityId: string) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const params = new DrupalJsonApiParams()
      .addInclude('field_image')
      .addInclude('uid')
      .getQueryString();

    fetch(`/jsonapi/${entityType}/${entityId}?${params}`)
      .then(res => res.json())
      .then(data => {
        setData(data.data);
        setLoading(false);
      });
  }, [entityType, entityId]);

  return { data, loading };
}
```

### 2. OpenAPI Schema Parser

```typescript
// schema-parser.ts
export function parseOpenApiSchema(spec: any, entityType: string) {
  const schema = spec.components.schemas[entityType];

  return {
    fields: Object.entries(schema.properties).map(([name, field]) => ({
      name,
      type: field.type,
      required: schema.required?.includes(name),
      description: field.description
    })),
    relationships: Object.entries(schema.properties)
      .filter(([_, field]) => field.$ref)
      .map(([name, field]) => ({
        name,
        targetType: field.$ref.split('/').pop()
      }))
  };
}
```

### 3. Component Generator Service

```php
// CanvasComponentGenerator.php
class CanvasComponentGenerator {

  public function generateFromSchema(array $schema, string $componentName): string {
    // Generate React component from OpenAPI schema
    $jsx = $this->generateJsx($schema);
    $yml = $this->generateComponentYml($schema, $componentName);

    // Write files
    $componentPath = "canvas/components/03-organisms/{$componentName}";
    file_put_contents("{$componentPath}/index.jsx", $jsx);
    file_put_contents("{$componentPath}/component.yml", $yml);

    return $componentPath;
  }

  private function generateJsx(array $schema): string {
    // Use AI agent to generate optimal JSX
    return $this->canvasGeneratorAgent->generate($schema);
  }
}
```

---

## Benefits

### For Developers
- ✅ Visual API exploration (no Postman needed)
- ✅ Interactive documentation
- ✅ Component library for API displays
- ✅ Auto-generated from schemas

### For Content Editors
- ✅ Visual entity browsers
- ✅ Inline editing
- ✅ Relationship visualization
- ✅ Real-time updates

### For AI Agents
- ✅ Can generate UI components automatically
- ✅ Schema-to-component mapping
- ✅ Consistent patterns
- ✅ Deployment automation

### For the Platform
- ✅ Unified visual language
- ✅ API-first with visual layer
- ✅ Drupal + React seamlessly integrated
- ✅ Extensible component library

---

## Success Metrics

| Metric | Target |
|--------|--------|
| Component Library Size | 50+ components |
| Auto-generation Accuracy | 90%+ |
| Canvas Page Load Time | < 2s |
| JSON:API Integration | 100% entities |
| Developer Adoption | 80% of API endpoints visualized |
| Agent Success Rate | 95% successful generations |

---

## Example Use Cases

### 1. Visual API Explorer
**Problem**: Developers need to understand API responses
**Solution**: Canvas visualizer shows responses as rich interactive cards

### 2. Entity Relationship Browser
**Problem**: Complex entity relationships hard to understand
**Solution**: Graph view with interactive navigation

### 3. Auto-generated Admin UI
**Problem**: Creating admin UIs for custom entities is tedious
**Solution**: Agent generates Canvas components from entity schemas

### 4. Real-time Content Dashboard
**Problem**: Static admin pages don't show live updates
**Solution**: Canvas components with WebSocket integration

### 5. API Documentation Site
**Problem**: OpenAPI specs are hard to read
**Solution**: Interactive Canvas components demonstrate APIs

---

## Next Steps

1. **Create api_normalizer_canvas submodule structure**
2. **Initialize Canvas workspace**
3. **Build first 3 components (ApiField, EntityCard, ApiExplorer)**
4. **Test JSON:API integration**
5. **Create canvas-generator agent**
6. **Demonstrate auto-generation**

---

## Resources

**Drupal Canvas**:
- CLI: https://www.npmjs.com/package/@drupal-canvas/cli
- Utils: https://www.npmjs.com/package/drupal-canvas
- Create: https://www.npmjs.com/package/@drupal-canvas/create

**JSON:API**:
- Params: https://www.npmjs.com/package/drupal-jsonapi-params
- Client: Built into `drupal-canvas`

**Current Work**:
- api_normalization: `/Users/thomas.scola/Sites/blueflyio/_CURRENT_WORK/api_normalization/`
- OpenAPI spec: `api_normalization/openapi.yml` (161KB)

---

**Status**: Planning Complete
**Next**: Begin Phase 1 Implementation
**Impact**: Revolutionary visual API layer for Drupal 🚀
