Metadata-Version: 2.4
Name: excalidraw-cli
Version: 0.2.0
Summary: CLI-Anything harness for Excalidraw — create and manipulate Excalidraw diagrams from the command line
Author: excalidraw-cli contributors
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: click>=8.0
Requires-Dist: prompt-toolkit>=3.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == 'dev'
Provides-Extra: export
Requires-Dist: cairosvg>=2.5; extra == 'export'
Requires-Dist: pillow>=9.0; extra == 'export'
Description-Content-Type: text/markdown

<h1 align="center">
  :pencil2: excalidraw-cli
</h1>

<p align="center">
  <strong>Create and manipulate <a href="https://excalidraw.com">Excalidraw</a> diagrams from the command line.</strong>
</p>

<p align="center">
  A <a href="https://github.com/HKUDS/CLI-Anything">CLI-Anything</a> harness that turns Excalidraw into an agent-native, scriptable tool.<br/>
  Generate flowcharts, sequence diagrams, ER diagrams, mind maps, and Kanban boards —<br/>
  then open them in Excalidraw for hand-drawn-style polish.
</p>

<p align="center">
  <a href="#quick-start"><img src="https://img.shields.io/badge/Quick_Start-5_min-blue?style=for-the-badge" alt="Quick Start" /></a>
  <a href="#features"><img src="https://img.shields.io/badge/Templates-5_Types-green?style=for-the-badge" alt="Templates" /></a>
  <a href="#testing"><img src="https://img.shields.io/badge/Tests-154_Passing-brightgreen?style=for-the-badge" alt="Tests" /></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge" alt="License" /></a>
</p>

<p align="center">
  <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-≥3.10-3776AB?logo=python&logoColor=white" alt="Python 3.10+" /></a>
  <a href="https://click.palletsprojects.com/"><img src="https://img.shields.io/badge/click-≥8.0-green" alt="Click" /></a>
  <a href="https://excalidraw.com"><img src="https://img.shields.io/badge/excalidraw-compatible-6965db?logo=excalidraw&logoColor=white" alt="Excalidraw" /></a>
  <a href="#export"><img src="https://img.shields.io/badge/export-SVG_|_PNG_|_JPG_|_PDF-orange" alt="Export Formats" /></a>
</p>

<p align="center">
  <img src="https://visitor-badge.laobi.icu/badge?page_id=prazjain.excalidraw-cli&style=for-the-badge&color=00d4ff" alt="Views" />
</p>

---

## Why excalidraw-cli?

| Problem | Solution |
|---------|----------|
| Excalidraw has no CLI — diagrams require the web UI | `excalidraw-cli` generates valid `.excalidraw` files from the terminal |
| AI agents can't create visual diagrams easily | `--json` flag on every command enables structured agent workflows |
| Repetitive diagram creation is tedious | Templates generate complete diagrams in one command |
| No programmatic access to the `.excalidraw` format | Python API (`Scene`, `create_element`) for full control |

---

## Quick Start

### Installation

**From PyPI** (recommended):
```bash
pip install excalidraw-cli

# For PNG, JPG, PDF export support:
pip install excalidraw-cli[export]
```

**From source** (for development):
```bash
cd agent-harness
pip install -e .

# For PNG, JPG, PDF export support:
pip install -e ".[export]"
```

### Your first diagram in 10 seconds

```bash
# Generate a flowchart and open it at excalidraw.com
excalidraw-cli template flowchart "Start" "?Is valid?" "Process" "End" \
  -o my_flow.excalidraw
```

