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.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
Add relabel.py (language variants) and restyle.py (re-theme existing diagrams) (#86)
Agents365.ai5465e518d4a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b9e5d79..0f406b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,22 @@ All notable changes to **drawio-skill** are documented here. The format is basedon [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).+## [1.31.0] — 2026-07-13+### Added+- **`scripts/relabel.py`** — language variants / bulk text swaps of an existing+ `.drawio` with layout, styles, and ids untouched. `--extract` dumps every label+ (vertices, edges, UserObjects, page names) as an identity JSON map; translate the+ values, then `--map` applies them. Built for bilingual EN/CN twins of one diagram.+- **`scripts/restyle.py`** — re-theme an **existing** `.drawio` with a style preset+ ("make this dark", "apply my corporate style"). Every vertex fill/stroke is remapped+ to the preset palette by nearest hue (greys → neutral), so same-colored nodes stay+ grouped; applies font family and dark-theme extras (fontColor, edgeColor ++ `labelBackgroundColor=none`, page background, sketch, strokeWidth). Layout, shape+ keywords, and edge routing are never touched; default-white and `fillColor=none`+ cells keep readable text. Presets resolve like Step 0 (user dir → built-ins).+- Routing entries in SKILL.md, toolbox sections, a cross-reference in+ `style-presets.md`, and 6 new regression tests (79 total). Scripts: 28 → 30.+## [1.30.0] — 2026-07-13### Added- **Three new diagram-type presets** in `references/diagram-types.md`, filling gaps thediff --git a/README.md b/README.mdindex 6de9bde..b01efe2 100644--- a/README.md+++ b/README.md@@ -191,6 +191,13 @@ 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 mappython3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.drawio@@ -202,6 +209,8 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio|---|---|| **12 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), 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 |diff --git a/README_CN.md b/README_CN.mdindex 311595d..92159bd 100644--- a/README_CN.md+++ b/README_CN.md@@ -189,6 +189,13 @@ python3 scripts/svgflow.py architecture.drawio -o flow.svg# 反向:.drawio → Mermaid 流程图(GitHub 原生渲染的 diagrams-as-code)python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md+# 语言变体:提取标签 → 翻译值 → 应用(布局不动)+python3 scripts/relabel.py architecture.drawio --extract -o labels.json+python3 scripts/relabel.py architecture.drawio --map labels.json -o architecture_cn.drawio++# 给已有 .drawio 换主题(如暗色模式)+python3 scripts/restyle.py architecture.drawio --preset dark+# 按数据给已有 .drawio 上色 → 成本 / 延迟 / 流量热力图python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.drawio@@ -200,6 +207,8 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio|---|---|| **12 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose** 资源图(自动配官方云图标)、**SQL DDL → ER 图**、**OpenAPI / Swagger → API 图**(按 HTTP 方法着色的接口 + schema),以及从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施(画出真正已部署的样子) || **图对比 (diff)** | `drawiodiff.py` 把两张 `.drawio`(或两个实时快照)对比成一张彩色图 —— 新增=绿、删除=红、变更=橙 —— 一眼看出架构 / 基础设施**漂移** |+| **语言变体** | `relabel.py` 按 JSON 映射批量换标签,布局/样式/id 全不动 —— `--extract` 导出全部标签,翻译值后 `--map` 应用。一张图 → 中英双胞胎,双语文档必备 |+| **换主题** | `restyle.py` 给**已有** `.drawio` 应用风格预设(内置 `dark`/`corporate`/… 或自定义)—— 按色相重映射调色板,同色节点保持同组;布局与连线路由不动 || **指标热力图** | `heatmap.py` 按一份「节点→数值」的 CSV/JSON 给已有 `.drawio` 重新着色 —— 成本 / 延迟 / 流量 / 错误率沿渐变由低到高上色(可选按值缩放节点 + 自动图例),按 cell id 或标签匹配 || **架构时间轴** | `timelapse.py` 沿 git 历史逐个提交重跑提取器,拼成一个自包含 HTML 播放器 —— 看着模块和依赖边随时间长出来(▶ 播放 / ‹ › 单步) || **图 → Markdown** | `explain.py` 把一张 `.drawio` 反向描述成结构化文档 —— 按层级列出组件、关系、C4 多页分节 —— 方便把架构摘要塞进 README 或 PR |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 37769a9..241af03 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,6 +1,6 @@---name: drawio-skill-version: 1.30.0+version: 1.31.0description: 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: MIThomepage: 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 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/toolbox.md` | You're **not sure which bundled script fits** a request, or want to chain several — a map of all 30 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) |@@ -62,6 +62,8 @@ When the workflow references one of these, read it on demand — none of them ne| `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/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 |## Prerequisitesdiff --git a/skills/drawio-skill/references/style-presets.md b/skills/drawio-skill/references/style-presets.mdindex 164bd0e..52c1f80 100644--- a/skills/drawio-skill/references/style-presets.md+++ b/skills/drawio-skill/references/style-presets.md@@ -21,6 +21,8 @@ Only user presets can have `"default": true`. When the user says *"make `<built-## Applying a preset+> **Existing diagrams:** these rules apply at generation time. To re-theme a `.drawio` that already exists, run `python3 scripts/restyle.py diagram.drawio --preset <name>` — it applies the palette (hue-mapped), font, and extras without touching layout or edge routing.+When SKILL.md's Step 0 identified a preset, it fully replaces the built-in palette, shape keywords, edge defaults, and font for this diagram — do not mix values from the built-in color table.**Color lookup.** For each role a shape plays (service / database / queue / gateway / error / external / security), resolve `preset.roles[role]` to a slot name, then `preset.palette[<slot>]` to the `(fillColor, strokeColor)` pair. If `roles[role]` is unset or the resolved slot is `null`, follow this fallback ladder:diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex 003d282..47bf3fe 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 28 bundled scripts grouped by what you're trying to do. The+A map of the 30 bundled scripts grouped by what you're trying to do. Theper-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 requestmaps to, or you want to chain several.@@ -34,6 +34,8 @@ exports it:| a `.drawio` | a slide deck | `drawio2pptx` (→ PPTX) || a `.drawio` | an animated data-flow | `svgflow` (→ SVG) || a `.drawio` | diagrams-as-code | `drawio2mermaid` (→ Mermaid) |+| a `.drawio` | the same diagram in another language | `relabel` (extract → translate → apply) |+| a `.drawio` | it re-themed (dark / corporate preset) | `restyle` || a shape/icon need | the exact style string | `shapesearch` · `aiicons` (AI/LLM logos) |## 1. Author & place@@ -84,6 +86,8 @@ The skill runs both directions — these turn a `.drawio` back into something el## 7. Utilities & quality+- **`relabel.py`** — swap every label via a JSON map, layout untouched — `--extract` dumps an identity map of all labels (vertices, edges, UserObjects, page names), translate the values, `--map` applies them. Built for bilingual (EN/CN) variants of one diagram.+- **`restyle.py`** — apply a style preset (user or built-in, e.g. `dark`) to an existing `.drawio`: palette remap by hue, font, dark-theme extras, page background. Layout, shapes, and edge routing stay put.- **`validate.py`** — deterministic structural lint (dangling edges, dup/reserved ids, overlaps; `--score` for layout readability). Run before exporting.- **`repair_png.py`** — fix draw.io's truncated IEND chunk after every `-e` PNG export (issue #8).- **`encode_drawio_url.py`** — encode a `.drawio` into a diagrams.net browser URL when the CLI is unavailable (`--edit` for an editable editor URL).diff --git a/skills/drawio-skill/scripts/relabel.py b/skills/drawio-skill/scripts/relabel.pynew file mode 100644index 0000000..33a6bef--- /dev/null+++ b/skills/drawio-skill/scripts/relabel.py@@ -0,0 +1,102 @@+#!/usr/bin/env python3+"""Swap every label in a .drawio via a mapping — layout, styles, ids untouched.++The main use-case is language variants of one diagram (EN <-> CN docs figures):+extract the labels, translate the values, apply the map — the geometry never+moves, so both variants stay pixel-identical except for the text.++ python3 relabel.py diagram.drawio --extract -o labels.json # step 1+ # edit labels.json: keep keys, replace each value with the new text+ python3 relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio++Extract emits an identity JSON map {"label": "label", ...} of every non-empty+vertex/edge label, UserObject label, and page name, in document order. Apply+replaces each label that exactly matches a map key (raw string, HTML markup+included) and reports what matched. Unmapped labels stay unchanged; map keys+that matched nothing are listed on stderr so translations don't silently miss.++Usage: relabel.py <file.drawio> (--extract | --map <labels.json>) [-o <out>]+"""+import argparse+import json+import os+import sys+import xml.etree.ElementTree as ET+++def label_slots(tree):+ """Yield (element, attribute) for every label-bearing slot in the file."""+ for diagram in tree.getroot().iter("diagram"):+ if diagram.get("name"):+ yield diagram, "name"+ model = diagram.find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None: # compressed page — can't edit+ sys.stderr.write("warning: skipping compressed page "+ f"'{diagram.get('name', '?')}' (open+save in draw.io to decompress)\n")+ continue+ for child in root:+ if child.tag == "mxCell":+ if child.get("value"):+ yield child, "value"+ elif child.tag in ("UserObject", "object"):+ if child.get("label"):+ yield child, "label"+ inner = child.find("mxCell")+ if inner is not None and inner.get("value"):+ yield inner, "value"+++def main():+ p = argparse.ArgumentParser(description="Extract or swap .drawio labels via a JSON map.")+ p.add_argument("file", help="input .drawio")+ mode = p.add_mutually_exclusive_group(required=True)+ mode.add_argument("--extract", action="store_true",+ help="dump an identity label map as JSON")+ mode.add_argument("--map", metavar="JSON", dest="mapfile",+ help="JSON map {old label: new label} to apply")+ p.add_argument("-o", "--output", help="output path (default: stdout for --extract, "+ "<file>-relabel.drawio for --map)")+ args = p.parse_args()++ if not os.path.isfile(args.file):+ sys.exit(f"error: {args.file} not found")+ tree = ET.parse(args.file)++ if args.extract:+ seen = {}+ for el, attr in label_slots(tree):+ seen.setdefault(el.get(attr), el.get(attr))+ out = json.dumps(seen, ensure_ascii=False, indent=2)+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(out + "\n")+ sys.stderr.write(f"wrote {args.output} ({len(seen)} labels)\n")+ else:+ print(out)+ return++ with open(args.mapfile, encoding="utf-8") as f:+ mapping = json.load(f)+ if not isinstance(mapping, dict):+ sys.exit("error: map file must be a JSON object {old: new}")++ matched, used = 0, set()+ for el, attr in label_slots(tree):+ old = el.get(attr)+ if old in mapping:+ el.set(attr, str(mapping[old]))+ matched += 1+ used.add(old)++ out = args.output or os.path.splitext(args.file)[0] + "-relabel.drawio"+ tree.write(out, encoding="utf-8", xml_declaration=False)+ unused = [k for k in mapping if k not in used]+ if unused:+ sys.stderr.write("warning: %d map key(s) matched no label: %s\n"+ % (len(unused), ", ".join(repr(k)[:60] for k in unused[:10])))+ sys.stderr.write(f"wrote {out} ({matched} labels replaced)\n")+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/restyle.py b/skills/drawio-skill/scripts/restyle.pynew file mode 100644index 0000000..023ebb3--- /dev/null+++ b/skills/drawio-skill/scripts/restyle.py@@ -0,0 +1,161 @@+#!/usr/bin/env python3+"""Re-theme an EXISTING .drawio with a style preset — layout and shapes untouched.++Style presets (styles/schema.json) normally apply at generation time; this is+the post-processor for diagrams that already exist: "make this dark", "apply my+corporate style to last week's diagram".++ python3 restyle.py diagram.drawio --preset dark+ python3 restyle.py diagram.drawio --preset ~/.drawio-skill/styles/corp.json -o out.drawio++What it changes, per the preset application rules in references/style-presets.md:+- Every vertex fill/stroke is remapped to the preset palette. Each existing+ fillColor is matched to its nearest palette slot by hue (grey/low-saturation+ -> neutral), so same-colored nodes stay same-colored in the new theme.+- font.fontFamily on every vertex; existing fontSize values are kept (they+ encode hierarchy).+- extras: fontColor (vertices + text cells), edgeColor (edge stroke + label),+ sketch=1, globalStrokeWidth, page background on <mxGraphModel>.+Edge ROUTING styles and shape keywords are left alone — rewriting them would+break existing waypoints and geometry. fillColor=none is structural (lanes,+transparent containers) and is never replaced.++Usage: restyle.py <file.drawio> --preset <name|path.json> [-o <out.drawio>]+"""+import argparse+import colorsys+import json+import os+import re+import sys+import xml.etree.ElementTree as ET++SKILL_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+# Canonical hue (degrees) of each palette slot in the built-in conventions.+SLOT_HUES = {"primary": 210, "success": 120, "warning": 50, "accent": 30,+ "danger": 0, "secondary": 280}+SLOT_ORDER = ["primary", "success", "warning", "accent", "danger", "neutral", "secondary"]+++def find_preset(name):+ """Resolve a preset name/path to its JSON dict (user dir, then built-ins)."""+ candidates = [name] if name.endswith(".json") else [+ os.path.expanduser(f"~/.drawio-skill/styles/{name.lower()}.json"),+ os.path.join(SKILL_DIR, "styles", "built-in", f"{name.lower()}.json"),+ ]+ for path in candidates:+ if os.path.isfile(path):+ with open(path, encoding="utf-8") as f:+ return json.load(f)+ builtin = os.path.join(SKILL_DIR, "styles", "built-in")+ known = sorted(f[:-5] for f in os.listdir(builtin) if f.endswith(".json"))+ sys.exit(f"error: preset '{name}' not found (built-ins: {', '.join(known)})")+++def hue_slot(hexcolor, palette):+ """Nearest non-null palette slot for an existing fill color, by hue."""+ r, g, b = (int(hexcolor[i:i + 2], 16) / 255 for i in (1, 3, 5))+ h, l, s = colorsys.rgb_to_hls(r, g, b)+ if s < 0.15 or l > 0.97 or l < 0.03: # grey / near-white / near-black+ slot = "neutral"+ else:+ deg = h * 360+ slot = min(SLOT_HUES, key=lambda k: min(abs(deg - SLOT_HUES[k]),+ 360 - abs(deg - SLOT_HUES[k])))+ if palette.get(slot):+ return slot+ for k in SLOT_ORDER: # fallback ladder+ if palette.get(k):+ return k+ sys.exit("error: preset palette has no non-null slots")+++def get_key(style, key):+ m = re.search(rf"(?:^|;){key}=([^;]*)", style)+ return m.group(1) if m else None+++def set_keys(style, **kv):+ """Replace/insert style keys, dropping existing occurrences first."""+ for key in kv:+ style = re.sub(rf"(?:^|;){key}=[^;]*", "", style)+ style = style.strip("; ")+ tail = ";".join(f"{k}={v}" for k, v in kv.items() if v is not None)+ return (style + ";" if style else "") + tail + ";"+++def main():+ p = argparse.ArgumentParser(description="Apply a style preset to an existing .drawio.")+ p.add_argument("file", help="input .drawio")+ p.add_argument("--preset", required=True, help="preset name (user or built-in) or JSON path")+ p.add_argument("-o", "--output", help="output path (default: <file>-<preset>.drawio)")+ args = p.parse_args()++ if not os.path.isfile(args.file):+ sys.exit(f"error: {args.file} not found")+ preset = find_preset(args.preset)+ palette, extras, font = preset["palette"], preset.get("extras", {}), preset["font"]++ vertex_extra = {"fontFamily": font["fontFamily"]}+ if extras.get("fontColor"):+ vertex_extra["fontColor"] = extras["fontColor"]+ if extras.get("sketch"):+ vertex_extra["sketch"] = "1"+ if extras.get("globalStrokeWidth") not in (None, 1):+ vertex_extra["strokeWidth"] = "%g" % extras["globalStrokeWidth"]++ tree = ET.parse(args.file)+ slot_map, n_vert, n_edge = {}, 0, 0+ for diagram in tree.getroot().iter("diagram"):+ model = diagram.find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None:+ sys.stderr.write(f"warning: skipping compressed page '{diagram.get('name', '?')}'\n")+ continue+ if extras.get("background"):+ model.set("background", extras["background"])+ for child in root:+ cell = child if child.tag == "mxCell" else child.find("mxCell")+ if cell is None:+ continue+ style = cell.get("style") or ""+ if cell.get("edge") == "1":+ kv = {}+ if extras.get("edgeColor"):+ # labelBackgroundColor=none: the default white label box is+ # unreadable under a light edgeColor on dark backgrounds+ kv.update(strokeColor=extras["edgeColor"], fontColor=extras["edgeColor"],+ labelBackgroundColor="none")+ if extras.get("sketch"):+ kv["sketch"] = "1"+ if extras.get("globalStrokeWidth") not in (None, 1):+ kv["strokeWidth"] = "%g" % extras["globalStrokeWidth"]+ if kv:+ cell.set("style", set_keys(style, **kv))+ n_edge += 1+ continue+ if cell.get("vertex") != "1":+ continue+ kv = dict(vertex_extra)+ fill = get_key(style, "fillColor")+ if fill and re.fullmatch(r"#[0-9A-Fa-f]{6}", fill):+ slot = slot_map.setdefault(fill.lower(), hue_slot(fill.lower(), palette))+ pair = palette[slot]+ kv.update(fillColor=pair["fillColor"], strokeColor=pair["strokeColor"])+ elif fill is None:+ # No fillColor -> draw.io default white fill. Keep its default+ # dark text: extras.fontColor would be unreadable on white.+ kv.pop("fontColor", None)+ cell.set("style", set_keys(style, **kv))+ n_vert += 1++ out = args.output or "%s-%s.drawio" % (os.path.splitext(args.file)[0],+ preset.get("name", "restyled"))+ tree.write(out, encoding="utf-8", xml_declaration=False)+ remap = ", ".join(f"{c}->{s}" for c, s in sorted(slot_map.items()))+ sys.stderr.write(f"wrote {out} ({n_vert} vertices, {n_edge} edges restyled"+ + (f"; colors: {remap}" if remap else "") + ")\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex a6ec06b..790fe9d 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -1138,5 +1138,116 @@ class TestHeatmap(unittest.TestCase):self.assertIn("hm-title", cells) # legend injected+FIXTURE_RELABEL = (+ '<mxfile><diagram id="p" name="Flow"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="a" value="Start" style="ellipse;" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<UserObject id="b" label="Web Server" link="https://x">'+ '<mxCell style="rounded=1;" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell></UserObject>'+ '<mxCell id="e" value="go" style="endArrow=classic;" edge="1" parent="1" '+ 'source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>'+ '</root></mxGraphModel></diagram></mxfile>')+++class TestRelabel(unittest.TestCase):+ @staticmethod+ def _write(path, text):+ with open(path, "w", encoding="utf-8") as f:+ f.write(text)++ def test_extract_and_apply_roundtrip(self):+ with tempfile.TemporaryDirectory() as d:+ dp, lp, out = (os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio"))+ self._write(dp, FIXTURE_RELABEL)+ r = run("relabel.py", dp, "--extract", "-o", lp)+ self.assertEqual(r.returncode, 0, r.stderr)+ labels = json.load(open(lp, encoding="utf-8"))+ # page name + vertex value + UserObject label + edge label+ self.assertEqual(set(labels), {"Flow", "Start", "Web Server", "go"})+ labels.update({"Start": "\u5f00\u59cb", "Web Server": "Web \u670d\u52a1\u5668"})+ json.dump(labels, open(lp, "w", encoding="utf-8"), ensure_ascii=False)+ r = run("relabel.py", dp, "--map", lp, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("4 labels replaced", r.stderr)+ text = open(out, encoding="utf-8").read()+ self.assertIn("\u5f00\u59cb", text)+ self.assertIn("Web \u670d\u52a1\u5668", text)+ self.assertNotIn('value="Start"', text)+ # geometry untouched+ self.assertIn('x="200"', text)++ def test_unmatched_map_key_warns(self):+ with tempfile.TemporaryDirectory() as d:+ dp, lp, out = (os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio"))+ self._write(dp, FIXTURE_RELABEL)+ self._write(lp, '{"Nope": "X"}')+ r = run("relabel.py", dp, "--map", lp, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("matched no label", r.stderr)+++class TestRestyle(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("restyle")++ def test_hue_slot_mapping(self):+ palette = {k: {"fillColor": "#000000", "strokeColor": "#000000"}+ for k in ("primary", "success", "warning", "accent",+ "danger", "neutral", "secondary")}+ self.assertEqual(self.m.hue_slot("#dae8fc", palette), "primary") # blue+ self.assertEqual(self.m.hue_slot("#d5e8d4", palette), "success") # green+ self.assertEqual(self.m.hue_slot("#f8cecc", palette), "danger") # red+ self.assertEqual(self.m.hue_slot("#f5f5f5", palette), "neutral") # grey++ def test_set_keys_replaces_and_appends(self):+ s = self.m.set_keys("rounded=1;fillColor=#111111;", fillColor="#222222",+ fontFamily="Helvetica")+ self.assertEqual(s.count("fillColor="), 1)+ self.assertIn("fillColor=#222222", s)+ self.assertIn("fontFamily=Helvetica", s)+ self.assertIn("rounded=1", s)++ def test_dark_preset_end_to_end(self):+ drawio = (+ '<mxfile><diagram id="p" name="P"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="svc" value="Svc" style="rounded=1;fillColor=#dae8fc;'+ 'strokeColor=#6c8ebf;" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="plain" value="Plain" style="rounded=1;" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="e" value="go" style="endArrow=classic;" edge="1" parent="1" '+ 'source="svc" target="plain"><mxGeometry relative="1" as="geometry"/></mxCell>'+ '</root></mxGraphModel></diagram></mxfile>')+ with tempfile.TemporaryDirectory() as d:+ dp, out = os.path.join(d, "a.drawio"), os.path.join(d, "out.drawio")+ with open(dp, "w", encoding="utf-8") as f:+ f.write(drawio)+ r = run("restyle.py", dp, "--preset", "dark", "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ import xml.etree.ElementTree as ET+ tree = ET.parse(out)+ cells = {c.get("id"): c.get("style") for c in tree.getroot().iter("mxCell")}+ self.assertIn("fillColor=#004870", cells["svc"]) # blue -> dark primary+ self.assertIn("fontColor=#f0f0f0", cells["svc"])+ self.assertNotIn("fontColor=", cells["plain"]) # default white fill kept dark text+ self.assertIn("strokeColor=#bbbbbb", cells["e"]) # edgeColor+ self.assertIn("labelBackgroundColor=none", cells["e"])+ model = tree.getroot().find(".//mxGraphModel")+ self.assertEqual(model.get("background"), "#1e1e1e")++ def test_unknown_preset_lists_builtins(self):+ with tempfile.TemporaryDirectory() as d:+ dp = os.path.join(d, "a.drawio")+ with open(dp, "w", encoding="utf-8") as f:+ f.write(FIXTURE_RELABEL)+ r = run("restyle.py", dp, "--preset", "nope")+ self.assertNotEqual(r.returncode, 0)+ self.assertIn("dark", r.stderr + r.stdout)++if __name__ == "__main__":unittest.main()