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: interactive HTML viewer for .drawio (v1.28.0) (#77)

Agents365.ai89ff88cb27cd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57bb897..7bf76b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,22 @@ All notable changes to **drawio-skill** are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/), and the project follows
semantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).
+## [1.28.0] — 2026-07-04
+### Added
+- **Interactive HTML viewer** (`scripts/drawiohtml.py`) — publish a `.drawio` as
+ ONE self-contained `.html`: every page exported to SVG via the draw.io CLI and
+ inlined with page tabs, drag-pan, wheel-zoom (cursor-anchored), node search
+ (matches glow, Enter cycles + centres) and **working links** — external links
+ open normally, internal `data:page/id,…` links (e.g. a C4 model's drill-down)
+ switch tabs inside the viewer. No server, no external requests; share the file
+ with anyone, no draw.io needed.
+ - Internal page links survive SVG export by being rewritten to `#page-<id>`
+ fragments first (draw.io drops raw `data:page/id` links); search targets the
+ `<g data-cell-id>` groups draw.io wraps every cell in.
+ - Verified in a real browser (Playwright): C4 Context→Container→Component
+ drill-down chain, search hit/centre, wheel zoom, tab switching. SKILL.md
+ router + toolbox.md + READMEs updated; script count 27 → 28. Suite now 73.
+
## [1.27.0] — 2026-07-04
### Added
- **OpenAPI / Swagger → API diagram** (`scripts/openapiimports.py`) — turn an
diff --git a/README.md b/README.md
index 7edc0bb..66d7cdd 100644
--- a/README.md
+++ b/README.md
@@ -183,6 +183,9 @@ 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
@@ -203,6 +206,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **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 |
diff --git a/README_CN.md b/README_CN.md
index 02beaba..50fe70d 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -181,6 +181,9 @@ python3 scripts/explain.py architecture.drawio -o architecture.md
# 图 → PowerPoint 幻灯片(每页一张;C4 模型 → 演示稿)
python3 scripts/drawio2pptx.py c4.drawio -o c4.pptx # 需要: pip install python-pptx
+# 交互式 HTML 查看器 —— 平移/缩放/搜索/页签 + 可用的下钻链接,单文件
+python3 scripts/drawiohtml.py c4.drawio -o c4.html
+
# 数据流动画 SVG —— 让边「流动」起来(marching ants);GitHub 可直接渲染
python3 scripts/svgflow.py architecture.drawio -o flow.svg
@@ -201,6 +204,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **指标热力图** | `heatmap.py` 按一份「节点→数值」的 CSV/JSON 给已有 `.drawio` 重新着色 —— 成本 / 延迟 / 流量 / 错误率沿渐变由低到高上色(可选按值缩放节点 + 自动图例),按 cell id 或标签匹配 |
| **架构时间轴** | `timelapse.py` 沿 git 历史逐个提交重跑提取器,拼成一个自包含 HTML 播放器 —— 看着模块和依赖边随时间长出来(▶ 播放 / ‹ › 单步) |
| **图 → Markdown** | `explain.py` 把一张 `.drawio` 反向描述成结构化文档 —— 按层级列出组件、关系、C4 多页分节 —— 方便把架构摘要塞进 README 或 PR |
+| **交互式查看器** | `drawiohtml.py` 把 `.drawio` 发布成一个自包含 HTML —— 页签、拖拽平移、滚轮缩放、节点搜索,C4 模型的下钻链接照常可点。发一个文件即可分享;不需要 draw.io,也不需要服务器 |
| **图 → PowerPoint** | `drawio2pptx.py` 把多页图变成 16:9 幻灯片(每页一张、页名当标题)—— C4 模型一键变成可演示的 slideshow |
| **数据流动画** | `svgflow.py` 让图里的边「流动」起来(沿箭头方向的 marching-ants 动画)—— 自包含循环 SVG,可在 GitHub、文档或幻灯片背景里直接播放 |
| **图 → Mermaid** | `drawio2mermaid.py` 把 `.drawio` 转成 Mermaid `flowchart`(容器变 subgraph、保留边标签)—— 粘进 Markdown 就是 GitHub 原生渲染的 diagrams-as-code |
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index c162ad5..aef0826 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-version: 1.27.0
+version: 1.28.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, 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
@@ -34,7 +34,7 @@ When the workflow references one of these, read it on demand — none of them ne
| 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 27 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/toolbox.md` | You're **not sure which bundled script fits** a request, or want to chain several — a map of all 28 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) |
@@ -54,6 +54,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `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 → `subgraph`s, 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 |
diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.md
index 9726b83..003d282 100644
--- a/skills/drawio-skill/references/toolbox.md
+++ b/skills/drawio-skill/references/toolbox.md
@@ -1,6 +1,6 @@
# Toolbox — every bundled script, by use-case
-A map of the 27 bundled scripts grouped by what you're trying to do. The
+A map of the 28 bundled scripts grouped by what you're trying to do. The
per-task routing table in `SKILL.md` says *when* to reach for each; this says
*how they fit together*. Read it when you're not sure which script a request
maps to, or you want to chain several.
@@ -29,6 +29,7 @@ exports it:
| a system at 3 zoom levels | a C4 model with drill-down | `c4` |
| two diagrams / two snapshots | what changed (drift) | `drawiodiff` |
| a repo's git history | how its architecture grew | `timelapse` |
+| a `.drawio` | a shareable interactive viewer | `drawiohtml` (→ HTML: pan/zoom/search/tabs) |
| a `.drawio` | a written description | `explain` (→ Markdown) |
| a `.drawio` | a slide deck | `drawio2pptx` (→ PPTX) |
| a `.drawio` | an animated data-flow | `svgflow` (→ SVG) |
@@ -75,6 +76,7 @@ The **actual** counterpart to §3 — see `references/live-infra.md`.
The skill runs both directions — these turn a `.drawio` back into something else:
+- **`drawiohtml.py`** — → a self-contained **interactive HTML viewer**: every page inlined as SVG with tabs, drag-pan, wheel-zoom, node search, and working drill-down links (C4 `data:page/id` links switch tabs). Share one file; no draw.io, no server.
- **`explain.py`** — → structured **Markdown** (components by tier, relations, per-page C4).
- **`drawio2pptx.py`** — → a 16:9 **PowerPoint** deck, one page per slide (needs `python-pptx`).
- **`svgflow.py`** — → an **animated SVG** (edges flow as marching ants); renders on GitHub.
diff --git a/skills/drawio-skill/scripts/drawiohtml.py b/skills/drawio-skill/scripts/drawiohtml.py
new file mode 100644
index 0000000..a67b937
--- /dev/null
+++ b/skills/drawio-skill/scripts/drawiohtml.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""Publish a .drawio as a single interactive HTML viewer.
+
+Exports every page to SVG via the draw.io CLI and inlines them into ONE
+self-contained .html with pan (drag), zoom (wheel / buttons), page tabs,
+node search, and working links — external links open normally and internal
+page links ("data:page/id,…", e.g. a C4 model's drill-down) switch tabs
+inside the viewer. Share the file with anyone: no draw.io, no server,
+no external requests.
+
+ python3 drawiohtml.py architecture.drawio -o architecture.html
+ python3 drawiohtml.py c4.drawio # -> c4.html, drill-down works
+
+Search matches node text (draw.io wraps every cell in <g data-cell-id>);
+matches glow, Enter cycles through them and centres each. Internal page
+links survive export by being rewritten to "#page-<id>" fragments first
+(draw.io drops raw data:page/id links from SVG).
+
+Usage: python3 drawiohtml.py <file.drawio> [-o out.html]
+"""
+import argparse
+import html
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import xml.etree.ElementTree as ET
+
+PAGE_LINK = "data:page/id,"
+
+
+def pages_of(path):
+ """[(id, name)] of the <diagram> pages, in order."""
+ try:
+ root = ET.parse(path).getroot()
+ except (ET.ParseError, OSError) as exc:
+ sys.exit(f"error: cannot parse {path}: {exc}")
+ return [(d.get("id") or f"p{i}", d.get("name") or f"Page {i + 1}")
+ for i, d in enumerate(root.findall("diagram"))]
+
+
+def rewrite_page_links(tree):
+ """data:page/id,X links -> #page-X (fragments survive SVG export). Returns count."""
+ n = 0
+ for el in tree.getroot().iter():
+ link = el.get("link")
+ if link and link.startswith(PAGE_LINK):
+ el.set("link", "#page-" + link[len(PAGE_LINK):])
+ n += 1
+ return n
+
+
+def export_svg(drawio_file, index, out_svg):
+ """Export one page (1-based index) to SVG via the draw.io CLI."""
+ r = subprocess.run(["drawio", "-x", "-f", "svg", "--page-index", str(index),
+ "-o", out_svg, drawio_file], capture_output=True)
+ return r.returncode == 0 and os.path.exists(out_svg)
+
+
+def strip_prolog(svg):
+ """Drop any XML declaration / doctype so the SVG can be inlined in HTML."""
+ return re.sub(r"^\s*(<\?xml[^>]*\?>\s*|<!DOCTYPE[^>]*>\s*)*", "", svg)
+
+
+def build_html(title, page_meta, svgs):
+ """One self-contained viewer page. page_meta = [(id, name)] aligned with svgs."""
+ sections = "\n".join(
+ f'<div class="page" data-pgid="{html.escape(pid, quote=True)}">{svg}</div>'
+ for (pid, _), svg in zip(page_meta, svgs))
+ tabs = json.dumps([{"id": pid, "name": name} for pid, name in page_meta]) \
+ .replace("</", "<\\/")
+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>{html.escape(title)}</title><style>
+:root{{color-scheme:light dark}}
+*{{box-sizing:border-box}}
+body{{margin:0;font:14px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;
+background:#f6f7f9;color:#1a1a1a;height:100vh;display:flex;flex-direction:column}}
+@media(prefers-color-scheme:dark){{body{{background:#15171a;color:#e8e8e8}}}}
+header{{padding:10px 16px 8px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}}
+h1{{margin:0;font-size:15px;font-weight:600}}
+nav{{display:flex;gap:6px;flex-wrap:wrap}}
+button,input{{font:inherit;color:inherit}}
+nav button,.ctl button{{padding:4px 10px;border:1px solid #0002;border-radius:8px;
+background:#fff;cursor:pointer}}
+@media(prefers-color-scheme:dark){{nav button,.ctl button{{background:#262b31;border-color:#fff2}}}}
+nav button.on{{border-color:#0d99ff;color:#0d99ff;font-weight:600}}
+.ctl{{display:flex;gap:8px;align-items:center;margin-left:auto}}
+.ctl input{{padding:4px 10px;border:1px solid #0002;border-radius:8px;background:#fff;width:180px}}
+@media(prefers-color-scheme:dark){{.ctl input{{background:#262b31;border-color:#fff2}}}}
+#hits{{font-size:12px;color:#889;min-width:56px}}
+#stage{{flex:1;overflow:hidden;position:relative;background:#fff;
+border-top:1px solid #0001;cursor:grab;touch-action:none}}
+@media(prefers-color-scheme:dark){{#stage{{background:#1e2226;border-color:#fff2}}}}
+#stage.drag{{cursor:grabbing}}
+.page{{position:absolute;transform-origin:0 0;display:none}}
+.page.on{{display:block}}
+.page svg{{display:block}}
+.hit{{filter:drop-shadow(0 0 3px #ff9800) drop-shadow(0 0 6px #ff980088)}}
+.hit.cursel{{filter:drop-shadow(0 0 4px #f44336) drop-shadow(0 0 9px #f44336aa)}}
+</style></head><body>
+<header><h1>{html.escape(title)}</h1><nav id="tabs"></nav>
+<div class="ctl">
+ <input id="q" type="search" placeholder="Search nodes… Enter = next">
+ <span id="hits"></span>
+ <button id="zout" title="zoom out">−</button><button id="zin" title="zoom in">+</button>
+ <button id="fit">Fit</button>
+</div></header>
+<main id="stage">
+{sections}
+</main>
+<script>
+const META={tabs};
+const stage=document.getElementById('stage');
+const pages=[...document.querySelectorAll('.page')];
+const view=pages.map(()=>({{x:0,y:0,s:1}}));
+let cur=0,hits=[],hi=-1;
+const tabs=document.getElementById('tabs');
+if(META.length>1)META.forEach((m,i)=>{{
+ const b=document.createElement('button');b.textContent=m.name;
+ b.onclick=()=>show(i);tabs.appendChild(b);}});
+function apply(){{const v=view[cur];
+ pages[cur].style.transform=`translate(${{v.x}}px,${{v.y}}px) scale(${{v.s}})`;}}
+function svgSize(i){{const s=pages[i].querySelector('svg');
+ return[parseFloat(s.getAttribute('width'))||800,
+ parseFloat(s.getAttribute('height'))||600];}}
+function fit(){{const[w,h]=svgSize(cur),r=stage.getBoundingClientRect(),
+ s=Math.min((r.width-40)/w,(r.height-40)/h,4);
+ view[cur]={{s,x:(r.width-w*s)/2,y:(r.height-h*s)/2}};apply();}}
+function show(i){{cur=i;
+ pages.forEach((p,j)=>p.classList.toggle('on',j===i));
+ [...tabs.children].forEach((b,j)=>b.classList.toggle('on',j===i));
+ if(!pages[i].dataset.seen){{pages[i].dataset.seen=1;fit();}}else apply();
+ search();}}
+stage.addEventListener('wheel',e=>{{e.preventDefault();const v=view[cur],
+ r=stage.getBoundingClientRect(),mx=e.clientX-r.left,my=e.clientY-r.top,
+ k=Math.exp(-e.deltaY*0.0015),s=Math.min(Math.max(v.s*k,0.05),8);
+ v.x=mx-(mx-v.x)*s/v.s;v.y=my-(my-v.y)*s/v.s;v.s=s;apply();}},{{passive:false}});
+let drag=null;
+stage.addEventListener('pointerdown',e=>{{if(e.target.closest('a'))return;
+ drag={{x:e.clientX,y:e.clientY}};stage.classList.add('drag');
+ stage.setPointerCapture(e.pointerId);}});
+stage.addEventListener('pointermove',e=>{{if(!drag)return;const v=view[cur];
+ v.x+=e.clientX-drag.x;v.y+=e.clientY-drag.y;
+ drag={{x:e.clientX,y:e.clientY}};apply();}});
+stage.addEventListener('pointerup',()=>{{drag=null;stage.classList.remove('drag');}});
+function zoom(k){{const v=view[cur],r=stage.getBoundingClientRect(),
+ mx=r.width/2,my=r.height/2,s=Math.min(Math.max(v.s*k,0.05),8);
+ v.x=mx-(mx-v.x)*s/v.s;v.y=my-(my-v.y)*s/v.s;v.s=s;apply();}}
+document.getElementById('zin').onclick=()=>zoom(1.25);
+document.getElementById('zout').onclick=()=>zoom(0.8);
+document.getElementById('fit').onclick=fit;
+// Internal page links: any anchor whose target ends in #page-<id> switches tabs.
+document.addEventListener('click',e=>{{const a=e.target.closest('a');
+ if(!a)return;const href=a.getAttribute('xlink:href')||a.getAttribute('href')||'';
+ const m=href.match(/#page-(.+)$/);if(!m)return;e.preventDefault();
+ const i=META.findIndex(p=>p.id===decodeURIComponent(m[1]));if(i>=0)show(i);}},true);
+const q=document.getElementById('q'),hitEl=document.getElementById('hits');
+function search(){{
+ hits.forEach(g=>g.classList.remove('hit','cursel'));hits=[];hi=-1;
+ const t=q.value.trim().toLowerCase();
+ if(t){{
+ const all=[...pages[cur].querySelectorAll('g[data-cell-id]')]
+ .filter(g=>!['0','1'].includes(g.dataset.cellId))
+ .filter(g=>g.textContent.toLowerCase().includes(t));
+ hits=all.filter(g=>!all.some(o=>o!==g&&g.contains(o))); // innermost only
+ hits.forEach(g=>g.classList.add('hit'));
+ }}
+ hitEl.textContent=t?hits.length+' hit'+(hits.length===1?'':'s'):'';}}
+function centre(g){{const v=view[cur],r=stage.getBoundingClientRect(),
+ b=g.getBoundingClientRect();
+ v.x+=r.left+r.width/2-(b.left+b.width/2);
+ v.y+=r.top+r.height/2-(b.top+b.height/2);apply();}}
+q.addEventListener('input',search);
+q.addEventListener('keydown',e=>{{
+ if(e.key==='Escape'){{q.value='';search();q.blur();}}
+ if(e.key!=='Enter'||!hits.length)return;
+ if(hi>=0)hits[hi].classList.remove('cursel');
+ hi=(hi+1)%hits.length;hits[hi].classList.add('cursel');centre(hits[hi]);}});
+show(0);
+</script></body></html>
+"""
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Export a .drawio to a self-contained interactive HTML viewer.")
+ ap.add_argument("file")
+ ap.add_argument("-o", "--output", help="output .html (default: alongside input)")
+ args = ap.parse_args()
+
+ if not os.path.isfile(args.file):
+ sys.exit(f"error: {args.file} not found")
+ meta = pages_of(args.file)
+ if not meta:
+ sys.exit(f"error: no <diagram> pages in {args.file}")
+
+ tree = ET.parse(args.file)
+ relinked = rewrite_page_links(tree)
+
+ svgs, kept = [], []
+ with tempfile.TemporaryDirectory() as tmp:
+ src = args.file
+ if relinked: # export the rewritten copy instead
+ src = os.path.join(tmp, "relinked.drawio")
+ tree.write(src, encoding="utf-8", xml_declaration=False)
+ for i, (pid, name) in enumerate(meta, 1): # draw.io --page-index is 1-based
+ out = os.path.join(tmp, f"p{i}.svg")
+ if not export_svg(src, i, out):
+ sys.stderr.write(f"warning: page {i} ({name}) export failed — skipped\n")
+ continue
+ with open(out, encoding="utf-8") as f:
+ svgs.append(strip_prolog(f.read()))
+ kept.append((pid, name))
+
+ if not svgs:
+ sys.exit("error: no pages exported (is the draw.io CLI installed?)")
+ title = os.path.splitext(os.path.basename(args.file))[0]
+ out = args.output or os.path.splitext(args.file)[0] + ".html"
+ with open(out, "w", encoding="utf-8") as f:
+ f.write(build_html(title, kept, svgs))
+ sys.stderr.write(f"wrote {out} ({len(svgs)} page{'s' if len(svgs) != 1 else ''}"
+ + (f", {relinked} drill-down link{'s' if relinked != 1 else ''}" if relinked else "")
+ + ")\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 4bb0199..a6ec06b 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -1018,6 +1018,68 @@ class TestImportersCli(unittest.TestCase):
self.assertEqual(graph["edges"], [])
+class TestDrawioHtml(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.m = load("drawiohtml")
+
+ TWO_PAGE = (
+ '<mxfile>'
+ '<diagram id="pg1" name="Context"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<UserObject label="System" link="data:page/id,pg2" id="sys">'
+ '<mxCell style="rounded=1;" vertex="1" parent="1">'
+ '<mxGeometry x="40" y="40" width="120" height="60" as="geometry"/></mxCell>'
+ '</UserObject></root></mxGraphModel></diagram>'
+ '<diagram id="pg2" name="Container"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="app" value="App" style="rounded=1;" vertex="1" parent="1">'
+ '<mxGeometry x="40" y="40" width="120" height="60" as="geometry"/></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+
+ def test_rewrite_page_links(self):
+ import xml.etree.ElementTree as ET
+ import io
+ tree = ET.parse(io.StringIO(self.TWO_PAGE))
+ self.assertEqual(self.m.rewrite_page_links(tree), 1)
+ links = [el.get("link") for el in tree.getroot().iter() if el.get("link")]
+ self.assertEqual(links, ["#page-pg2"])
+
+ def test_strip_prolog(self):
+ svg = '<?xml version="1.0"?>\n<!DOCTYPE svg>\n<svg><g/></svg>'
+ self.assertEqual(self.m.strip_prolog(svg), "<svg><g/></svg>")
+
+ def test_build_html_self_contained(self):
+ html = self.m.build_html("t", [("pg1", "Context"), ("pg2", "Container")],
+ ['<svg width="10" height="10"/>',
+ '<svg width="10" height="10"/>'])
+ self.assertEqual(html.count('class="page"'), 2)
+ self.assertIn('data-pgid="pg1"', html)
+ self.assertIn('"name": "Container"', html)
+ self.assertIn("#page-", html) # link interception
+ for banned in ("<script src=", "<link ", "@import", "https://cdn"):
+ self.assertNotIn(banned, html) # no external requests
+
+ def test_viewer_end_to_end(self):
+ import shutil
+ if not shutil.which("drawio"):
+ self.skipTest("draw.io CLI not installed")
+ with tempfile.TemporaryDirectory() as d:
+ src = os.path.join(d, "two.drawio")
+ with open(src, "w", encoding="utf-8") as f:
+ f.write(self.TWO_PAGE)
+ out = os.path.join(d, "two.html")
+ r = run("drawiohtml.py", src, "-o", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("2 pages", r.stderr)
+ self.assertIn("1 drill-down link", r.stderr)
+ with open(out, encoding="utf-8") as f:
+ html = f.read()
+ self.assertEqual(html.count("<svg"), 2) # both pages inlined
+ self.assertIn("#page-pg2", html) # drill-down survived
+ self.assertIn("data-cell-id", html) # searchable cells
+
+
class TestHeatmap(unittest.TestCase):
@classmethod
def setUpClass(cls):