Open `my_flow.excalidraw` in [excalidraw.com](https://excalidraw.com) (File > Open) to see your diagram with the signature hand-drawn style.

---

## Features

- **5 diagram templates** — flowchart, sequence, ER, mind map, Kanban
- **Export to SVG, PNG, JPG, PDF** — high-quality image and vector output with configurable scale and quality
- **Full element control** — add, update, remove, connect shapes programmatically
- **Undo/redo** — built-in state management for safe iteration
- **`--json` everywhere** — structured output for AI agents and pipelines
- **REPL mode** — interactive session for iterative diagram building
- **Python API** — import `Scene` directly for maximum flexibility
- **Valid Excalidraw format** — output files open natively in excalidraw.com

---

## Command Reference

```
excalidraw-cli [--json] [--version] COMMAND
```

### Scene Management

| Command | Description |
|---------|-------------|
| `scene new [--background COLOR] [--grid SIZE]` | Create a new empty scene |
| `scene load FILE` | Load an existing `.excalidraw` file |
| `scene save [FILE]` | Save the current scene |
| `scene info` | Show scene summary (element counts, background, etc.) |
| `scene clear` | Remove all elements |
| `scene background COLOR` | Change background color |
| `scene undo` | Undo last modification |
| `scene redo` | Redo last undone modification |

### Element Operations

| Command | Description |
|---------|-------------|
| `element add TYPE [OPTIONS]` | Add an element (rectangle, ellipse, diamond, arrow, line, text, freedraw, image, frame) |
| `element list [--type TYPE]` | List elements, optionally filtered by type |
| `element remove ID` | Remove an element by ID |
| `element update ID [OPTIONS]` | Update element properties |
| `element connect FROM_ID TO_ID` | Draw an arrow between two elements |

**Element add options:**
```
--x, --y          Position (default: 0,0)
-w, --width       Width (default: 200)
-h, --height      Height (default: 100)
-l, --label       Text label
--stroke-color    Stroke color (hex, e.g. "#ff0000")
--bg-color        Background color (hex)
--fill            Fill style: hachure | cross-hatch | solid
--stroke-width    Stroke width (number)
--roughness       0=sharp, 1=normal, 2=rough
--opacity         0-100
```

### Templates

| Command | Description |
|---------|-------------|
| `template flowchart STEPS... [-d vertical\|horizontal] [-o FILE]` | Linear flowchart; prefix step with `?` for decision diamond |
| `template sequence -a ACTORS -m FROM:TO:TEXT [-o FILE]` | Sequence diagram with lifelines |
| `template er -e NAME:field1,field2 -r A:B:label [-o FILE]` | Entity-relationship diagram |
| `template mindmap ROOT -b LABEL:leaf1,leaf2 [-o FILE]` | Radial mind map |
| `template kanban -c NAME:card1,card2 [-o FILE]` | Kanban board with columns |

### Export

All export commands accept `--input/-i FILE` to load directly from a `.excalidraw` file, enabling single-command export without a separate load step.

| Command | Description |
|---------|-------------|
| `export json [-o FILE] [--compact]` | Export as raw JSON |
| `export excalidraw FILE` | Save as `.excalidraw` file |
| `export svg FILE [--scale N] [--padding N]` | Export as SVG vector image |
| `export png FILE [--scale N] [--padding N]` | Export as high-quality PNG (default 2x DPI) |
| `export jpg FILE [--scale N] [--quality 1-100]` | Export as JPG (default quality 95) |
| `export pdf FILE [--scale N] [--padding N]` | Export as PDF document |

**Optional dependencies for image export:**
```bash
pip install cairosvg          # Required for PNG, JPG, PDF
pip install Pillow            # Required for JPG
# Or install everything at once:
pip install -e ".[export]"
```

---

## Usage Examples

### 1. Flowchart with decisions

```bash
excalidraw-cli template flowchart \
  "User submits form" \
  "?Input valid?" \
  "Save to database" \
  "Send confirmation" \
  "?Email delivered?" \
  "Done" \
  -o registration_flow.excalidraw
```

### 2. REST API sequence diagram

```bash
excalidraw-cli template sequence \
  -a "Browser,API Gateway,Auth Service,Database" \
  -m "0:1:POST /login" \
  -m "1:2:Validate token" \
  -m "2:3:SELECT user" \
  -m "3:2:User row" \
  -m "2:1:JWT token" \
  -m "1:0:200 OK + token" \
  -o api_auth.excalidraw
```

### 3. Database ER diagram

```bash
excalidraw-cli template er \
  -e "User:id,username,email,created_at" \
  -e "Post:id,title,body,published_at" \
  -e "Comment:id,body,created_at" \
  -r "User:Post:writes" \
  -r "Post:Comment:has many" \
  -r "User:Comment:authors" \
  -o blog_schema.excalidraw
```

### 4. Project mind map

```bash
excalidraw-cli template mindmap "My SaaS App" \
  -b "Frontend:React,TypeScript,Tailwind" \
  -b "Backend:Python,FastAPI,SQLAlchemy" \
  -b "Infrastructure:AWS,Docker,Terraform" \
  -b "Data:PostgreSQL,Redis,S3" \
  -o architecture.excalidraw
```

### 5. Sprint Kanban board

```bash
excalidraw-cli template kanban \
  -c "Backlog:Auth flow,Dark mode,Search" \
  -c "In Progress:User profiles,API docs" \
  -c "Review:Payment integration" \
  -c "Done:Landing page,CI/CD pipeline" \
  -o sprint_board.excalidraw
```

### 6. Manual element-by-element construction

```bash
# Create a scene and build step by step
excalidraw-cli scene new --background "#f5f5dc"

excalidraw-cli element add rectangle --x 100 --y 50 -w 180 -h 80 \
  -l "Client" --bg-color "#a5d8ff" --fill solid

excalidraw-cli element add rectangle --x 100 --y 250 -w 180 -h 80 \
  -l "Server" --bg-color "#d0bfff" --fill solid

excalidraw-cli element add text --x 80 --y 10 -l "System Overview"

excalidraw-cli scene save system.excalidraw
```

### 7. Export to PNG, JPG, PDF, SVG

```bash
# Generate a diagram and export to all formats in one go
excalidraw-cli template flowchart "Start" "Process" "End" -o diagram.excalidraw

# High-quality PNG (2x scale by default for crisp images)
excalidraw-cli export png diagram.png -i diagram.excalidraw

# Ultra-high-res PNG (4x scale, great for presentations)
excalidraw-cli export png diagram_4x.png -i diagram.excalidraw --scale 4.0

# JPG with custom quality
excalidraw-cli export jpg diagram.jpg -i diagram.excalidraw --quality 95

# PDF for documents and printing
excalidraw-cli export pdf diagram.pdf -i diagram.excalidraw

# SVG for web embedding
excalidraw-cli export svg diagram.svg -i diagram.excalidraw
```

### 8. JSON output for scripting / AI agents

```bash
# Every command supports --json
excalidraw-cli --json scene new
# {"status": "created", "background": "#ffffff", "grid": null}

excalidraw-cli --json element add rectangle --x 100 --y 100
# {"status": "added", "id": "abc123...", "type": "rectangle"}

excalidraw-cli --json element list
# [{"id": "abc123...", "type": "rectangle", "x": 100, "y": 100, ...}]

excalidraw-cli --json scene info
# {"total_elements": 1, "element_types": {"rectangle": 1}, ...}
```

---

## Using with AI Agents

excalidraw-cli is designed to be controlled by AI agents via structured JSON I/O. Here are patterns for common AI workflows:

### Claude Code / Claude

```
You: Create an architecture diagram for a microservices app with
     API gateway, user service, order service, and PostgreSQL.

Claude: I'll use excalidraw-cli to generate that diagram.

> excalidraw-cli --json scene new --background "#fafafa"
> excalidraw-cli --json element add rectangle --x 300 --y 50 -w 200 -h 70 -l "API Gateway" --bg-color "#a5d8ff" --fill solid
> excalidraw-cli --json element add rectangle --x 100 --y 200 -w 180 -h 70 -l "User Service" --bg-color "#b2f2bb" --fill solid
> excalidraw-cli --json element add rectangle --x 400 --y 200 -w 180 -h 70 -l "Order Service" --bg-color "#d0bfff" --fill solid
> excalidraw-cli --json element add rectangle --x 250 --y 380 -w 200 -h 70 -l "PostgreSQL" --bg-color "#f9e2af" --fill solid
> excalidraw-cli --json element connect <gateway_id> <user_svc_id>
> excalidraw-cli --json element connect <gateway_id> <order_svc_id>
> excalidraw-cli --json element connect <user_svc_id> <db_id>
> excalidraw-cli --json element connect <order_svc_id> <db_id>
> excalidraw-cli --json scene save microservices.excalidraw

Created microservices.excalidraw — open in excalidraw.com to view.
```

### Python scripting (agent or automation)

```python
from cli_anything.excalidraw.core import Scene
from cli_anything.excalidraw.templates import flowchart

# Use templates for common patterns
scene = flowchart(["Receive order", "?In stock?", "Ship", "Backorder"])
scene.save("order_flow.excalidraw")

# Or build custom diagrams
scene = Scene()
scene.set_background("#1e1e2e")
web = scene.add_shape("rectangle", x=200, y=50, width=200, height=70,
                       label="Web App", backgroundColor="#89b4fa", fillStyle="solid")
api = scene.add_shape("rectangle", x=200, y=200, width=200, height=70,
                       label="API", backgroundColor="#a6e3a1", fillStyle="solid")
scene.connect(web, api)
scene.save("custom.excalidraw")
```

### Shell pipeline

```bash
# Generate a diagram from a list of steps in a file
cat steps.txt | xargs excalidraw-cli template flowchart -o pipeline.excalidraw

# Batch generate diagrams
for project in frontend backend infra; do
  excalidraw-cli template mindmap "$project" \
    -b "$(cat ${project}_topics.txt)" \
    -o "${project}_map.excalidraw"
done
```

### REPL mode for interactive building

```
$ excalidraw-cli
excalidraw-cli v0.1.0 — interactive mode
Type 'help' for commands, 'quit' to exit.

excalidraw> scene new
  status: created
excalidraw> element add rectangle --x 100 --y 100 -l "Hello"
  status: added
excalidraw> element list
  - abc123  type=rectangle  (100,100)  200x100
excalidraw> scene save hello.excalidraw
  status: saved
excalidraw> quit
Bye!
```

---

## Project Structure

```
excalidraw-cli/
├── README.md                  # This file
├── LICENSE                    # MIT License
├── CONTRIBUTING.md            # Contribution guidelines
├── agent-harness/
│   ├── setup.py               # Package installation
│   ├── cli_anything/
│   │   └── excalidraw/
│   │       ├── __init__.py    # Version
│   │       ├── core.py        # Scene & element engine
│   │       ├── templates.py   # Diagram templates
│   │       ├── render.py      # SVG renderer + PNG/JPG/PDF export
│   │       └── cli.py         # Click CLI + REPL
│   └── tests/
│       ├── test_core.py       # 39 unit tests
│       ├── test_templates.py  # 11 template tests
│       ├── test_render.py     # 43 render/export tests
│       └── test_cli.py        # 29 E2E CLI tests
├── examples/
│   ├── flowchart.sh           # Flowchart example
│   ├── sequence.sh            # Sequence diagram example
│   ├── er_diagram.sh          # ER diagram example
│   ├── mindmap.sh             # Mind map example
│   ├── kanban.sh              # Kanban board example
│   ├── manual_build.sh        # Step-by-step manual build
│   └── ai_agent_example.py    # Python API usage example
└── TEST.md                    # Test documentation & results
```

## Architecture

```
                     ┌──────────────────────┐
                     │     CLI (cli.py)     │  Click commands + REPL
                     │     --json flag      │  Human & agent output
                     └──────────┬───────────┘
                                │
          ┌─────────────────────┼─────────────────────┐
          ▼                     ▼                     ▼
 ┌──────────────┐      ┌──────────┐      ┌──────────────────┐
 │ templates.py │      │ core.py  │      │   render.py      │
 │  flowchart   │      │  Scene   │      │  SVG renderer    │
 │  sequence    │      │  Element │      │  ┌──── PNG (2x+) │
 │  er / mind   │      │  undo/   │      │  ├──── JPG       │
 │  kanban      │      │  redo    │      │  ├──── PDF       │
 └──────────────┘      └──────────┘      │  └──── SVG       │
                             │           └──────────────────┘
                    ┌────────┴────────┐
                    │ .excalidraw JSON │
                    │  (open in web)  │
                    └─────────────────┘
```

---

## Testing

```bash
cd agent-harness
pip install pytest
python -m pytest tests/ -v
```

**154 tests** covering:
- **Core** (39 tests) — element creation, scene management, persistence, undo/redo
- **Templates** (11 tests) — all 5 diagram templates with edge cases
- **Render/Export** (43 tests) — SVG generation, PNG/JPG/PDF output, format validation, CLI integration
- **CLI E2E** (29 tests) — every command with JSON output validation

---

## Supported Element Types

| Type | Description | Key Properties |
|------|-------------|----------------|
| `rectangle` | Rectangle shape | x, y, width, height, label, fill, stroke |
| `ellipse` | Ellipse/circle | x, y, width, height, label |
| `diamond` | Diamond (decision) | x, y, width, height, label |
| `arrow` | Arrow with arrowheads | start/end binding, points, arrowhead style |
| `line` | Straight/multi-point line | points array, stroke style |
| `text` | Text element | text, fontSize, fontFamily, textAlign |
| `freedraw` | Freehand drawing | points, pressure, simulatePressure |
| `image` | Embedded image | fileId, status, scale |
| `frame` | Grouping frame | name |

---

## Excalidraw File Format

The `.excalidraw` format is plain JSON:

```json
{
  "type": "excalidraw",
  "version": 2,
  "source": "https://excalidraw.com",
  "elements": [
    {
      "type": "rectangle",
      "x": 100,
      "y": 100,
      "width": 200,
      "height": 100,
      "strokeColor": "#1e1e1e",
      "backgroundColor": "transparent",
      "fillStyle": "hachure",
      "roughness": 1,
      "opacity": 100,
      ...
    }
  ],
  "appState": {
    "viewBackgroundColor": "#ffffff",
    "gridSize": null
  },
  "files": {}
}
```

Files generated by excalidraw-cli are fully compatible with:
- [excalidraw.com](https://excalidraw.com) (File > Open)
- [VS Code Excalidraw extension](https://marketplace.visualstudio.com/items?itemName=pomdtr.excalidraw-editor)
- [Obsidian Excalidraw plugin](https://github.com/zsviczian/obsidian-excalidraw-plugin)
- Any tool that reads the `.excalidraw` JSON format

---

## Star History

<p align="center">
  <a href="https://star-history.com/#prazjain/excalidraw-cli&Date">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=prazjain/excalidraw-cli&type=Date&theme=dark" />
      <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=prazjain/excalidraw-cli&type=Date" />
      <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=prazjain/excalidraw-cli&type=Date" width="600" />
    </picture>
  </a>
</p>

---

## Built With

- [CLI-Anything](https://github.com/HKUDS/CLI-Anything) — methodology for agent-native CLI generation
- [Excalidraw](https://github.com/excalidraw/excalidraw) — open source hand-drawn style whiteboard
- [Click](https://click.palletsprojects.com/) — Python CLI framework
- [prompt_toolkit](https://python-prompt-toolkit.readthedocs.io/) — REPL interface

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. In short:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Write tests for new functionality
4. Ensure all 154+ tests pass (`python -m pytest tests/ -v`)
5. Submit a pull request

## License

This project is licensed under the MIT License — see [LICENSE](LICENSE) for details.

## Acknowledgments

- [HKUDS](https://github.com/HKUDS) for the CLI-Anything framework and methodology
- [Excalidraw](https://excalidraw.com) team for the amazing open source whiteboard
- The [Excalidraw JSON schema docs](https://docs.excalidraw.com/docs/codebase/json-schema) for format specification
