Skip to content

Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.

feat(drawio): borrow shape search, URL fix, WSL2 support from drawio-mcp (#20)

Agents365.ai979b6dc5c8eb
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 481c6a2..ba1bd8e 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.10.0
+version: 1.11.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, 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":"1.10.0"}
+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":"1.11.0"}
---
# Draw.io Diagrams
@@ -26,11 +26,12 @@ When the workflow references one of these, read it on demand — none of them ne
| File | Read it when |
|---|---|
| `references/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, architecture, ML/DL, flowchart) |
+| `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 |
| `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 |
+| `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 |
@@ -202,6 +203,8 @@ Always lowercase the user-provided name before any file operation — the schema
| `shape=cylinder3;` | cylinder — databases |
| `swimlane;` | group/container with title bar |
+For **vendor/branded icons** (AWS/Azure/GCP/Cisco/Kubernetes) and any non-trivial shape, don't guess the `shape=mxgraph.*` name — a wrong name renders as a blank box. Run `python3 <this-skill-dir>/scripts/shapesearch.py "<keywords>"` to get the exact official style + size, or see `references/shapes.md` for the hand-writable cheatsheet.
+
### Required properties
```xml
@@ -407,13 +410,16 @@ The script's `endswith(IEND)` guard makes it a no-op once draw.io fixes the bug
### Browser fallback (no CLI needed)
-When the draw.io desktop CLI is unavailable, generate a client-side viewer URL:
+When the draw.io desktop CLI is unavailable, generate a client-side URL:
```bash
-python3 <this-skill-dir>/scripts/encode_drawio_url.py input.drawio
+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
```
-Prints a `https://viewer.diagrams.net/...` URL with the diagram XML deflate-compressed and base64-encoded into the URL fragment. The fragment (after `#`) is never sent to the server, so nothing is uploaded — the diagram opens client-side for viewing and editing. Useful when the user cannot install the desktop app.
+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").
### Fallback chain
@@ -437,14 +443,19 @@ if command -v drawio &>/dev/null; then
# Fall back to the dot-named binary (older installs, manual symlinks)
elif command -v draw.io &>/dev/null; then
DRAWIO="draw.io"
-# Final fallback: macOS .app bundle (binary inside the bundle keeps the dot)
+# 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 `#fragment`s) — see the "WSL2 / Windows specifics" section in `references/troubleshooting.md`.
+
## Common Mistakes
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.
diff --git a/skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md b/skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md
new file mode 100644
index 0000000..3f97ac5
--- /dev/null
+++ b/skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md
@@ -0,0 +1,17 @@
+# Shape index attribution
+
+`shape-index.json.gz` is a gzipped copy of the shape search index from
+[jgraph/drawio-mcp](https://github.com/jgraph/drawio-mcp) (`shape-search/search-index.json`),
+which is generated from the official draw.io / diagrams.net client shape
+libraries. Both upstream sources are licensed under the **Apache License 2.0**.
+
+- Each entry is `{style, w, h, title, tags, type}` for one palette shape.
+- 10,446 shapes spanning AWS, Azure, GCP, Cisco, Kubernetes, UML, BPMN, P&ID,
+ electrical, flowchart, network, and the general shape sets.
+- Used read-only by `scripts/shapesearch.py` to resolve exact official style
+ strings instead of hand-guessing them.
+
+To refresh against a newer draw.io release, regenerate upstream with
+`shape-search/generate-index.js` in the drawio-mcp repo, then re-gzip:
+
+ gzip -9 -c search-index.json > data/shape-index.json.gz
diff --git a/skills/drawio-skill/data/shape-index.json.gz b/skills/drawio-skill/data/shape-index.json.gz
new file mode 100644
index 0000000..7b6ad4b
Binary files /dev/null and b/skills/drawio-skill/data/shape-index.json.gz differ
diff --git a/skills/drawio-skill/references/shapes.md b/skills/drawio-skill/references/shapes.md
new file mode 100644
index 0000000..da67b56
--- /dev/null
+++ b/skills/drawio-skill/references/shapes.md
@@ -0,0 +1,116 @@
+# Shape vocabulary & search
+
+Read this when a diagram needs a **specific shape** — a cloud-provider icon
+(AWS/Azure/GCP), a network/Cisco/Kubernetes symbol, a UML/BPMN/ER element, an
+electrical or P&ID part — or any time you'd otherwise *guess* a `style=` string.
+
+There are two ways to get a style:
+
+1. **Search the official shape index** (`scripts/shapesearch.py`) — 10,446 real
+ draw.io palette shapes with their exact `style`, `w`, `h`. Use this for
+ branded/vendor icons and anything non-trivial. **Always prefer a searched
+ style over a hand-written `shape=mxgraph.*` guess** — guessed stencil names
+ silently render as a blank box if the name is wrong.
+2. **The cheatsheet below** — the common built-in shapes whose style strings are
+ short and stable enough to write by hand (rectangles, flowchart symbols,
+ UML primitives, containers, edges).
+
+## Searching shapes
+
+```bash
+python3 <this-skill-dir>/scripts/shapesearch.py "aws lambda" --limit 5
+python3 <this-skill-dir>/scripts/shapesearch.py "uml actor" --json
+```
+
+- Query is space-separated keywords; matching is tag-based with Soundex
+ fuzziness and `camelCase`/`digit` splitting (`"pid2valve"` → `pid valve`).
+- Prints each match as `Title (WxH)` followed by its full `style=` string. With
+ `--json`, emits `[{style,w,h,title}]` for programmatic use.
+- Copy the `style` verbatim into an `mxCell`, and use the reported `w`/`h` as the
+ `mxGeometry` width/height (vendor icons are drawn at a fixed aspect ratio).
+
+```xml
+<mxCell id="2" value="Lambda" style="<paste the searched style here>" vertex="1" parent="1">
+ <mxGeometry x="40" y="40" width="78" height="78" as="geometry"/>
+</mxCell>
+```
+
+Covered libraries: AWS (`aws3`/`aws4`), Azure, GCP, Cisco, Kubernetes, UML,
+BPMN, ER, electrical, P&ID, mockup/wireframe, flowchart, network, and the
+general/basic sets. The bundled index (`data/shape-index.json.gz`) is the
+upstream draw.io shape data — see `data/SHAPE-INDEX-NOTICE.md` for attribution.
+
+## Cheatsheet — hand-writable styles
+
+These are stable enough to write without searching. Combine with `whiteSpace=wrap;html=1;`.
+
+### Common shapes (`shape=` keyword)
+
+| Need | style |
+|---|---|
+| Rectangle / rounded box | `rounded=0;` / `rounded=1;` |
+| Circle / ellipse | `ellipse;` (`aspect=fixed;` for a true circle) |
+| Diamond (decision) | `rhombus;` |
+| Cylinder (database) | `shape=cylinder3;` |
+| Cloud | `cloud;` |
+| Cube (3D) | `shape=cube;` |
+| Sticky note | `shape=note;` |
+| Document (curled bottom) | `shape=document;` |
+| Folder | `shape=folder;` |
+| Card (cut corner) | `shape=card;` |
+| Process (double border) | `shape=process;` |
+| Step / chevron | `shape=step;` |
+| Parallelogram (I/O) | `shape=parallelogram;perimeter=parallelogramPerimeter;` |
+| Trapezoid | `shape=trapezoid;perimeter=trapezoidPerimeter;` |
+| Hexagon | `shape=hexagon;perimeter=hexagonPerimeter2;` |
+| Manual input | `shape=manualInput;` |
+| Data storage | `shape=dataStorage;` |
+| Off-page connector | `shape=offPageConnector;` |
+| Delay | `shape=delay;` |
+| OR / XOR gate | `shape=or;` / `shape=xor;` |
+| Block arrow | `shape=singleArrow;` / `shape=doubleArrow;` |
+| Callout (speech bubble) | `shape=callout;` |
+
+### UML primitives
+
+| Element | style |
+|---|---|
+| Actor (stick figure) | `shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;` |
+| Boundary | `shape=umlBoundary;` |
+| Control | `shape=umlControl;` |
+| Entity | `shape=umlEntity;` |
+| Lifeline | `shape=umlLifeline;perimeter=lifelinePerimeter;container=1;` |
+| Frame | `shape=umlFrame;` |
+| Provided interface (lollipop) | `shape=lollipop;direction=south;` |
+| Required interface | `shape=requires;direction=north;` |
+| Component | `shape=component;` |
+
+### Containers (parent-child; children use relative coords)
+
+| Type | style | When |
+|---|---|---|
+| Invisible group | `group;pointerEvents=0;` | No border, no own connections |
+| Titled swimlane | `swimlane;startSize=30;` | Visible title bar / has connections |
+| Any shape as container | append `container=1;pointerEvents=0;` | Box without own connections |
+
+### Edges
+
+| Need | add to style |
+|---|---|
+| Orthogonal routing | `edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;` |
+| Curved | `curved=1;` |
+| No arrowhead | `endArrow=none;` |
+| Open/thin arrow | `endArrow=open;` / `endArrow=classicThin;` |
+| Dashed | `dashed=1;` (pattern via `dashPattern=8 8;`) |
+| Flow animation | `flowAnimation=1;` |
+| Label background | `labelBackgroundColor=#ffffff;` |
+
+### Useful property knobs
+
+- `fontStyle` is a bitmask: `1`=bold, `2`=italic, `4`=underline (add to combine: `3`=bold+italic).
+- `direction=north|south|east|west` rotates a shape in 90° steps; `rotation=<deg>` for free rotation.
+- `gradientColor=#RRGGBB;` + `gradientDirection=north;` for a gradient fill.
+- `sketch=1;` gives a hand-drawn look (set globally via a style preset instead when possible).
+
+For richer per-shape detail, the upstream source is jgraph/drawio-mcp's
+`shared/style-reference.md` (Apache-2.0).
diff --git a/skills/drawio-skill/references/troubleshooting.md b/skills/drawio-skill/references/troubleshooting.md
index 599a710..7bceb49 100644
--- a/skills/drawio-skill/references/troubleshooting.md
+++ b/skills/drawio-skill/references/troubleshooting.md
@@ -25,3 +25,39 @@ Read this when something looks wrong in the output (rendering, export, layout, e
| Background color wrong in CLI export | Known CLI bug; add `--transparent` flag or set background via style |
| Vision returns 400 "Could not process image" on draft PNG | Re-export the preview without `-e` (issue #8). Root cause is a truncated IEND chunk in `-e` PNGs, not the `zTXt` chunk itself — but skipping `-e` for the preview is the simplest fix. |
| Final `-e` PNG won't open in image viewers / vision APIs | Run `python3 <this-skill-dir>/scripts/repair_png.py <path>`. draw.io CLI emits `-e` PNGs with an 8-byte truncation at IEND. SVG/PDF unaffected. |
+| WSL2: `drawio` / `draw.io` not found | The CLI lives on the Windows side. Use the Windows desktop exe via `/mnt/c`: `"/mnt/c/Program Files/draw.io/draw.io.exe"` (or per-user `"/mnt/c/Users/<you>/AppData/Local/Programs/draw.io/draw.io.exe"`). |
+| WSL2: opening an exported file fails with a `/mnt/c/...`-style path | `cmd.exe` can't resolve WSL paths — convert first: `cmd.exe /c start "" "$(wslpath -w diagram.drawio.png)"`. The empty `""` after `start` is the (required) window title. |
+| Browser URL opens to a blank/empty diagram (Windows/WSL2) | `cmd.exe`'s `start` treats `&` as a separator and drops everything after `#` — so the `#R…`/`#create=…` fragment (the whole diagram) is lost. Never pass the URL straight to `start`. Write a `.url` shortcut file and open *that* (see "WSL2 / Windows" below). |
+
+## WSL2 / Windows specifics
+
+**Locate the CLI.** Detect WSL2 with `grep -qi microsoft /proc/version`. On WSL2 the
+export CLI is the Windows desktop exe, reached through `/mnt/c` (quote the path —
+it contains a space):
+
+```bash
+"/mnt/c/Program Files/draw.io/draw.io.exe" --version
+# per-user install fallback:
+"/mnt/c/Users/$USER/AppData/Local/Programs/draw.io/draw.io.exe" --version
+```
+
+**Open a file.** Convert the WSL path to a Windows path first; `cmd.exe` cannot
+follow `/mnt/c/...`:
+
+```bash
+cmd.exe /c start "" "$(wslpath -w diagram.drawio.png)"
+```
+
+**Open a browser-fallback URL.** `cmd.exe /c start` strips the URL fragment
+(`&` ends the command, `#…` is dropped) — and the fragment carries the entire
+diagram. Write a `.url` shortcut and open it instead, so the URL survives intact:
+
+```bash
+URL=$(python3 <this-skill-dir>/scripts/encode_drawio_url.py --edit diagram.drawio)
+TMP=$(mktemp --suffix=.url)
+printf '[InternetShortcut]\r\nURL=%s\r\n' "$URL" > "$TMP"
+cmd.exe /c start "" "$(wslpath -w "$TMP")"
+```
+
+On native Windows the same `.url`-file trick applies (`start "" "%TEMP%\d.url"`).
+On macOS/Linux just `open "$URL"` / `xdg-open "$URL"` — no workaround needed.
diff --git a/skills/drawio-skill/scripts/encode_drawio_url.py b/skills/drawio-skill/scripts/encode_drawio_url.py
index c73e9a1..5523a1b 100755
--- a/skills/drawio-skill/scripts/encode_drawio_url.py
+++ b/skills/drawio-skill/scripts/encode_drawio_url.py
@@ -1,33 +1,58 @@
#!/usr/bin/env python3
-"""Encode a .drawio XML file into a diagrams.net viewer URL.
+"""Encode a .drawio XML file into a diagrams.net browser URL.
Used as the browser fallback when the draw.io desktop CLI is unavailable.
-Produces a client-side URL — the diagram XML is encoded in the URL
-fragment (after `#`), so nothing is uploaded to any server.
+The diagram XML is carried in the URL fragment (after `#`), so nothing is
+uploaded to any server.
-Usage: python3 encode_drawio_url.py <path/to/input.drawio>
+Two modes:
+ (default) read-only viewer -> https://viewer.diagrams.net/...#R<payload>
+ --edit editable editor -> https://app.diagrams.net/...#create=<payload>
+
+Usage: python3 encode_drawio_url.py [--edit] <path/to/input.drawio>
"""
import base64
+import json
import sys
import urllib.parse
import zlib
-def encode(xml: str) -> str:
- # Raw deflate (no zlib header) — diagrams.net uses mxGraph's raw inflate
+def _deflate_b64(xml: str) -> str:
+ # draw.io's loader runs JS decodeURIComponent on the inflated string, so the
+ # XML MUST be percent-encoded (encodeURIComponent) BEFORE deflate — otherwise
+ # a literal `%` or any non-ASCII (e.g. CJK) label makes the browser throw
+ # "URI malformed" and the diagram never opens. encodeURIComponent leaves
+ # only A-Za-z0-9 and -_.!~*'() unescaped, which `quote` reproduces here.
+ pre = urllib.parse.quote(xml, safe="!~*'()")
c = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
- compressed = c.compress(xml.encode("utf-8")) + c.flush()
- # Standard base64 (atob rejects url-safe -/_); strip newlines
- encoded = base64.b64encode(compressed).decode("utf-8").replace("\n", "")
+ compressed = c.compress(pre.encode("utf-8")) + c.flush()
+ # Standard base64 (atob rejects url-safe -/_); strip newlines.
+ return base64.b64encode(compressed).decode("utf-8").replace("\n", "")
+
+
+def encode(xml: str) -> str:
+ """Read-only viewer URL (mxGraph `#R` raw-inflate format)."""
return (
"https://viewer.diagrams.net/?tags=%7B%7D&lightbox=1&edit=_blank#R"
- + urllib.parse.quote(encoded, safe="")
+ + urllib.parse.quote(_deflate_b64(xml), safe="")
+ )
+
+
+def edit_url(xml: str) -> str:
+ """Editable editor URL — opens directly in the draw.io editor."""
+ payload = json.dumps({"type": "xml", "compressed": True, "data": _deflate_b64(xml)})
+ return (
+ "https://app.diagrams.net/?grid=0&pv=0&border=10&edit=_blank#create="
+ + urllib.parse.quote(payload, safe="")
)
if __name__ == "__main__":
- if len(sys.argv) != 2:
- print("usage: encode_drawio_url.py <path>", file=sys.stderr)
+ args = [a for a in sys.argv[1:] if a != "--edit"]
+ if len(args) != 1:
+ print("usage: encode_drawio_url.py [--edit] <path>", file=sys.stderr)
sys.exit(2)
- with open(sys.argv[1], "r", encoding="utf-8") as f:
- print(encode(f.read()))
+ with open(args[0], "r", encoding="utf-8") as f:
+ xml = f.read()
+ print(edit_url(xml) if "--edit" in sys.argv[1:] else encode(xml))
diff --git a/skills/drawio-skill/scripts/shapesearch.py b/skills/drawio-skill/scripts/shapesearch.py
new file mode 100644
index 0000000..95ecfb3
--- /dev/null
+++ b/skills/drawio-skill/scripts/shapesearch.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+"""Search 10k+ official draw.io shapes for their exact style strings.
+
+Resolves a keyword query (e.g. "aws lambda", "uml actor", "k8s pod") to the
+matching palette shapes so a diagram can use the real draw.io `style=` string
+instead of a hand-guessed one. Covers AWS / Azure / GCP / Cisco / Kubernetes /
+UML / BPMN / P&ID / electrical / flowchart / network / general shape sets.
+
+Port of the search in jgraph/drawio-mcp (Apache-2.0): tag map with exact +
+Soundex matching, strict AND first, scored OR fallback. The bundled index
+(data/shape-index.json.gz) is the upstream draw.io shape data — see
+data/SHAPE-INDEX-NOTICE.md.
+
+Usage:
+ python3 shapesearch.py "aws lambda" [--limit N] [--json]
+"""
+import argparse
+import gzip
+import json
+import os
+import re
+import sys
+
+INDEX = os.path.join(os.path.dirname(__file__), "..", "data", "shape-index.json.gz")
+_SOUNDEX_MAP = "01230120022455012603010202" # A..Z digit codes
+_TRAIL = re.compile(r"\.*\d*$") # strip trailing digits/dots before soundex
+
+
+def soundex(name):
+ if not name:
+ return ""
+ s = [name[0].upper()]
+ si = 1
+ for ch in name[1:]:
+ c = ord(ch.upper()) - 65
+ if 0 <= c <= 25 and _SOUNDEX_MAP[c] != "0":
+ code = _SOUNDEX_MAP[c]
+ if code != s[si - 1]:
+ s.append(code)
+ si += 1
+ if si > 3:
+ break
+ s += ["0"] * (4 - len(s))
+ return "".join(s[:4])
+
+
+def build_tag_map(shapes):
+ """tag (and its Soundex) -> set of shape indices."""
+ tag_map = {}
+ for i, shape in enumerate(shapes):
+ raw = shape.get("tags")
+ if not raw:
+ continue
+ seen = set()
+ for token in re.sub(r"[/,()]", " ", raw.lower()).split(" "):
+ if len(token) < 2 or token in seen:
+ continue
+ seen.add(token)
+ tag_map.setdefault(token, set()).add(i)
+ sx = soundex(_TRAIL.sub("", token))
+ if sx and sx != token and sx not in seen:
+ seen.add(sx)
+ tag_map.setdefault(sx, set()).add(i)
+ return tag_map
+
+
+def split_compound(token):
+ """'pid2misc' -> ['pid','misc']; 'discInst' -> ['disc','inst']."""
+ spaced = re.sub(r"([a-z])([A-Z])", r"\1 \2", token)
+ spaced = re.sub(r"([a-zA-Z])(\d)", r"\1 \2", spaced)
+ spaced = re.sub(r"(\d)([a-zA-Z])", r"\1 \2", spaced)
+ return [p for p in spaced.lower().split() if len(p) >= 2]
+
+
+def match_term(tag_map, term):
+ exact = set(tag_map.get(term, set()))
+ phonetic = set()
+ sx = soundex(_TRAIL.sub("", term))
+ if sx and sx != term:
+ phonetic = {i for i in tag_map.get(sx, set()) if i not in exact}
+ return exact, phonetic
+
+
+def search(shapes, tag_map, query, limit):
+ if not query:
+ return []
+ terms, seen = [], set()
+ for raw in query.lower().split():
+ subs = split_compound(raw) or ([raw] if len(raw) >= 2 else [])
+ for t in subs:
+ if t not in seen:
+ seen.add(t)
+ terms.append(t)
+ if not terms:
+ return []
+
+ term_matches = [match_term(tag_map, t) for t in terms]
+
+ # Strict AND across all terms first.
+ and_set = None
+ for exact, phonetic in term_matches:
+ combined = exact | phonetic
+ and_set = combined if and_set is None else (and_set & combined)
+ if not and_set:
+ break
+
+ # Score: +1.0 exact, +0.5 Soundex-only, per term. AND results if any, else OR.
+ scores = {}
+ pool = and_set if and_set else None
+ for exact, phonetic in term_matches:
+ for idx in exact:
+ if pool is None or idx in pool:
+ scores[idx] = scores.get(idx, 0) + 1.0
+ for idx in phonetic:
+ if (pool is None or idx in pool) and idx not in exact:
+ scores[idx] = scores.get(idx, 0) + 0.5
+
+ # Rank by score desc, then title (casefold ~ JS localeCompare), then index —
+ # the trailing index makes ties deterministic and matches upstream ordering.
+ ranked = sorted(scores, key=lambda i: (-scores[i], shapes[i].get("title", "").casefold(), i))
+ return [{"style": shapes[i]["style"], "w": shapes[i]["w"],
+ "h": shapes[i]["h"], "title": shapes[i]["title"]} for i in ranked[:limit]]
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Search official draw.io shapes for their style strings.")
+ ap.add_argument("query", help='keywords, e.g. "aws lambda" or "uml actor"')
+ ap.add_argument("--limit", type=int, default=10)
+ ap.add_argument("--json", action="store_true", help="emit JSON instead of a table")
+ args = ap.parse_args()
+
+ if not os.path.exists(INDEX):
+ sys.exit(f"error: shape index not found at {INDEX}")
+ with gzip.open(INDEX, "rt", encoding="utf-8") as f:
+ shapes = json.load(f)
+
+ results = search(shapes, build_tag_map(shapes), args.query, args.limit)
+ if not results:
+ sys.exit(f"no shapes matched {args.query!r}")
+ if args.json:
+ print(json.dumps(results, indent=2, ensure_ascii=False))
+ else:
+ for r in results:
+ print(f"{r['title']} ({r['w']}x{r['h']})\n {r['style']}")
+
+
+if __name__ == "__main__":
+ main()