复制安装命令
用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。
复制前请先查看来源、License 和安全提示。
English · 中文 · 📖 Online Docs
用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。
复制前请先查看来源、License 和安全提示。
来源文件:README.md
English · 中文 · 📖 Online Docs
A skill that turns natural-language descriptions into .drawio XML and exports them to PNG / SVG / PDF / JPG via the native draw.io desktop CLI. It can also turn an existing codebase (Python / JS-TS / Go / Rust), Terraform / Kubernetes / docker-compose infrastructure, or a SQL schema into an auto-laid-out diagram. Works with Claude Code, Cursor, Copilot, OpenClaw, Codex, Autohand Code, Hermes, and any agent compatible with the Agent Skills format.
.drawio — structure in, layout freeCREATE TABLE statements into per-table nodes with PK/FK markers and crow's-foot foreign-key edgesshape=mxgraph.* typos).drawio file or image, reuse on demandnpx installer needs Node, the skill itself does not)
A bird's-eye view of everything the skill does — diagram types, import sources, layout engines, styling, export formats, and repurposing — in one map. Fittingly, this map was itself drawn with drawio-skill.
[!TIP] The hero image above was generated from this single prompt:
Create a microservices e-commerce architecture with Mobile/Web/Admin clients,
API Gateway (auth + rate limiting + routing), Auth/User/Order/Product/Payment
services, Kafka message queue, Notification service, and User DB / Order DB /
Product DB / Redis Cache / Stripe API
The skill is designed to route edges cleanly across different topologies, avoiding lines that cross through shapes:
![]() Star · 7 nodes Central message broker with 6 microservices radiating outward, no edge crossings on this example. |
![]() Layered · 10 nodes / 4 tiers E-commerce stack with horizontal and diagonal cross-connections routed via corridors. |
![]() Ring · 8 nodes CI/CD pipeline with a closed loop and 2 spur branches flowing along the perimeter. |
It also speaks Mermaid — standard types (flowchart, mindmap, kanban, gitGraph, timeline…) convert straight to native, editable .drawio. Here's a Kanban board (this project's own roadmap) generated from a few lines of Mermaid:
Tube-Map Mode restyles a pipeline or journey as a London-Underground-style metro map — coloured lines, octilinear (H/V/45°) routing, and white interchange circles. Here's the skill's own flow (this map is assets/tubemap.json, ~20 lines):
Full walkthrough in docs/USAGE.md.
| Platform | Command |
|---|---|
| macOS | brew install --cask drawio |
| Windows | Download installer |
| Linux | .deb/.rpm from releases; sudo apt install xvfb for headless |
Verify with drawio --version. Version ≥ 30 recommended — it unlocks Mermaid → .drawio conversion and the ELK --layout pass (both unavailable on ≤ 29). On WSL2 the CLI is the Windows desktop exe reached via /mnt/c — the skill detects this automatically (see troubleshooting). Full recipes in docs/INSTALL_CLI.md.
# Any agent (Claude Code, Cursor, Copilot, ...)
npx skills add Agents365-ai/365-skills -g
# Claude Code plugin marketplace
> /plugin marketplace add Agents365-ai/365-skills
> /plugin install drawio
# Manual install
git clone https://github.com/Agents365-ai/drawio-skill.git \
~/.claude/skills/drawio-skill
# Autohand Code global install
git clone https://github.com/Agents365-ai/drawio-skill.git \
~/.autohand/skills/drawio-skill
# Autohand Code project-level install
git clone https://github.com/Agents365-ai/drawio-skill.git \
.autohand/skills/drawio-skill
Autohand Code also supports autohand --skill-install for cataloged skills, with --project for workspace-level installs. Until this skill is listed there, use the direct clone path above.
Also indexed on SkillsMP and ClawHub.
Updating: /plugin update drawio (Claude Code), skills update drawio-skill (SkillsMP), clawhub update drawio-pro-skill (OpenClaw), or git pull for manual installs — see docs/INSTALL_SKILL.md#updates. Release history in CHANGELOG.md.
After installation, just describe what you want. For example, an ML model:
Draw a Transformer encoder-decoder for machine translation: 6-layer encoder
with self-attention, 6-layer decoder with cross-attention, input embeddings
(batch × 512 × 768), positional encoding, and a final output projection.
Annotate tensor shapes between layers and color-code by layer type.
The skill plans the layout, generates the .drawio XML, exports to your chosen format, self-checks the result, and lets you iterate.
Beyond hand-authored diagrams, the skill turns existing code, infrastructure, and schemas into diagrams — no manual coordinates. Just ask:
"Visualize the module structure of this Python project" · "Draw the class hierarchy of
mypackage"
↑ Python's logging package as a class hierarchy — one command, modules auto-boxed, every inheritance edge resolved.
Under the hood it runs a bundled extractor → auto-layout → validate pipeline:
# Import graph — Python / JS-TS / Go / Rust
python3 scripts/pyimports.py myproject --group -o graph.json
python3 scripts/jsimports.py ./src --group -o graph.json
python3 scripts/goimports.py ./module --group -o graph.json
python3 scripts/rustimports.py ./crate --group -o graph.json
# Python class-inheritance hierarchy
python3 scripts/pyclasses.py mypackage --group -o graph.json
# Infrastructure as Code — official cloud icons resolved automatically
python3 scripts/tfimports.py ./infra -o graph.json # Terraform → AWS/Azure/GCP icons
python3 scripts/k8simports.py ./manifests -o graph.json # K8s YAML/JSON → kind icons
python3 scripts/composeimports.py compose.yml -o graph.json # services + named volumes
# Live infrastructure — draw what's ACTUALLY running / deployed
terraform show -json | python3 scripts/tfstate.py - -o graph.json # deployed cloud
docker inspect $(docker ps -q)| python3 scripts/dockerimports.py - -o graph.json # running containers
kubectl get all,ing,cm,secret,pvc -o json | python3 scripts/k8simports.py - -o graph.json # live cluster
# Data & interactions
python3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER diagram
python3 scripts/ciimports.py . -o graph.json # GitHub Actions + GitLab CI -> pipeline DAG
python3 scripts/openapiimports.py openapi.yaml -o graph.json # OpenAPI/Swagger → API diagram (by method)
python3 scripts/seqlayout.py seq.json -o sequence.drawio # sequence diagram, direct to .drawio
python3 scripts/c4.py c4.json -o c4.drawio # C4 model, multi-page + drill-down
# Diff two diagrams / snapshots → colour-coded "what changed"
python3 scripts/drawiodiff.py old.drawio new.drawio -o graph.json # +added -removed ~changed
# Architecture time-lapse → self-contained HTML player of how a codebase grew
python3 scripts/timelapse.py src --importer pyimports # → architecture-evolution.html
# Reverse: describe an existing .drawio as structured Markdown (README / PR summary)
python3 scripts/explain.py architecture.drawio -o architecture.md
# Diagram → PowerPoint deck (one page per slide; C4 model → presentation)
python3 scripts/drawio2pptx.py c4.drawio -o c4.pptx # needs: pip install python-pptx
# Interactive HTML viewer — pan/zoom/search/tabs + working drill-down links, one file
python3 scripts/drawiohtml.py c4.drawio -o c4.html
# Animated data-flow SVG — edges "flow" (marching ants); renders on GitHub
python3 scripts/svgflow.py architecture.drawio -o flow.svg
# Reverse: .drawio → Mermaid flowchart (diagrams-as-code GitHub renders)
python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md
# Language variant: extract labels → translate values → apply (layout untouched)
python3 scripts/relabel.py architecture.drawio --extract -o labels.json
python3 scripts/relabel.py architecture.drawio --map labels.json -o architecture_cn.drawio
# Re-theme an existing .drawio with a style preset (e.g. dark mode)
python3 scripts/restyle.py architecture.drawio --preset dark
# Colour an existing .drawio by data → cost / latency / traffic heat map
python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.drawio
# any extractor → auto-layout → editable .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
# Image → editable .drawio — your vision extracts the graph JSON, this rebuilds it
python3 scripts/raster2drawio.py whiteboard-graph.json -o out.drawio
# Watch a diagram build itself, node by node → HTML player (+ optional GIF)
python3 scripts/buildup.py architecture.drawio --gif build.gif # → buildup.html
# Big diagram → boardroom exec summary (clustered) + click-to-drill-down to full
python3 scripts/compress.py big.drawio -o exec.drawio
# Decision-tree flowchart → click-through HTML triage runbook (no draw.io CLI needed)
python3 scripts/runbook.py triage.drawio -o triage.html
# CI: render base/head/diff PNGs + Markdown report for every .drawio a PR changed
python3 scripts/prdiff.py --base origin/main --head HEAD -o drawio-pr/report.md
# Tube-Map Mode — restyle a pipeline / journey as a metro / subway map
python3 scripts/tubemap.py metro.json -o metro.drawio
| Piece | What it does |
|---|---|
| 13 extractors | import graphs for Python · JS/TS · Go · Rust, Python class inheritance, Terraform / Kubernetes / docker-compose resource graphs (official cloud icons), SQL DDL → ERD, OpenAPI / Swagger → API diagram (operations coloured by HTTP method + schemas), CI pipelines → DAG (GitHub Actions needs: graphs + GitLab stages, with triggers, matrix sizes, reusable-workflow calls), and live infra from terraform show -json / docker inspect / kubectl get -o json (draw what's actually deployed) |
| Diagram diff | drawiodiff.py compares two .drawio (or two live snapshots) into one colour-coded graph — added=green, removed=red, changed=orange — so you can see architecture / infra drift at a glance |
| Language variants | relabel.py swaps every label via a JSON map with layout/styles/ids untouched — --extract dumps all labels, translate the values, --map applies them. One diagram → EN + CN twins for bilingual docs |
| Re-theme | restyle.py applies a style preset (built-in dark/corporate/… or your own) to an existing .drawio — palette remapped by hue so same-colored nodes stay grouped; layout and edge routing untouched |
| Metric heat map | heatmap.py recolours an existing .drawio from a CSV/JSON of per-node values — cost / latency / traffic / error-rate shaded low→high on a gradient (optional size-by-value + legend), matched by cell id or label |
| Architecture time-lapse | timelapse.py re-runs an importer across a repo's git history and assembles a self-contained HTML player — watch modules & edges appear over time (▶ play / ‹ › step) |
| Diagram → Markdown | explain.py reverses a .drawio into a structured description — components by tier, relations, per-page for C4 — for dropping an architecture summary into a README or PR |
| Interactive viewer | drawiohtml.py publishes a .drawio as one self-contained HTML — page tabs, drag-pan, wheel-zoom, node search, and a C4 model's drill-down links keep working. Share the file; no draw.io, no server |
| Diagram → PowerPoint | drawio2pptx.py turns a multi-page diagram into a 16:9 deck (one page per slide, page name as title) — a C4 model becomes a ready-to-present slideshow |
| Animated data-flow | svgflow.py makes a diagram's edges flow (marching-ants animation along each arrow) — a self-contained looping SVG that renders on GitHub, in docs, or as a slide background |
| Diagram → Mermaid | drawio2mermaid.py converts a .drawio into a Mermaid flowchart (containers → subgraphs, edge labels kept) — paste it into Markdown as diagrams-as-code that GitHub renders natively |
| Sequence engine | seqlayout.py computes lifeline / activation-bar / arrow geometry from a message list — no Graphviz, no hand placement |
| Auto-layout | Graphviz places nodes and routes orthogonal edges around them — removes the manual-coordinate ceiling for large graphs. --tune tries both directions and keeps the more readable one |
| Transitive reduction | drops edges implied by a longer path, turning a dense hairball into a traceable graph (asyncio: 149 → 46 edges) |
| Nested containers | --group boxes modules by sub-package, nested for deep package trees |
| Deterministic validator | validate.py lints the .drawio (dangling edges, duplicate ids, overlaps) before the visual self-check |
Layout needs Graphviz (brew install graphviz / apt install graphviz) — optional; everything else works without it. Full format + flag reference in references/autolayout.md. Regenerate, validate (--strict gate) and render headlessly in CI: docs/CI.md.
| Category | Examples | Notable features |
|---|---|---|
| Architecture | microservices, cloud (AWS/GCP/Azure), network topology, deployment | Tier-based swimlanes, hub-center strategy |
| C4 model | system context, containers, components | Multi-page .drawio, click-to-drill-down links |
| ML / Deep Learning | Transformer, CNN, LSTM, GRU | Tensor shape annotations, layer-type color coding |
| Flowcharts | business processes, workflows, decision trees, state machines | Semantic shapes (parallelogram I/O, diamond decisions) |
| UML | class diagrams, sequence diagrams | Inheritance / composition / aggregation arrows; lifelines + activation boxes |
| SysML / MBSE | block definition (bdd), internal block (ibd), requirement (req), parametric (par) | «block» / «requirement» compartments, satisfy/derive/verify edges, native mxgraph.sysml.* ports & flows |
| BPMN | business processes, pools & lanes | Native mxgraph.bpmn.* events/tasks/gateways, sequence vs message flows |
| Network topology | LAN/WAN, subnets, DMZ | mxgraph.networks.* device shapes, zone containers, link labels; Cisco/rack via shape search |
| Cross-functional swimlane | who-does-what processes, handoffs | Pool + role lanes, flowchart vocabulary, orthogonal handoff edges |
| Data | ER diagrams, data flow diagrams (DFD) | Table containers, PK/FK notation |
| Mermaid-authored | mind maps, gantt, timeline, journey, pie, sankey, kanban + 20 more | Native CLI conversion (≥ v30) — structure only, layout free |
| Other | org charts, wireframes | — |
Need a real AWS / Azure / GCP / Cisco / Kubernetes / UML / BPMN icon? The skill searches 10,000+ official draw.io shapes for the exact style string — so vendor icons render correctly instead of falling back to a blank box from a guessed shape=mxgraph.* name.
"Add an AWS Lambda wired to an S3 bucket" · "Use the real Kubernetes pod icon"
python3 scripts/shapesearch.py "aws lambda" --limit 5
# → Lambda (77x93)
# outlineConnect=0;...;shape=mxgraph.aws3.lambda;fillColor=#F58534;...
↑ A serverless AWS architecture — every icon is the real official draw.io shape resolved by shapesearch.py, not a hand-guessed shape= string.
Covers AWS / Azure / GCP / Cisco / Kubernetes / UML / BPMN / ER / electrical / P&ID and the general shape sets. Hand-writable style cheatsheet + search usage in references/shapes.md.
draw.io ships no modern AI/LLM logos, so an LLM-app diagram renders as generic boxes. aiicons.py resolves a brand name to a draw.io image style for any of 321 logos (OpenAI, Claude, Gemini, Mistral, Llama, Cohere, DeepSeek, Qwen, Ollama, LangChain, HuggingFace…) from lobe-icons (MIT), plus 18 data-store brands (Redis, Postgres, MongoDB, Qdrant, Milvus, Supabase…) via simple-icons (CC0) for RAG stacks.
python3 scripts/aiicons.py "claude" --json # CDN-referenced (default)
python3 scripts/aiicons.py "openai" --embed # self-contained data URI
↑ A multi-provider LLM app — every brand logo resolved by aiicons.py. Icons are referenced from the unpkg CDN by default (network needed at render time); --embed inlines them for offline use. Logos are trademarks of their owners, used for identification only.
Capture a visual style once, reuse it everywhere. Five presets are built in — default, corporate, handdrawn, colorblind-safe (Okabe-Ito palette), dark — and you can teach the skill your own style from a .drawio file or a flat image:
Draw a microservices architecture using my "corporate" style
Learn my style from ~/diagrams/brand.drawio as "mybrand"
The skill extracts colors, shapes, fonts, and edge style, renders a preview, and only saves the preset after you approve. Full preset-management commands in docs/STYLE_PRESETS.md.
Behind the scenes: check dependencies → plan layout → generate .drawio XML → export draft PNG → self-check + auto-fix (up to 2 rounds) → show to user → 5-round feedback loop until approved → final export.
| Feature | Native agent | drawio-skill |
|---|---|---|
| Self-check after export | ❌ | ✅ reads PNG, auto-fixes 6 issue types |
| Iterative review loop | ❌ manual re-prompt | ✅ targeted edits, 5-round safety valve |
| Diagram type presets | ❌ | ✅ 7 presets (ERD, UML, Seq, C4, Arch, ML, Flow) |
| Mermaid → editable .drawio | ❌ | ✅ 28 types via native CLI conversion (≥ v30) |
| Visualize a codebase | ❌ | ✅ import graphs (Py/JS/Go/Rust) + class diagrams |
| IaC → architecture diagram | ❌ | ✅ Terraform / K8s / compose → official cloud icons |
| SQL DDL → ER diagram | ❌ | ✅ CREATE TABLE → PK/FK tables, crow's-foot edges |
| Sequence diagrams | ❌ hand-placed coordinates | ✅ deterministic geometry engine (seqlayout.py) |
| C4 model | ❌ | ✅ multi-page Context→Container→Component with click-to-drill-down |
| Auto-layout for large graphs | ❌ hand-places, overlaps | ✅ Graphviz placement, ortho routing, nested containers |
| Structural validation | ❌ | ✅ deterministic .drawio linter |
| Official shape search | ❌ guesses, blank boxes | ✅ exact style for 10k+ AWS/Azure/GCP/UML shapes |
| AI/LLM brand logos | ❌ none | ✅ 321 AI + 18 data-store logos via aiicons.py |
| Grid-aligned layout | ❌ | ✅ 10px snap, routing corridors |
| Color palette | random / inconsistent | ✅ 7-color semantic system |
| Style presets | ❌ | ✅ learn from .drawio file or image |
| Feature | drawio-skill | jgraph/drawio-mcp (official) | bahayonghang/drawio-skills | GBSOSS/ai-drawio |
|---|---|---|---|---|
| Approach | Pure SKILL.md | MCP servers / Claude Code plugin / Project | YAML DSL + CLI (MCP optional) | Claude Code plugin |
| Dependencies | draw.io desktop only | draw.io desktop | draw.io desktop (MCP optional) | draw.io plugin + browser |
| Multi-agent | ✅ 6 platforms | ⚠️ MCP hosts (Claude, Cursor, VS Code) | ✅ Claude / Gemini / Codex | ❌ Claude Code only |
| Self-check + auto-fix | ✅ 2-round (reads PNG) | ❌ | ✅ validation + strict mode | ❌ screenshot only |
| Iterative review | ✅ 5-round loop | ❌ generate once | ✅ 3 workflows | ❌ |
| Diagram presets | ✅ 7 types | ❌ | ✅ paper-mode classifier | ❌ |
| Mermaid authoring | ✅ 28 types (CLI ≥ 30) | ✅ | ❌ | ❌ |
| ML/DL diagrams | ✅ tensor shapes, layer colors | ❌ | ❌ | ❌ |
| Color system | ✅ 7-color semantic | ❌ | ✅ 6 themes | ❌ |
| Official shape search | ✅ 10k+ shapes (local) | ✅ 10k+ shapes (MCP) | ❌ | ❌ |
| AI/LLM brand logos | ✅ 321 + 18 data-store | ❌ | ❌ | ❌ |
| Browser fallback | ✅ diagrams.net URL (viewer + editable) | ✅ diagrams.net URL (plugin) + inline preview | ✅ via optional MCP | ✅ diagrams.net viewer (primary) |
| Zero-config | ✅ copy skills/drawio-skill/ | ✅ | ✅ desktop-only mode | ❌ needs plugin install |
Using the official jgraph plugin? jgraph/drawio-mcp now ships an official Claude Code plugin (
/plugin install drawio@drawio) that also generates.drawioand exports via the desktop CLI. drawio-skill is complementary — reach for it when you want the code / IaC / SQL / OpenAPI importers, AI-brand logos, deterministic sequence & C4 generators, self-check + review loop, and the interactive HTML viewer, all from a single SKILL.md with no MCP server.
Full comparison + key-advantages summary in docs/COMPARISON.md (with audit timestamp).
Good fit:
Reach for a sibling skill instead when you need:
Part of the Agents365-ai diagram-skill family — pick the right tool for the job:
| Skill | Style | Best for |
|---|---|---|
| excalidraw-skill | Hand-drawn / sketchy | Whiteboard mockups, informal diagrams |
| mermaid-skill | Text-based, auto-layout | README-embeddable, version-control friendly |
| plantuml-skill | UML-focused | Class / sequence diagrams in CI pipelines |
| tldraw-skill | Whiteboard collaboration | Casual sketches, FigJam-style boards |
If this skill helps you, consider supporting the author:
WeChat Pay |
Alipay |
Buy Me a Coffee |
Give a Reward |
Agents365-ai
name: drawio-skill
version: 2.1.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, SysML / MBSE diagrams (block definition, internal block, requirement, parametric), BPMN business process diagrams, swimlane / cross-functional flowcharts, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. Optional auto-layout (scripts/autolayout.py) needs Graphviz (dot).
platforms: [macos, linux, windows]
metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"2.1.0"}Generate .drawio XML files and export to PNG/SVG/PDF/JPG locally using the native draw.io desktop app CLI.
Supported formats: PNG, SVG, PDF, JPG — no browser automation needed.
PNG, SVG, and PDF exports support --embed-diagram (-e) — the exported file contains the full diagram XML, so opening it in draw.io recovers the editable diagram. Use double extensions (name.drawio.png) to signal embedded XML.
Use this skill for: polished, precise diagrams (architecture, network, strict UML, ERD), anything needing solid opaque fills, 10,000+ stock/branded shapes, swimlanes, or custom geometry, exported as editable PNG/SVG/PDF.
Do NOT use it — route elsewhere — for:
When the workflow references one of these, read it on demand — none of them need to be in context up front.
| File | Read it when |
|---|---|
references/toolbox.md | You're not sure which bundled script fits a request, or want to chain several — a map of all 31 scripts grouped by use-case (author / import code / import IaC / import API spec / live infra / compare / annotate / reverse-export / utilities) with an "I have X, I want Y → use Z" guide |
references/xml-authoring.md | You're about to hand-write .drawio XML (workflow step 3) — file skeleton, shape/edge cells, containers, connection distribution, palette, spacing/grid rules. Not needed when a bundled generator writes the XML |
references/mermaid-authoring.md | The diagram is a standard type with no custom styling/icon needs (flowchart, state, gantt, mindmap, timeline, journey, pie, …) and the CLI is ≥ v30 — author it as Mermaid text and let the CLI convert to native .drawio (structure only, layout free). Also documents the CLI's ELK --layout pass for XML |
references/diagram-types.md | The user names a specific diagram type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart, SysML, BPMN, network topology, swimlane) |
references/shapes.md + scripts/shapesearch.py | The diagram needs a specific shape — a cloud icon (AWS/Azure/GCP), Cisco/Kubernetes/network symbol, UML/BPMN/ER/electrical/P&ID element — or any time you'd otherwise guess a style= string. shapesearch.py "<keywords>" returns the exact official style for 10k+ shapes |
scripts/aiicons.py | The diagram involves an AI/LLM brand (OpenAI, Claude, Gemini, Mistral, Llama, HuggingFace, Ollama, LangChain, …) — aiicons.py "<brand>" returns a draw.io image style for the brand logo (lobe-icons via CDN; --embed to inline). draw.io has no built-in AI logos. See references/shapes.md → "AI / LLM brand logos" |
references/style-presets.md | The user asks to learn / save / list / set-default / delete a style preset, or you've resolved an active preset and need the application rules |
references/style-extraction.md | You're inside the Learn flow and need the extraction procedure (called from style-presets.md) |
references/troubleshooting.md | An export fails, vision rejects a PNG, or a rendering looks wrong |
scripts/repair_png.py | After every -e PNG export — fixes draw.io's truncated IEND chunk (issue #8) |
scripts/encode_drawio_url.py | The CLI is unavailable and you need a browser-fallback diagrams.net URL (--edit for an editable editor URL) |
references/autolayout.md | The diagram is large or layout-heavy (dependency/call graph, code structure, >~15 nodes) and you want Graphviz to place nodes + route edges instead of hand-placing coordinates |
scripts/pyimports.py · jsimports.py · goimports.py · rustimports.py | The user wants to visualize a Python, JS/TS, Go, or Rust project structure — extracts the import graph (transitive-reduced, optional --group containers, nested by sub-package) for autolayout |
scripts/pyclasses.py | The user wants a Python class hierarchy / class diagram — extracts classes + inheritance edges (boxed by module with --group) for autolayout |
scripts/tfimports.py · k8simports.py · composeimports.py | The user wants to visualize declared infrastructure (Terraform .tf, Kubernetes manifests, or docker-compose) — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) for autolayout |
scripts/tfstate.py · dockerimports.py (+ k8simports.py) | The user wants to draw what is ACTUALLY running / deployed — pipe terraform show -json (deployed state), docker inspect $(docker ps -q) (live containers), or kubectl get all,ing,cm,secret,pvc -o json (live cluster, via k8simports) and get the real topology with the same official icons. See references/live-infra.md |
scripts/drawiodiff.py | The user wants to compare / diff two diagrams or two snapshots ("what changed", infra drift) — drawiodiff.py old.drawio new.drawio -o diff.json emits a colour-coded graph (added=green, removed=red, changed=orange, same=grey) for autolayout. Matches by cell id (importer/live-snapshot output) or --by-label (hand-drawn) |
scripts/timelapse.py | The user wants an architecture time-lapse / to see how a codebase's structure evolved over git history — timelapse.py <dir> --importer pyimports re-runs an importer at each sampled commit and assembles a self-contained HTML player (embedded frames, play/step controls). Best on a package with real import edges (point <dir> at the module root) |
scripts/explain.py | The user wants to describe / document / summarize an existing .drawio in words (reverse of generating one) — explain.py diagram.drawio emits structured Markdown: components grouped by container/tier, relations (A —label→ B), per-page sections for multi-page/C4. Good for a README/PR summary or a text-only read-out |
scripts/drawio2pptx.py | The user wants a PowerPoint deck / slides from a diagram — drawio2pptx.py diagram.drawio -o deck.pptx puts each page on its own 16:9 slide (page name as title), so a multi-page C4 model becomes a ready-to-present deck. Needs python-pptx (pip install python-pptx) + the draw.io CLI |
scripts/drawiohtml.py | The user wants a shareable interactive viewer for a diagram (pan / zoom / search, no draw.io needed) — drawiohtml.py diagram.drawio -o viewer.html inlines every page's SVG into ONE self-contained HTML with page tabs, drag-pan, wheel-zoom, node search (Enter cycles + centres matches) and working drill-down links (a C4 model's data:page/id links switch tabs). No server, no external requests — send the file to anyone |
scripts/svgflow.py | The user wants an animated / "flowing" diagram (data-flow, moving edges) — svgflow.py diagram.drawio -o flow.svg exports to SVG and makes every edge a marching-ants animation (dashes travel along the arrows). Self-contained looping .svg that renders on GitHub / any browser; --speed / --dash / --reverse |
scripts/drawio2mermaid.py | The user wants to convert a .drawio into Mermaid text (diagrams-as-code for a Markdown file that GitHub renders) — drawio2mermaid.py diagram.drawio emits a flowchart (containers → subgraphs, edge labels kept, cylinder/rhombus shapes mapped); --fenced wraps in ```mermaid, multi-page → one graph per page. Structural only (styling/icons don't survive) |
scripts/sqlerd.py | The user wants an ER diagram from SQL DDL — parses CREATE TABLE statements into per-table nodes (columns with PK/FK markers) and crow's-foot FK edges for autolayout |
scripts/ciimports.py | The user wants a CI pipeline diagram (GitHub Actions workflows or GitLab CI) — ciimports.py <repo-root> reads .github/workflows/*.yml + .gitlab-ci.yml and emits jobs (runner, matrix size, reusable-workflow calls), needs: dependency edges, per-workflow trigger nodes, and stage/workflow containers for autolayout. Needs PyYAML |
scripts/openapiimports.py | The user wants an API diagram from an OpenAPI / Swagger spec — openapiimports.py spec.yaml maps each operation to a node coloured by HTTP method (GET blue, POST green, PUT/PATCH orange, DELETE red) plus one node per component schema, with edges from operations to the schemas they use and between nested schemas. --group boxes by tag, --no-schemas shows just the endpoint surface; feeds autolayout |
scripts/heatmap.py | The user wants to colour an existing .drawio by data (a cost / latency / traffic / error-rate heat map) — heatmap.py diagram.drawio -m metrics.csv matches each metric (CSV key,value or JSON {key:value}) to a node by id or label and recolours it along a gradient (--palette heat|cool|warm, --reverse), optionally scaling node size (--size) and adding a legend. Post-processes any diagram; export as usual |
scripts/seqlayout.py | The user wants a sequence diagram — describe participants + messages as JSON and the script computes all lifeline/activation/arrow geometry deterministically (no hand-placed coordinates, no Graphviz needed) |
scripts/c4.py | The user wants a C4 model (System Context / Container / Component) — levels JSON in, one multi-page .drawio out with official C4 shapes/colors and click-to-drill-down links between levels |
scripts/relabel.py | The user wants a language variant or bulk text swap of an existing .drawio (e.g. an EN diagram re-labelled in Chinese for a bilingual README) — relabel.py diagram.drawio --extract -o labels.json dumps every label as an identity JSON map; translate the values (keep the keys), then relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio swaps them with layout/styles/ids untouched |
scripts/restyle.py | The user wants to re-theme an EXISTING .drawio ("make this dark", "apply my corporate style to this diagram") — restyle.py diagram.drawio --preset <name> remaps every vertex fill/stroke to the preset palette by hue, applies font/extras (dark fontColor, edge color, background), and leaves layout, shapes, and edge routing untouched. Presets resolve like Step 0 (user dir, then built-ins) |
scripts/edgeports.py | Edges stack on top of each other where they meet a shape — the usual swimlane/cross-functional complaint, and anywhere a node has several connections leaving the same side. edgeports.py diagram.drawio pins exitX/exitY+entryX/entryY: it picks the side of each node facing the other endpoint, then spreads that side's edges over evenly-spaced slots ordered by the far endpoint's position, so they keep their relative order instead of crossing. Resolves absolute coordinates through swimlane parents, skips ends you already pinned, and is idempotent. It is a port assigner, not a router — it separates lines at the shape boundary, it will not stop an edge crossing an unrelated shape mid-run (add waypoints for that) |
scripts/validate.py | You generated a .drawio (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check. --score prints a readability score for comparing layout variants |
scripts/raster2drawio.py | The user has an image of a diagram (whiteboard photo, legacy PNG, Visio screenshot) and wants an editable .drawio — read the image with your own vision, extract nodes/edges as JSON (schema + full workflow in references/derasterize.md), then raster2drawio.py graph.json -o out.drawio honours those coordinates/labels/shapes; nodes missing x/y fall back to autolayout.py placement |
scripts/buildup.py | The user wants a diagram to build itself node-by-node as a video/GIF (a construction time-lapse of ONE static diagram — distinct from timelapse.py's git-history animation) — buildup.py diagram.drawio reveals cells in topological (dependency) order into a self-contained HTML player (play/pause/step/scrub); --gif also exports an animated GIF (needs Pillow). Needs the draw.io CLI |
scripts/compress.py | The user wants an executive / boardroom summary of a big diagram — collapses clusters (pure-Python label propagation, no networkx) into one labeled node each with aggregated inter-cluster edges, emitting a 2-page .drawio (exec view + click-to-drill-down into the full original). Claude can rename clusters semantically afterward. Needs Graphviz dot |
scripts/runbook.py | The user wants a flowchart/decision-tree .drawio turned into a click-through triage app (on-call runbook) — runbook.py flow.drawio reads the XML (no draw.io CLI needed) and emits a self-contained HTML runbook: current-step text, per-edge choice buttons, breadcrumb trail, Back/Restart, end-state on terminal nodes |
scripts/prdiff.py | You're setting up automated PR diagram review in CI — for every .drawio changed between two git refs it renders base/head/diff PNGs and emits a Markdown report; ships with a composite GitHub Action (.github/actions/drawio-diff/) that posts a sticky PR comment. See references/pr-bot.md |
scripts/tubemap.py | The user wants a metro / subway / tube map — a system, pipeline, or journey drawn as coloured transit lines with octilinear (H/V/45°) routing, white interchange circles, and station stops. Compose a metro JSON (lines = ordered stations on an integer grid, shared stations = interchanges), then tubemap.py metro.json -o metro.drawio. Stdlib-only; schema + the one grid rule in references/tubemap.md |
The draw.io desktop app must be installed and the CLI accessible:
macOS sandbox / sandbox isolation note (e.g., codex.app): In some sandboxed macOS environments, invoking the draw.io desktop CLI (even drawio --version) can crash the draw.io process or produce no output. If that happens, treat the CLI as unavailable in this sandbox isolation — do not keep retrying inside the sandbox. Prefer a non-sandboxed host environment (outside sandbox isolation) for any CLI export work, or use the browser fallback / XML-only outputs.
# macOS (Homebrew — recommended; CLI binary is `drawio`, not `draw.io`)
brew install --cask drawio
drawio --version
# macOS (full path if not in PATH)
/Applications/draw.io.app/Contents/MacOS/draw.io --version
# Windows
"C:\Program Files\draw.io\draw.io.exe" --version
# Linux
drawio --version
Install draw.io desktop if missing:
brew install --cask drawio or download from https://github.com/jgraph/drawio-desktop/releases.deb/.rpm from https://github.com/jgraph/drawio-desktop/releases — do not use snap (AppArmor sandbox denies secrets/keyring on servers, causes crash)Before starting the workflow, assess whether the user's request is specific enough. If key details are missing, ask 1-3 focused questions:
./artifacts/"). Don't ask if they didn't mention one.Skip clarification if the request already specifies these details or is clearly simple (e.g., "draw a flowchart of X").
Step 0 — Resolve active preset. Determine which (if any) user-defined style preset applies to this generation.
<name> style", "with my <name> style", "in <name> mode", "in the style of <name>". A bare with <name> does not count — "draw a diagram with redis" names a component, not a style. If a clear match is found → active preset = <name>.~/.drawio-skill/styles/ for any file with "default": true. If found → active preset = that one.Load the preset JSON from ~/.drawio-skill/styles/<name>.json, falling back to <this-skill-dir>/styles/built-in/<name>.json. If the named preset exists in neither location, tell the user the name is unknown, list the available presets (user dir + built-in), and stop — do not silently fall back to defaults.
When a preset loads successfully, mention it in the first line of the reply: "Using preset <name> (confidence: <level>)." See references/style-presets.md → "Applying a preset" for how the preset changes color/shape/edge/font decisions.
drawio --version (the canonical name for Homebrew cask, jgraph .deb/.rpm, Arch AUR), (b) draw.io --version (older builds, some custom symlinks, some distro packages), (c) macOS .app direct: /Applications/draw.io.app/Contents/MacOS/draw.io --version, (d) Windows: "C:\Program Files\draw.io\draw.io.exe" --version. The first one that prints a version is your binary; remember the exact path/name and substitute it for drawio in every export command below. Do not copy the example commands verbatim if your binary is named differently — the examples use drawio only because it's the most common. On macOS-Homebrew, drawio is just a thin wrapper script that execs /Applications/draw.io.app/Contents/MacOS/draw.io — they run the same engine, so candidate (c) is only needed when the drawio wrapper is absent (e.g. the app was installed by drag-and-drop without the cask). Also note the major version the command printed: ≥ 30 unlocks Mermaid→.drawio conversion and the ELK --layout pass (see references/mermaid-authoring.md); on ≤ 29 both are unavailable — .mmd input fails and --layout corrupts argument parsing — so never emit those flags there..drawio file, choosing the authoring mode: (a) Mermaid → CLI convert when the diagram is a standard type with no custom styling/icon needs and the CLI is ≥ v30 — write a .mmd and run drawio -x -f xml -o <name>.drawio <name>.mmd, see references/mermaid-authoring.md (structure only; layout comes free; never --layout afterwards). (b) Hand-written XML for custom styling, vendor icons, swimlanes, precise geometry — read references/xml-authoring.md first (skeleton, cell forms, palette, spacing rules). (c) A bundled generator for the data-driven cases below. For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place — describe the graph as JSON and run python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio to compute node positions + orthogonal edge routing via Graphviz (see references/autolayout.md; add --tune to auto-pick the more readable direction). For a Python / JS-TS / Go / Rust project, the matching importer (scripts/pyimports.py, jsimports.py, goimports.py, or rustimports.py) extracts the import graph (transitive-reduced; add --group to box modules by sub-package, nested for deep trees) ready for autolayout; for a Python class hierarchy, scripts/pyclasses.py extracts classes + inheritance instead; for Terraform / Kubernetes / docker-compose (scripts/tfimports.py, k8simports.py, composeimports.py), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw what is actually running rather than the declared config, pipe terraform show -json into scripts/tfstate.py or docker inspect $(docker ps -q) into scripts/dockerimports.py (k8simports.py already accepts live kubectl get ... -o json) — see references/live-infra.md; for an ER diagram from SQL DDL, scripts/sqlerd.py parses CREATE TABLE into table nodes + crow's-foot FK edges; for an API diagram from an OpenAPI / Swagger spec, scripts/openapiimports.py maps operations (coloured by HTTP method) + component schemas into a graph for autolayout; for a CI pipeline diagram (GitHub Actions / GitLab CI), scripts/ciimports.py extracts jobs, needs: edges, triggers, and stage/workflow containers. To turn any generated .drawio into a metric heat map — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv (matches on cell id or label; --palette, --size, legend). For a sequence diagram, skip autolayout entirely — describe participants + messages as JSON and run python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a C4 model, python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels labelBackgroundColor=#ffffff;fontSize=11 and use edge geometry x/y offsets plus <mxPoint as="offset" /> to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. For hand-placed diagrams where edges cross shapes (architecture, network topology, deployment, UML), fix the routing in the XML — run python3 <this-skill-dir>/scripts/edgeports.py <name>.drawio to distribute stacked edges over each shape's perimeter automatically, then add <Array as="points"> waypoints or widen node spacing for any edge still crossing a shape mid-run (see references/xml-authoring.md). No CLI flag reroutes edges without moving nodes: every --layout preset is an ELK node layout that re-places vertices, and an unrecognised value opens a modal error dialog that hangs headless runs. draw.io's obstacle-avoiding router is editor-side only. After generating any .drawio, run python3 <this-skill-dir>/scripts/validate.py <name>.drawio for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. ./artifacts/, docs/images/), use that instead — mkdir -p the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.-e at this step — the embedded zTXt mxGraphModel chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. Cap the preview width with --width 2000 (not -s 2) — Claude's vision API rejects images larger than 2576×2576px with "Unable to resize image — dimensions exceed the 2576x2576px limit", and -s 2 on a medium-or-larger diagram easily overshoots that ceiling. Save the clean preview as <name>.png (single extension). Embedding and full-resolution scale are for the final export only (step 7).-e by mistake — re-export without -e and retry once. If it still fails, skip self-check and continue to step 6.-e here (PNG/SVG/PDF) so the deliverable stays editable in draw.io; save as <name>.drawio.png to signal embedded XML. For PNG with -e, run python3 <this-skill-dir>/scripts/repair_png.py <name>.drawio.png immediately after — draw.io's CLI truncates the IEND chunk in -e PNG output (8 bytes missing), producing a corrupt file that vision APIs and strict PNG decoders reject (issue #8). Report file paths.If drawio --version crashes or prints nothing (common in restricted macOS sandbox isolation like codex.app):
scripts/encode_drawio_url.py) or deliver the .drawio XML only.Escalation rule:
After exporting the draft PNG, use the agent's vision capability (e.g., Claude's image input) to read the image and check for these issues before showing the user. If the agent does not support vision, skip self-check and show the PNG directly.
Important: the draft PNG read here must have been exported without -e. Draw.io's -e flag emits a PNG with a truncated IEND chunk (8 bytes of type+CRC missing) that the Anthropic vision API rejects with 400 "Could not process image" (issue #8). The simplest fix for the preview step is to skip -e entirely; the final export in step 7 keeps -e and runs the repair snippet. If you see the 400 error here, re-export without -e and retry once; if it still fails (any other reason), skip self-check and proceed to step 6.
| Check | What to look for | Auto-fix action |
|---|---|---|
| Overlapping shapes | Two or more shapes stacked on top of each other | Shift shapes apart by ≥200px |
| Clipped labels | Text cut off at shape boundaries | Increase shape width/height to fit label |
| Missing connections | Arrows that don't visually connect to shapes | Verify source/target ids match existing cells |
| Off-canvas shapes | Shapes at negative coordinates or far from the main group | Move to positive coordinates near the cluster |
| Edge-shape overlap | An edge/arrow visually crosses through an unrelated shape | Add waypoints (<Array as="points">) to route around the shape, or increase spacing between shapes |
| Stacked edges | Multiple edges overlap each other on the same path | Distribute entry/exit points across the shape perimeter (use different exitX/entryX values) |
| Edge-label overlap | Edge text overlaps another label, line, or node in the exported PNG | Keep the label on the edge, add a white label background, and move it locally with edge geometry x/y offsets into adjacent whitespace |
After self-check, show the exported image and ask the user for feedback.
Targeted edit rules — for each type of feedback, apply the minimal XML change:
| User request | XML edit action |
|---|---|
| Change color of X | Find mxCell by value matching X, update fillColor/strokeColor in style |
| Add a new node | Append a new mxCell vertex with next available id, position near related nodes |
| Remove a node | Delete the mxCell vertex and any edges with matching source/target |
| Move shape X | Update x/y in the mxGeometry of the matching mxCell |
| Resize shape X | Update width/height in the mxGeometry of the matching mxCell |
| Add arrow from A to B | Append a new mxCell edge with source/target matching A and B ids |
| Change label text | Update the value attribute of the matching mxCell |
| Change layout direction | Full regeneration — rebuild XML with new orientation |
Rules:
{name}.png (no -e) each iteration — do not create v1, v2, v3 files. -e is reserved for the final export in step 7..drawio file in draw.io desktop for fine-grained adjustmentsOnce the user approves:
.drawio source file and exported image(s).drawio file in draw.io desktop for fine-tuning — open diagram.drawio (macOS), xdg-open (Linux), start (Windows)A style preset is a named JSON file capturing a user's visual preferences (palette, shapes, font, edges). When active, it fully replaces the built-in color/shape conventions in this skill.
Lookup order when SKILL.md's Step 0 resolves a preset name:
~/.drawio-skill/styles/<name>.json — user presets (survive git pull)<this-skill-dir>/styles/built-in/<name>.json — shipped built-ins (default, corporate, handdrawn, colorblind-safe, dark)Always lowercase the user-provided name before any file operation — the schema enforces lowercase.
For everything else — Learn flow (extracting a preset from a file), management ops (list/default/delete/rename), application rules (color lookup, shape keywords, edges, fonts, extras, interaction with diagram-type presets), and validation — read references/style-presets.md. It's only needed when the user invokes those flows or when an active preset must be applied to the current generation.
Before hand-writing any .drawio XML (step 3), read references/xml-authoring.md — file skeleton, shape/edge cell forms, containers, connection-point distribution, color palette, and spacing/grid rules all live there. Skip it only when a bundled generator writes the XML for you (autolayout.py + importers, seqlayout.py).
Two rules worth stating even here: never reuse ids 0/1 (reserved root cells), and every edge mxCell needs a <mxGeometry relative="1" as="geometry" /> child — self-closing edge cells do not render.
There are two export modes:
-e. Output diagram.png. Required for vision self-check; using -e here triggers a 400 "Could not process image" error from the vision API (issue #8).-e. Output diagram.drawio.png. The embedded XML keeps the file editable in draw.io.All commands below write
drawioas a placeholder for the binary you resolved in Step 1. If your binary is on PATH asdraw.io(with dot — some older or distro-packaged installs), substitutedraw.iothroughout. If only the macOS.appor Windows.exeis available, use the full path variant shown a few lines down.
# Preview PNG (use this in step 4, before self-check) — NO -e, width-capped to stay under vision's 2576px ceiling
drawio -x -f png --width 2000 -o diagram.png input.drawio
# Final PNG (step 7, after user approval) — WITH -e, double extension
drawio -x -f png -e -s 2 -o diagram.drawio.png input.drawio
# macOS — full path (if not in PATH); preview / final variants
/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png --width 2000 -o diagram.png input.drawio
/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png -e -s 2 -o diagram.drawio.png input.drawio
# Windows
"C:\Program Files\draw.io\draw.io.exe" -x -f png -e -s 2 -o diagram.drawio.png input.drawio
# Linux (headless — requires xvfb-run; on servers add HOME and --disable-gpu)
export HOME=${HOME:-/tmp}
xvfb-run -a --server-args="-screen 0 1280x1024x24" \
drawio -x -f png -e -s 2 -o diagram.drawio.png input.drawio --disable-gpu
# Running as root (CI / Docker)? Append --no-sandbox AT THE END (placing it earlier makes drawio treat it as the input filename)
# SVG export (final — -e is safe; SVG is text)
drawio -x -f svg -e -o diagram.svg input.drawio
# PDF export (final)
drawio -x -f pdf -e -o diagram.pdf input.drawio
# Custom output directory (e.g. CI artifacts dir) — create if missing, then export there
mkdir -p ./artifacts && drawio -x -f png -e -s 2 -o ./artifacts/diagram.drawio.png input.drawio
-e PNG export)draw.io CLI truncates the IEND chunk when emitting -e PNGs — the file ends with the 4-byte IEND length field but the IEND type + CRC (8 bytes) are missing. Result: vision APIs return 400 "Could not process image" and strict PNG decoders error out. SVG/PDF are unaffected.
Run this immediately after every -e PNG export:
python3 <this-skill-dir>/scripts/repair_png.py diagram.drawio.png
The script's endswith(IEND) guard makes it a no-op once draw.io fixes the bug upstream — safe to run unconditionally.
Key flags:
-x — export mode (required)-f — format: png, svg, pdf, jpg-e — embed diagram XML in output (PNG, SVG, PDF) — exported file remains editable in draw.io. Skip for the preview PNG used in step 5 self-check — -e PNGs have a truncated IEND chunk that vision APIs reject (issue #8). For final PNG export, keep -e and run scripts/repair_png.py (see Post-export PNG repair). SVG/PDF unaffected.-s — scale: 1, 2, 3 (2 recommended for final PNG; do NOT use for the step-4 preview — see --width)--width <px> — target width in pixels (no short form; -w does not exist and silently breaks the input-file parser). Use --width 2000 for the step-4 preview to keep the PNG under Claude's 2576×2576 vision ceiling. There's also a --height <px> flag for tall-narrow diagrams. Don't combine --width with -s.-o — output file path; accepts any directory (e.g. ./artifacts/diagram.drawio.png) — mkdir -p the target dir first. Use .drawio.png double extension when embedding.--layout <preset|json> — CLI ≥ v30 only — Post-generate layout pass on XML input. Accepts only the ELK presets verticalFlow, horizontalFlow, verticalTree, horizontalTree, radialTree, organic, or a JSON layout array — all of them re-place nodes as well as routing edges; alternative to autolayout.py when Graphviz is missing. Any other value opens a modal Unknown layout: dialog that hangs a headless run — there is no edge-routing-only mode on the CLI. Never combine with Mermaid-converted files (already laid out). On ≤ 29 this flag breaks argument parsing — don't emit it. See references/mermaid-authoring.md-b — border width around diagram (default: 0, recommend 10)-t — transparent background (PNG only)--page-index <n> — export one page of a multi-page file. 1-based in current drawio-desktop (verified on 29.7.8: --page-index 2 exports the second page; older docs claimed 0-based). Default: first page. --page-range 2..3 also worksWhen the draw.io desktop CLI is unavailable, generate a client-side URL:
python3 <this-skill-dir>/scripts/encode_drawio_url.py input.drawio # read-only viewer
python3 <this-skill-dir>/scripts/encode_drawio_url.py --edit input.drawio # opens in the editor
Default prints a https://viewer.diagrams.net/...#R… viewer URL; --edit prints a https://app.diagrams.net/...#create=… URL that opens straight into the editable editor. Either way the diagram XML is encodeURIComponent-encoded, deflate-compressed, and base64'd into the URL fragment — the fragment (after #) is never sent to the server, so nothing is uploaded. The encodeURIComponent step is mandatory: without it, any diagram containing a literal % or non-ASCII (e.g. CJK) label makes the browser throw "URI malformed" and the diagram never opens.
Open the URL with open "$URL" (macOS) / xdg-open "$URL" (Linux). On WSL2 / Windows, cmd.exe drops the #fragment — write a .url shortcut file and open that instead (see references/troubleshooting.md → "WSL2 / Windows specifics").
When tools are unavailable, degrade gracefully:
| Scenario | Behavior |
|---|---|
| draw.io CLI missing, Python available | Use browser fallback (diagrams.net URL) |
| draw.io CLI missing, Python missing | Generate .drawio XML only; instruct user to open in draw.io desktop or diagrams.net manually |
| draw.io CLI crashes / no output in macOS sandbox isolation | Treat CLI as unavailable in-sandbox; use browser fallback / XML-only; ask user to run CLI exports in a non-sandboxed host environment |
| Vision unavailable for self-check | Skip self-check (step 5); proceed directly to showing user the exported PNG |
| Export fails (Chromium/display issues) | On Linux, retry with xvfb-run -a; if still failing, deliver .drawio XML and suggest manual export |
| Export fails on Linux server (headless) | Try in order: (1) xvfb-run -a, (2) append --no-sandbox at the very end if root, (3) add --disable-gpu, (4) export HOME=/tmp, (5) install apt deps (libgtk-3-0 libnotify4 libnss3 libgbm1 libasound2t64 etc.), (6) fall back to tomkludy/drawio-renderer Docker (REST API for headless export) |
# Prefer the Homebrew / Linux-package binary name (no dot)
if command -v drawio &>/dev/null; then
DRAWIO="drawio"
# Fall back to the dot-named binary (older installs, manual symlinks)
elif command -v draw.io &>/dev/null; then
DRAWIO="draw.io"
# macOS .app bundle (binary inside the bundle keeps the dot)
elif [ -f "/Applications/draw.io.app/Contents/MacOS/draw.io" ]; then
DRAWIO="/Applications/draw.io.app/Contents/MacOS/draw.io"
# WSL2: the CLI is the Windows desktop exe, reached via /mnt/c (note the space)
elif grep -qi microsoft /proc/version 2>/dev/null && [ -f "/mnt/c/Program Files/draw.io/draw.io.exe" ]; then
DRAWIO="/mnt/c/Program Files/draw.io/draw.io.exe"
else
echo "drawio not found — install from https://github.com/jgraph/drawio-desktop/releases (Homebrew: brew install --cask drawio)"
fi
On WSL2 / native Windows, opening exported files and browser-fallback URLs needs path conversion + a .url-file workaround (cmd.exe drops URL #fragments) — see the "WSL2 / Windows specifics" section in references/troubleshooting.md.
When something looks wrong (export fails, vision rejects a PNG, layout broken, edges misroute), see references/troubleshooting.md for a row-by-row mistake → fix table.
When the user requests a specific diagram type, read references/diagram-types.md for the matching preset (shapes, edges, layout direction). Pick by user phrasing:
| User says | Section in references/diagram-types.md |
|---|---|
| "ER diagram", "schema diagram", "data model" | ERD |
| "UML class diagram", "class diagram" | UML Class |
| "sequence diagram", "interaction diagram", "lifeline" | Sequence |
| "architecture", "system diagram", "service diagram" | Architecture |
| "neural network", "model architecture", "ML diagram", "deep learning" | ML / Deep Learning Model |
| "flowchart", "decision tree", "process flow" | Flowchart |
| "C4", "system context diagram", "container diagram", "component diagram" | C4 Model |
| "SysML", "MBSE", "block definition diagram", "internal block diagram", "requirement diagram", "parametric diagram" | SysML |
| "BPMN", "business process", "process model", "pool and lanes", "workflow diagram" | BPMN |
| "network topology", "network diagram", "LAN/WAN", "subnet", "firewall diagram" | Network Topology |
| "swimlane diagram", "cross-functional flowchart", "who does what", "handoff diagram" | Cross-Functional Flowchart |
The diagram-type preset sets structural style keywords. If a user style preset is also active (see ## Style Presets), keep the structural keywords and layer color/font/edge/extras on top — read references/style-presets.md → "Interaction with diagram-type presets" for the merge rules.
评论 (0)
暂无评论,成为第一个评论者吧!