Visual Markdown Diagramming Target: Claude Code • Cursor • Windsurf • Devin 119 Lines • Markdown + DDL

Mermaid.ai & Eraser Replacement — Entire Agent Prompt Specification

This is the verbatim production plan (mermaid-flowchart-canvas.plan.md). Copy and paste this directly into your coding agent's Planning Mode prompt, or attach it as a workspace file before starting execution.

Download Raw .plan.md ← Back to Blueprint Overview
mermaid-flowchart-canvas.plan.md
# Blueprint: Visual Flowchart & Markdown Canvas (Mermaid.ai / Eraser.io Clone)
**Version:** 1.1.0 // Production Vetted  
**Target Agents:** Claude Code, Cursor, Windsurf, Devin  
**Methodology:** Strict Planning Mode, AST Parse State Machine, 200-Line File Cap, Two-Gate Regression Testing  

---

## 1. Executive Summary & Tech Stack Constraints
A high-performance visual diagramming canvas and markdown editor where developers write Mermaid.js or text diagrams on the left and see real-time, interactive, pan-and-zoom SVG flowcharts on the right. Features robust syntax error recovery, template insertion, SVG/PNG export, and shareable link serialization.

### Architectural Constraints:
- **Framework:** Next.js 14+ (App Router) / React 18+ with Vite
- **Diagram Engine:** `mermaid` (v10+) rendered through a sandboxed Web Worker to prevent UI thread lockup on large graphs
- **Canvas Math:** HTML5 Canvas / SVG matrix transform (`scale`, `translateX`, `translateY`) with pinch-to-zoom and spacebar-drag panning
- **State Architecture:** Zustand for canvas transform matrix; Monaco Editor or CodeMirror 6 for markdown input
- **File Limit:** Under 200 lines per file. Split canvas viewport, zoom controls, export modal, and syntax parser.

---

## 2. Data Model & Serialization Schema

```sql
-- Diagrams Storage
CREATE TABLE diagrams (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(255) NOT NULL DEFAULT 'Untitled Diagram',
    syntax_type VARCHAR(50) NOT NULL DEFAULT 'mermaid', -- 'mermaid' | 'plantuml' | 'markdown-table'
    content TEXT NOT NULL,
    viewport_state JSONB NOT NULL DEFAULT '{"zoom": 1.0, "x": 0, "y": 0}'::jsonb,
    is_public BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now()),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now())
);
CREATE INDEX idx_diagrams_updated ON diagrams(updated_at DESC);
```

---

## 3. Modular File System Blueprint (Under 200 Lines)

```
src/
├── app/
│   ├── page.tsx                           # < 95 lines (Hero & diagram launcher)
│   ├── editor/[id]/page.tsx               # < 130 lines (Split-pane layout container)
│   └── api/diagrams/route.ts              # < 120 lines (Save/load endpoints)
├── components/
│   ├── editor/
│   │   ├── code-editor-pane.tsx           # < 150 lines (CodeMirror/Monaco wrapper)
│   │   ├── syntax-error-banner.tsx        # < 70 lines (Friendly error recovery line marker)
│   │   └── template-selector.tsx          # < 110 lines (Flowchart, Sequence, ERD starters)
│   ├── canvas/
│   │   ├── diagram-canvas.tsx             # < 170 lines (SVG viewport & transform root)
│   │   ├── pan-zoom-controls.tsx          # < 95 lines (Zoom in, Zoom out, Fit-to-screen)
│   │   └── export-modal.tsx               # < 160 lines (SVG, High-DPI PNG, Clipboard copy)
│   └── ui/
│       ├── button.tsx, dialog.tsx         # Atomic UI primitives
├── hooks/
│   ├── use-mermaid-renderer.ts            # < 150 lines (Web worker debounced render)
│   └── use-canvas-transform.ts            # < 140 lines (Matrix math, pinch/zoom, pan)
├── workers/
│   └── mermaid-worker.ts                  # < 110 lines (Isolated graph parse & SVG stringify)
└── lib/
    ├── canvas-math.ts                     # < 90 lines (Matrix transform & boundary clamp)
    └── export-image.ts                    # < 130 lines (SVG to Canvas PNG converter)
```

---

## 4. State Machine & Business Logic Invariants
1. **Worker-Isolated Rendering:** Complex diagrams with 50+ nodes can freeze the browser main thread during layout computation. All parsing and SVG generation executes in a dedicated Web Worker with a 250ms debounce.
2. **Graceful Error Recovery:** When syntax is invalid (e.g. unclosed node brackets `A[Start --> B`), the canvas never crashes or wipes the previous valid SVG. It retains the last green render while overlaying an inline line-highlight banner pinpointing the exact syntax error.
3. **Infinite Canvas Pan/Zoom:** Panning updates matrix coordinates without triggering re-renders of the Monaco editor or re-parsing the Mermaid graph.
4. **Clean SVG/PNG Export:** Export pipeline rasterizes the SVG to a 2x/3x Retina `<canvas>` element and produces transparent 300 DPI PNGs or raw vector SVGs.

---

## 5. Phase-by-Phase Implementation Prompts for Agents

### Phase 1: Editor & Split-Pane Layout
```
Execute Phase 1: Set up the split-pane workspace layout using Tailwind and CodeMirror.
Left pane: Code editor with syntax highlighting for Mermaid.js and template selector (Flowchart, Sequence, Architecture, ERD).
Right pane: Canvas container with dark/light background grid dots.
Keep all files under 200 lines.
```

### Phase 2: Web Worker Mermaid Engine & Error Recovery
```
Execute Phase 2: Build the diagram rendering pipeline.
Create `workers/mermaid-worker.ts` running `@mermaid-js/mermaid` inside an isolated worker.
Debounce editor changes by 250ms.
If parsing fails, catch the error and display `syntax-error-banner.tsx` with line and column numbers while preserving the previous valid diagram on screen.
```

### Phase 3: Infinite Pan/Zoom & Fit-to-Screen Canvas Controls
```
Execute Phase 3: Implement canvas navigation in `useCanvasTransform`.
Add spacebar-click-and-drag panning, trackpad pinch-to-zoom, and mousewheel zoom.
Add floating controls: Zoom In (+), Zoom Out (-), Reset (100%), and Fit to Screen (computes bounding box and centers the diagram).
```

### Phase 4: High-DPI PNG & SVG Export Pipeline
```
Execute Phase 4: Implement the export modal.
Support 3 export modes:
1. Pure SVG download with embedded fonts and styling.
2. High-DPI PNG download (2x scale) with optional transparent or solid background.
3. One-click "Copy Image to Clipboard" using the Async Clipboard API.
```

### Phase 5: Persistence & Two-Gate Regression Harness
```
Execute Phase 5: Implement URL hash / database diagram saving and Vitest regression suites.
Add unit tests verifying:
- Valid flowchart AST parses cleanly.
- Broken syntax string throws friendly recoverable error without killing the worker.
- Fit-to-screen matrix calculation correctly scales oversized diagrams into viewport bounds.
```
End of specification • 119 lines
Full prompt copied to clipboard!