Skip to content
Back to search

unicode-diagrams

SkillWorks with Claude CodeGitHub

Draw architecture, system design and flow diagrams as Unicode box-drawing art (┌─┐ │ └─┘ ░ shadows), not plain ASCII. Use when asked for a text diagram, ASCII or box-drawing diagram, or a diagram in a design doc or README.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/rohalrafael--unicode-diagrams/badge.svg)](/listings/rohalrafael--unicode-diagrams)

HTML

<a href="/listings/rohalrafael--unicode-diagrams"><img src="/api/listings/rohalrafael--unicode-diagrams/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

git clone https://github.com/rohalrafael/unicode-diagrams ~/.claude/skills/unicode-diagrams

Python 3 is the only requirement. Then ask Claude for a text diagram, or type `/unicode-diagrams`.

The style rules, the API and the engine source are in [SKILL.md](SKILL.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 767 lines
  1. ---
  2. name: unicode-diagrams
  3. description: Draw architecture, system design and flow diagrams as Unicode box-drawing art (┌─┐ │ └─┘ ░ shadows), not plain ASCII. Use when asked for a text diagram, ASCII or box-drawing diagram, or a diagram in a design doc or README.
  4. ---
  5. # Unicode Diagrams
  6. Draw diagrams as plain text with Unicode box-drawing characters, in one house style.
  7. Always build the diagram with the `textdiagram.py` grid engine below. Do not draw by hand:
  8. hand-drawn diagrams drift out of alignment.
  9. ## Style rules
  10. - Plain text in a fenced code block. No Mermaid, SVG, images or emoji.
  11. - Width: 80 columns by default. To change it, pass `max_width` to the constructor,
  12. for example `D(max_width=100)`. The engine raises an error on a longer line.
  13. - **All text is UPPER CASE.** The engine does this for you: write normal text in the script.
  14. Exception: units whose case changes the meaning stay as written, when you write them
  15. exactly like this: `Hz kHz MHz GHz`, `kB MB GB TB KiB MiB GiB TiB`,
  16. `kb Mb Gb Tb kbps Mbps Gbps`, `ms µs ns`. Other words, such as NGINX or K8S, are upper case.
  17. - **COMPONENT box** (a part of the system: service, client, database, queue, worker):
  18. light lines `┌─┐ │ └─┘` plus a light `░` shadow, one column right and one row down.
  19. To group parts, split one box into sections: light dividers `├───┤`, one frame, one shadow.
  20. - **TITLE box** (the main title of the doc, one per diagram): double lines `╔═╗ ║ ╚═╝`, **no shadow**.
  21. One item per line (name, doc type, version), each line centered in the box. Make it with
  22. `d.header(...)`: the engine centers the box over the whole diagram. Optional: a meta box
  23. on the left (company, RFC, date) and a stamp box on the right (status). All three get the
  24. same height; padding lines of the title box hold a centered dot `·`.
  25. No arrow can start or end at a header box.
  26. - **FRAME box** (section header, note, callout): light lines, **no shadow**.
  27. Note / callout: put the name in the top border, like `┌─ NOTE ───┐`.
  28. Do not add a legend: the style is the same in every diagram.
  29. - **Free text** (`d.annotate`): a short remark with no box, beside the diagram. Use it
  30. rarely. A line must not cross it.
  31. - **Horizontal arrow**: label inside the line, one space each side: `── HTTPS ──▶`.
  32. Both ends touch a box: the line starts on the shadow column of the sending box and the
  33. head touches the receiving box.
  34. - **Vertical arrow**: line starts from `┬` on the bottom border, ends with `▼`. The label goes
  35. to the right of the line, one row below the shadow. Or cut the label into the line
  36. (`inline=True`): line, blank row, label lines centered on the line, blank row, line.
  37. - **Bent arrow** (`d.route`): any number of bends, in any direction (`▲ ▼ ◀ ▶`). The label goes
  38. inside an across segment, or beside (or, with `inline=True`, cut into) an up/down segment.
  39. Lines that cross or join make a junction (`┼ ├ ┤ ┬ ┴`). A line never passes through a box.
  40. - **Bus** (`d.fan_out`): one line from a box that splits into one arrow per target.
  41. The label goes on the shared line.
  42. - **Arrow heads**: filled `▶ ◀ ▲ ▼` for the main flow. Hollow `▷ ◁ △ ▽` for a second kind of
  43. relation (asynchronous, optional, event). Use hollow only if the diagram needs two kinds,
  44. and name the meaning in a label or a note, not in a legend.
  45. - Label every arrow with what flows (protocol, event, data).
  46. - If it is not clear which role a box has: COMPONENT for system parts, TITLE for the main title, FRAME for everything else.
  47. ## Workflow
  48. 1. List the components, frames and arrows before you draw.
  49. 2. Write the engine to `/tmp/textdiagram/textdiagram.py` (full source at the end of this file,
  50. copy it exactly). Write it again each session, so an old version is never used.
  51. 3. Write a short Python script that imports the engine and builds the diagram. Use the
  52. layout helpers to place boxes (do not guess coordinates):
  53. - `Diagram.x_right_of(a, label)` — x for the next box to the right, with room for the arrow label.
  54. - `Diagram.x_left_of(a, lines, label)` — x for a new box to the left of `a`, with room for the label.
  55. - `Diagram.y_below(a)` — y for a box below `a`. With an inline label: `Diagram.y_below(a, lines=N)`.
  56. - `Diagram.x_centered_under(a, lines)` — x so a box sits centered under `a` (needed for `arrow_v`).
  57. - For route lanes, use the edges of the boxes: `a.right + 4`, `a.bottom + 2`.
  58. 4. Run it. If it raises `DiagramError`, fix the layout as the message says and run again.
  59. 5. Paste the output into a code block **exactly as printed**. Do not edit it by hand.
  60. For a change, edit the script and run it again.
  61. ## Example 1: header, sections, routes
  62. ```python
  63. import sys; sys.path.insert(0, "/tmp/textdiagram")
  64. from textdiagram import Diagram as D
  65. d = D() # max_width=80 is the default
  66. t = d.header(["Order Platform", "Architecture"],
  67. left=["Acme Inc", "RFC 9000", "Nov 2026"],
  68. right=["*~~~~~~~~~*", "Deep Dive", "*~~~~~~~~~*"])
  69. y = t.bottom + 2
  70. cli = d.box(0, y, ["Client"]) # role="component" is default
  71. gw = d.box(D.x_right_of(cli, "HTTPS"), y, ["Gateway"])
  72. d.arrow_h(cli, gw, "HTTPS")
  73. svc = d.box(gw.x + 16, D.y_below(gw) + 2, # sections: one box, one shadow
  74. [["Auth"], ["Orders"], ["Billing"]], title="Services")
  75. d.route(gw, "bottom", svc, "top", via=[gw.bottom + 3], label="Calls") # S shape
  76. cache = d.box(D.x_left_of(svc, ["Cache"], "Reads"), svc.rows[1] - 1, ["Cache"])
  77. d.arrow_h(svc, cache, "Reads", row=svc.rows[1]) # attach to one section
  78. aud = d.box(svc.right + 9, y, ["Audit"])
  79. d.route(svc, "right", aud, "bottom", a_row=svc.rows[0], label="Events") # one bend
  80. d.route(svc, "right", cli, "bottom", a_row=svc.rows[2], # loop around: 3 bends
  81. via=[svc.right + 4, svc.bottom + 2], label="Retry")
  82. print(d.render())
  83. ```
  84. Output:
  85. ```
  86. ┌────────────┐ ╔══════════════════╗ ┌───────────────┐
  87. │ ACME INC │ ║ ORDER PLATFORM ║ │ *~~~~~~~~~* │
  88. │ RFC 9000 │ ║ ARCHITECTURE ║ │ DEEP DIVE │
  89. │ NOV 2026 │ ║ · ║ │ *~~~~~~~~~* │
  90. └────────────┘ ╚══════════════════╝ └───────────────┘
  91. ┌──────────┐ ┌───────────┐ ┌─────────┐
  92. │ CLIENT │── HTTPS ──▶│ GATEWAY │░ │ AUDIT │░
  93. └──────────┘░ └─────┬─────┘░ └─────────┘░
  94. ░░░░░▲░░░░░░ ░░░░░│░░░░░░░ ░░░░▲░░░░░░
  95. │ │ │
  96. │ │ │
  97. │ └───── CALLS ─────┐ │
  98. │ │ │
  99. │ ▼ │
  100. │ ┌─ SERVICES ────┐ │
  101. │ │ AUTH │─── EVENTS ───┘
  102. │ ┌─────────┐ ├───────────────┤░
  103. │ │ CACHE │◀─ READS ───│ ORDERS │░
  104. │ └─────────┘░ ├───────────────┤░
  105. │ ░░░░░░░░░░░ │ BILLING │────┐
  106. │ └───────────────┘░ │
  107. │ ░░░░░░░░░░░░░░░░░ │
  108. │ │
  109. └─────────────────────── RETRY ────────────────────────┘
  110. ```
  111. ## Example 2: bus, hollow heads, inline label, free text
  112. ```python
  113. import sys; sys.path.insert(0, "/tmp/textdiagram")
  114. from textdiagram import Diagram as D
  115. d = D()
  116. t = d.header(["Event Bus", "Design"], left=["Acme Inc", "ADR 12", "Nov 2026"],
  117. right=["*~~~~~~~*", "Draft", "*~~~~~~~*"])
  118. y = t.bottom + 4
  119. pub = d.box(0, y, ["Publisher"])
  120. s1 = d.box(36, y - 2, ["Billing"])
  121. s2 = d.box(36, y + 4, ["Audit"])
  122. s3 = d.box(36, y + 10, ["Search"])
  123. d.fan_out(pub, [s1, s2, s3], trunk=28, label="Events", head="hollow") # bus, hollow heads
  124. arc = d.box(D.x_centered_under(pub, ["Archive"]), D.y_below(pub, lines=2), ["Archive"])
  125. d.arrow_v(pub, arc, "Nightly\nbackup", inline=True) # label cut into the line
  126. d.annotate(46, y + 16, ["At-least-once", "delivery"]) # free text, no box
  127. print(d.render())
  128. ```
  129. Output:
  130. ```
  131. ┌────────────┐ ╔═════════════╗ ┌─────────────┐
  132. │ ACME INC │ ║ EVENT BUS ║ │ *~~~~~~~* │
  133. │ ADR 12 │ ║ DESIGN ║ │ DRAFT │
  134. │ NOV 2026 │ ║ · ║ │ *~~~~~~~* │
  135. └────────────┘ ╚═════════════╝ └─────────────┘
  136. ┌───────────┐
  137. ┌──────▷│ BILLING │░
  138. ┌─────────────┐ │ └───────────┘░
  139. │ PUBLISHER │── EVENTS ───┤ ░░░░░░░░░░░░░
  140. └──────┬──────┘░ │
  141. ░░░░░░│░░░░░░░░ │
  142. │ ┌─────────┐
  143. NIGHTLY ├──────▷│ AUDIT │░
  144. BACKUP │ └─────────┘░
  145. │ ░░░░░░░░░░░
  146. │ │
  147. ▼ │
  148. ┌───────────┐ │ ┌──────────┐
  149. │ ARCHIVE │░ └──────▷│ SEARCH │░
  150. └───────────┘░ └──────────┘░
  151. ░░░░░░░░░░░░░ ░░░░░░░░░░░░
  152. AT-LEAST-ONCE
  153. DELIVERY
  154. ```
  155. ## API reference
  156. - `D(max_width=80)` — create a diagram; `max_width` is the column limit.
  157. - `d.box(x, y, lines, role="component"|"frame"|"title", title=None, w=None, align="left")` → `Box`
  158. (`.x .y .w .h .right .bottom .cx .rows`; `right`/`bottom` include the shadow).
  159. `lines` is a list of lines, or a list of sections (lists of lines) to split the box.
  160. `box.rows` holds the arrow row of each section. `align="center"` centers the text.
  161. - `d.header(title, left=None, right=None, y=0)` → title `Box`. Each argument is a list of lines.
  162. The boxes get their final `x` at render time. One header per diagram.
  163. - `d.arrow_h(a, b, label="", row=None, head="filled")` — `a` and `b` side by side; works in both
  164. directions. `row` picks a section row (`a.rows[i]`). `head` is `"filled"` or `"hollow"`.
  165. - `d.arrow_v(a, b, label="", head="filled", inline=False)` — `b` below `a`, centered under it.
  166. A label can have more than one line (`"\n"`). With `inline=True`, leave room with
  167. `Diagram.y_below(a, lines=N)`.
  168. - `d.route(a, a_side, b, b_side, via=(), label="", label_seg=None, a_row=None, b_row=None, head="filled", inline=False)`
  169. — sides are `"left" "right" "top" "bottom"`. The line leaves `a_side` of `a` and enters
  170. `b_side` of `b`. It has `len(via) + 2` segments, which alternate across and up/down, starting
  171. with the direction that leaves `a_side`. Each `via` value is the lane of one middle segment:
  172. an x for an up/down segment, a y for an across segment. `via=[]` is one bend, one value is
  173. two bends (S or U shape), two values are three bends (a loop around). `a_row` / `b_row` pick
  174. a section row. `label_seg` picks the segment (from 0) that carries the label.
  175. - `d.fan_out(a, targets, trunk, a_side="right", b_side="left", label="", head="filled", a_row=None, inline=False)`
  176. — a bus. `trunk` is the lane of the shared line: an x for left/right sides, a y for top/bottom.
  177. - `d.arrow_elbow(a, b, label="", mode="vh"|"hv", head="filled")` — one bend, a short form of
  178. `route`. `vh`: leave the bottom of `a`, turn into the side of `b`. `hv`: leave the side of `a`,
  179. turn down into the top of `b`. The direction follows the position of `b`.
  180. - `d.annotate(x, y, lines, align="left")` → `Box` (role `"text"`) — free text, upper-cased.
  181. `lines` is a str (`"\n"` starts a new line) or a list.
  182. - `d.text(x, y, s)` — raw text (not upper-cased).
  183. - `d.render()` — returns the diagram; places the header; checks width and wide characters.
  184. - The engine raises `DiagramError` on overlaps, small gaps, wrong lane values, or lines over max width.
  185. ## If no shell is available
  186. Draw by hand with the same rules. Then count the columns on each line and check that:
  187. the right shadow is one column right of the box; the bottom shadow row starts one column
  188. right of the box's left edge and ends in the shadow column; all box edges line up.
  189. ## Engine source: textdiagram.py
  190. ```python
  191. """textdiagram: draw aligned Unicode box diagrams on a character grid.
  192. Style:
  193. All text is upper case, except the units in KEEP.
  194. COMPONENT box: light lines + light shadow (░) one column right, one row down.
  195. TITLE box: double lines, no shadow, centred over the diagram (placed at render).
  196. FRAME box: light lines, no shadow (note, callout).
  197. Header: title box with an optional meta box (left) and stamp box (right);
  198. padding lines of the title box hold a centred dot.
  199. Sections: one box split by light dividers, one shadow for the whole box.
  200. Horizontal arrow: label inside the line, both ends touch a box: ── LABEL ──▶
  201. Vertical arrow: label right of the line, one row below the shadow.
  202. Route: arrow with any number of bends, set by lane coordinates (via).
  203. Head: filled (▶) or hollow (▷). fan_out: one line that splits into several arrows.
  204. Label on an up/down line: beside the line, or cut into it (inline=True).
  205. annotate: free text with no box.
  206. """
  207. import re
  208. import unicodedata
  209. SHADOW = "░"
  210. MIN_DASH = 2 # dashes on each side of an arrow label
  211. HEADER_GAP = 2 # columns between the header boxes
  212. # Units whose case changes the meaning (MB = byte, Mb = bit, ms = milli, MS = mega).
  213. # A word is kept only if it is written exactly like one of these.
  214. KEEP = {
  215. "Hz", "kHz", "MHz", "GHz",
  216. "kB", "MB", "GB", "TB", "KiB", "MiB", "GiB", "TiB",
  217. "kb", "Mb", "Gb", "Tb", "kbps", "Mbps", "Gbps",
  218. "ms", "µs", "ns",
  219. }
  220. # Box-drawing characters as sets of arms: where two arrow lines meet, the arms
  221. # are joined into one junction character (┼, ├, ...).
  222. ARMS = {"─": "LR", "│": "UD", "┌": "RD", "┐": "LD", "└": "RU", "┘": "LU",
  223. "├": "UDR", "┤": "UDL", "┬": "LRD", "┴": "LRU", "┼": "UDLR"}
  224. BY_ARMS = {frozenset(v): k for k, v in ARMS.items()}
  225. # Route directions: R = right, L = left, D = down, U = up.
  226. STEP = {"R": (1, 0), "L": (-1, 0), "D": (0, 1), "U": (0, -1)}
  227. CORNER = {("R", "D"): "┐", ("R", "U"): "┘", ("L", "D"): "┌", ("L", "U"): "└",
  228. ("D", "R"): "└", ("D", "L"): "┘", ("U", "R"): "┌", ("U", "L"): "┐"}
  229. HEAD = {"R": "▶", "L": "◀", "D": "▼", "U": "▲"}
  230. HOLLOW = {"R": "▷", "L": "◁", "D": "▽", "U": "△"} # second kind of arrow
  231. LEAVE = {"right": "R", "left": "L", "bottom": "D", "top": "U"} # side of the first box
  232. ENTER = {"left": "R", "right": "L", "top": "D", "bottom": "U"} # side of the last box
  233. def cap(s):
  234. """Upper-case all text, except the words in KEEP: 'load 5 ms' -> 'LOAD 5 ms'."""
  235. def fix(m):
  236. w = m.group()
  237. return w if w in KEEP else "".join(c.upper() if c.isascii() else c for c in w)
  238. return re.sub(r"[A-Za-zµ]+", fix, s)
  239. class DiagramError(Exception):
  240. pass
  241. class Box:
  242. def __init__(self, x, y, w, h, role, rows=None):
  243. self.x, self.y, self.w, self.h, self.role = x, y, w, h, role
  244. self.rows = rows or [y + h // 2] # arrow row of each section
  245. self.deferred = False # True: x is set at render time
  246. @property
  247. def right(self): # last column used, shadow included
  248. return self.x + self.w - 1 + (1 if self.role == "component" else 0)
  249. @property
  250. def bottom(self): # last row used, shadow included
  251. return self.y + self.h - 1 + (1 if self.role == "component" else 0)
  252. @property
  253. def cx(self):
  254. return self.x + self.w // 2
  255. class Diagram:
  256. def __init__(self, max_width=80):
  257. self.max_width = max_width
  258. self.cells = {} # (x, y) -> (char, kind)
  259. self._deferred = [] # header boxes: (box, sections, place, align)
  260. # ---- low level -------------------------------------------------------
  261. def _put(self, x, y, ch, kind, allow=()):
  262. if x < 0 or y < 0:
  263. raise DiagramError(f"negative position ({x},{y})")
  264. old = self.cells.get((x, y))
  265. if old and old[1] == "label" and old[0] != " " and kind == "arrow" and ch == "─":
  266. return # the label cut this line
  267. if old and old[0] != ch:
  268. if old[1] == kind == "arrow" and old[0] in ARMS and ch in ARMS:
  269. ch = BY_ARMS[frozenset(ARMS[old[0]]) | frozenset(ARMS[ch])]
  270. elif old[1] not in allow:
  271. raise DiagramError(
  272. f"overlap at col {x}, row {y}: '{old[0]}' ({old[1]}) vs '{ch}' ({kind})"
  273. )
  274. self.cells[(x, y)] = (ch, kind)
  275. def text(self, x, y, s, kind="text"):
  276. for i, ch in enumerate(s):
  277. if ch != " ":
  278. self._put(x + i, y, ch, kind)
  279. else:
  280. self.cells.setdefault((x + i, y), (" ", kind))
  281. @staticmethod
  282. def _check_placed(*boxes):
  283. for b in boxes:
  284. if b.deferred:
  285. raise DiagramError("header boxes are placed at render time: no arrows to or from them")
  286. # ---- boxes -----------------------------------------------------------
  287. @staticmethod
  288. def _sections(lines):
  289. """Normalise lines to a list of sections, each a list of upper-cased lines."""
  290. if isinstance(lines, str):
  291. lines = [lines]
  292. secs = lines if lines and isinstance(lines[0], list) else [lines]
  293. return [[cap(l) for l in sec] for sec in secs]
  294. @staticmethod
  295. def size(lines, title=None, min_w=0):
  296. inner = max([len(l) for l in lines] + [len(title) + 3 if title else 0])
  297. return max(inner + 6, min_w), len(lines) + 2 # 2 spaces pad + 2 border
  298. @staticmethod
  299. def _size(lines, title=None, w=None):
  300. """Width and height of a box for lines (flat, list of sections, or str)."""
  301. secs = Diagram._sections(lines)
  302. flat = [l for sec in secs for l in sec]
  303. bw, _ = Diagram.size(flat, cap(title) if title else None, w or 0)
  304. return bw, len(flat) + len(secs) - 1 + 2
  305. def box(self, x, y, lines, role="component", title=None, w=None, align="left"):
  306. """Draw a box. lines: list of text lines, or a list of sections (lists of
  307. lines) to split the box with dividers. role: 'component' | 'frame' | 'title'."""
  308. if role not in ("component", "frame", "title"):
  309. raise DiagramError("role must be 'component', 'frame' or 'title'")
  310. secs = self._sections(lines)
  311. if role == "title" and len(secs) > 1:
  312. raise DiagramError("title boxes have no sections")
  313. bw, bh = self._size(lines, title, w)
  314. rows, r = [], y + 1
  315. for sec in secs:
  316. rows.append(r + (len(sec) - 1) // 2)
  317. r += len(sec) + 1
  318. box = Box(x, y, bw, bh, role, rows)
  319. if role == "title":
  320. box.deferred = True
  321. self._deferred.append((box, secs, "center", "center"))
  322. else:
  323. self._draw_box(box, secs, cap(title) if title else None, align)
  324. return box
  325. def _draw_box(self, box, secs, title, align):
  326. tl, tr, bl, br, hz, vt = "┌┐└┘─│" if box.role != "title" else "╔╗╚╝═║"
  327. x, y, bw, bh = box.x, box.y, box.w, box.h
  328. top = tl + hz * (bw - 2) + tr
  329. if title:
  330. top = tl + hz + " " + title + " " + hz * (bw - 5 - len(title)) + tr
  331. self.text(x, y, top, "border")
  332. r = y + 1
  333. for i, sec in enumerate(secs):
  334. if i:
  335. self.text(x, r, "├" + "─" * (bw - 2) + "┤", "border")
  336. r += 1
  337. for line in sec:
  338. body = line.center(bw - 6) if align == "center" else line.ljust(bw - 6)
  339. self.text(x, r, vt + " " + body + " " + vt, "border")
  340. r += 1
  341. self.text(x, y + bh - 1, bl + hz * (bw - 2) + br, "border")
  342. if box.role == "component":
  343. for rr in range(y + 1, y + bh):
  344. self._put(x + bw, rr, SHADOW, "shadow")
  345. for c in range(x + 1, x + bw + 1):
  346. self._put(c, y + bh, SHADOW, "shadow")
  347. def header(self, title, left=None, right=None, y=0):
  348. """Title box centred over the diagram, with an optional meta box (left,
  349. left-aligned) and stamp box (right, centred). All get the same height.
  350. Returns the title box; the side boxes sit in the same rows."""
  351. def pad(lines, n, centre, fill=""):
  352. extra = n - len(lines)
  353. top = extra // 2 if centre else 0
  354. return [fill] * top + list(lines) + [fill] * (extra - top)
  355. n = max(len(title), len(left or []), len(right or []))
  356. t = self.box(0, y, pad(title, n, True, "·"), role="title") # dot: padding looks planned
  357. for lines, place, align, centre in ((left, "left", "left", False),
  358. (right, "right", "center", True)):
  359. if lines:
  360. secs = self._sections(pad(lines, n, centre))
  361. bw, bh = self._size(pad(lines, n, centre))
  362. b = Box(0, y, bw, bh, "frame")
  363. b.deferred = True
  364. self._deferred.append((b, secs, place, align))
  365. return t
  366. def _place_deferred(self):
  367. if not self._deferred:
  368. return
  369. places = [p for _, _, p, _ in self._deferred]
  370. if len(set(places)) != len(places):
  371. raise DiagramError("one header (title) per diagram")
  372. items = {p: (b, secs, al) for b, secs, p, al in self._deferred}
  373. t = items["center"][0]
  374. left = items["left"][0] if "left" in items else None
  375. right = items["right"][0] if "right" in items else None
  376. w0 = max([x for x, _ in self.cells] + [-1]) + 1
  377. lw = left.w + HEADER_GAP if left else 0
  378. rw = right.w + HEADER_GAP if right else 0
  379. total = max(w0, lw + t.w + rw)
  380. t.x = min(max((total - t.w) // 2, lw), total - rw - t.w)
  381. if left:
  382. left.x = 0
  383. if right:
  384. right.x = total - right.w
  385. for b, secs, _, al in self._deferred:
  386. self._draw_box(b, secs, None, al)
  387. self._deferred = []
  388. # ---- layout helpers --------------------------------------------------
  389. @staticmethod
  390. def _need(label):
  391. return (len(label) + 2 + 2 * MIN_DASH + 1) if label else 4
  392. @staticmethod
  393. def x_right_of(a, label=""):
  394. """Smallest x for a box to the right of a, with room for the arrow label."""
  395. return a.right + Diagram._need(label)
  396. @staticmethod
  397. def x_left_of(a, lines, label="", title=None, w=None):
  398. """x for a new component box left of a, with room for the arrow label."""
  399. bw, _ = Diagram._size(lines, title, w)
  400. return a.x - bw - Diagram._need(label)
  401. @staticmethod
  402. def y_below(a, lines=0):
  403. """y for a box below a. lines: number of label lines to cut into the arrow
  404. between them (arrow_v with inline=True)."""
  405. if lines: # line, blank, text lines, blank, line, head
  406. return a.bottom + lines + (5 if a.role == "component" else 6)
  407. return a.bottom + (4 if a.role == "component" else 3)
  408. @staticmethod
  409. def x_centered_under(a, lines, title=None, w=None):
  410. bw, _ = Diagram._size(lines, title, w)
  411. return a.cx - bw // 2
  412. # ---- arrows ----------------------------------------------------------
  413. @staticmethod
  414. def _head(head, d):
  415. if head == "filled":
  416. return HEAD[d]
  417. if head == "hollow":
  418. return HOLLOW[d]
  419. raise DiagramError("head must be 'filled' or 'hollow'")
  420. @staticmethod
  421. def _lines(label):
  422. """Label as upper-case lines ('\\n' starts a new line)."""
  423. return cap(label).split("\n") if label else []
  424. @staticmethod
  425. def _inline_v(x, lo, hi, lines):
  426. """A label cut into an up/down line at column x, in rows lo..hi: one blank
  427. row, the text lines centred on x, one blank row. Returns (blank rows, text
  428. cells), or None if there is no room."""
  429. n, zone = len(lines), hi - lo + 1
  430. if zone < n + 2:
  431. return None
  432. top = lo + (zone - n - 2) // 2 + 1
  433. cells = {}
  434. for i, line in enumerate(lines):
  435. x0 = x - len(line) // 2
  436. for j, ch in enumerate(line):
  437. if ch != " ":
  438. cells[(x0 + j, top + i)] = ch
  439. return list(range(top - 1, top + n + 1)), cells
  440. def arrow_h(self, a, b, label="", row=None, head="filled"):
  441. """Arrow from box a (left) to box b (right): ── label ──▶"""
  442. self._check_placed(a, b)
  443. reverse = b.x < a.x
  444. left, right = (b, a) if reverse else (a, b)
  445. y = row if row is not None else max(left.rows[0], right.rows[0])
  446. for bx in (left, right):
  447. if not (bx.y < y < bx.y + bx.h - 1):
  448. raise DiagramError(f"arrow row {y} is not inside both boxes")
  449. x0, x1 = left.x + left.w, right.x - 1 # both ends touch a box
  450. n = x1 - x0 + 1
  451. body = ["─"] * n
  452. if label:
  453. seg = " " + cap(label) + " "
  454. if n < len(seg) + 2 * MIN_DASH + 1:
  455. raise DiagramError(
  456. f"gap too small for label '{label}': use Diagram.x_right_of()"
  457. )
  458. start = (n - len(seg)) // 2
  459. body[start:start + len(seg)] = list(seg)
  460. if reverse:
  461. body[0] = self._head(head, "L")
  462. else:
  463. body[-1] = self._head(head, "R")
  464. for i, ch in enumerate(body):
  465. if ch != " ":
  466. self._put(x0 + i, y, ch, "arrow", allow=("shadow",))
  467. def arrow_v(self, a, b, label="", head="filled", inline=False):
  468. """Arrow from box a (top) down to box b (bottom). The label goes right of
  469. the line, or cut into the line with inline=True (then leave room with
  470. Diagram.y_below(a, lines=N))."""
  471. self._check_placed(a, b)
  472. x = a.cx
  473. if not (b.x < x < b.x + b.w - 1):
  474. raise DiagramError("box b is not under the center of box a: use x_centered_under()")
  475. y0, y1 = a.y + a.h - 1, b.y - 1
  476. first, last = a.bottom + 1, y1 - 1 # rows free for the label
  477. if first > last:
  478. raise DiagramError("vertical gap too small: use Diagram.y_below()")
  479. lines = self._lines(label)
  480. blanks, cells = [], {}
  481. if lines and inline:
  482. res = self._inline_v(x, first + (0 if a.role == "component" else 1), last - 1, lines)
  483. if res is None:
  484. raise DiagramError("vertical gap too small for label: use Diagram.y_below(a, lines=N)")
  485. blanks, cells = res
  486. elif lines:
  487. row = (first + last - (len(lines) - 1)) // 2
  488. if a.role == "component": # keep the label off the row under the shadow
  489. row = max(row, first + 1)
  490. if row + len(lines) - 1 > last:
  491. raise DiagramError("vertical gap too small for label: use Diagram.y_below()")
  492. cells = {(x + 2 + j, row + i): ch for i, line in enumerate(lines)
  493. for j, ch in enumerate(line) if ch != " "}
  494. self._put(x, y0, "┬", "arrow", allow=("border",))
  495. for r in range(y0 + 1, y1):
  496. if r not in blanks:
  497. self._put(x, r, "│", "arrow", allow=("shadow",))
  498. self._put(x, y1, self._head(head, "D"), "arrow")
  499. for (cx, cy), ch in cells.items():
  500. self._put(cx, cy, ch, "label")
  501. @staticmethod
  502. def _anchor(box, side, row, leaving):
  503. """Cell where a route leaves (leaving=True) or enters a box on the given side."""
  504. if side not in LEAVE:
  505. raise DiagramError("side must be 'left', 'right', 'top' or 'bottom'")
  506. if row is not None and not (box.y < row < box.y + box.h - 1):
  507. raise DiagramError(f"row {row} is not inside the box")
  508. y = row if row is not None else box.rows[0]
  509. if side == "right":
  510. return (box.x + box.w, y)
  511. if side == "left":
  512. return (box.x - 1, y)
  513. if side == "top":
  514. return (box.cx, box.y if leaving else box.y - 1)
  515. return (box.cx, box.y + box.h - 1 if leaving else box.y + box.h)
  516. def route(self, a, a_side, b, b_side, via=(), label="", label_seg=None,
  517. a_row=None, b_row=None, head="filled", inline=False):
  518. """Arrow from a side of box a to a side of box b, with any number of bends.
  519. Segments alternate across and up/down, starting with the direction that
  520. leaves a_side. via holds one lane coordinate for each middle segment:
  521. an x for an up/down segment, a y for an across segment. So len(via) + 2
  522. segments are drawn: via=[] is one bend, via=[x] two bends (S or U shape),
  523. via=[x, y] three bends (a loop around). a_row / b_row pick the row of a
  524. section. label_seg picks the segment (from 0) that carries the label.
  525. A label goes inside an across segment, or beside an up/down segment; with
  526. inline=True it is cut into an up/down segment (use '\\n' for more lines)."""
  527. self._check_placed(a, b)
  528. start = self._anchor(a, a_side, a_row, True)
  529. end = self._anchor(b, b_side, b_row, False)
  530. s = len(via) + 2
  531. horiz = [(a_side in ("left", "right")) == (j % 2 == 0) for j in range(s)]
  532. if horiz[-1] != (b_side in ("left", "right")):
  533. raise DiagramError(
  534. f"{s} segments cannot go from {a_side} of a to {b_side} of b: "
  535. "add or remove one via value"
  536. )
  537. coord = [start[1] if horiz[0] else start[0]] + list(via) + \
  538. [end[1] if horiz[-1] else end[0]]
  539. pts = [start]
  540. for j in range(s - 1):
  541. pts.append((coord[j + 1], coord[j]) if horiz[j] else (coord[j], coord[j + 1]))
  542. pts.append(end)
  543. dirs = []
  544. for p, q in zip(pts, pts[1:]):
  545. dx, dy = q[0] - p[0], q[1] - p[1]
  546. if (dx != 0) == (dy != 0):
  547. raise DiagramError("a route segment has zero length: move a via value")
  548. dirs.append(("R" if dx > 0 else "L") if dx else ("D" if dy > 0 else "U"))
  549. if dirs[0] != LEAVE[a_side]:
  550. raise DiagramError(f"route leaves the {a_side} of a backwards: move a via value")
  551. if dirs[-1] != ENTER[b_side]:
  552. raise DiagramError(f"route enters the {b_side} of b backwards: move a via value")
  553. # walk the cells of the path: [x, y, direction in, direction out]
  554. path = [[start[0], start[1], None, None]]
  555. x, y = start
  556. for k, d in enumerate(dirs):
  557. while (x, y) != pts[k + 1]:
  558. x, y = x + STEP[d][0], y + STEP[d][1]
  559. path.append([x, y, d, None])
  560. for i in range(len(path) - 1):
  561. path[i][3] = path[i + 1][2]
  562. chars = {}
  563. for i, (x, y, din, dout) in enumerate(path):
  564. if i == len(path) - 1:
  565. ch = self._head(head, din)
  566. elif din is None or din == dout:
  567. ch = "─" if dout in "RL" else "│"
  568. else:
  569. ch = CORNER[(din, dout)]
  570. chars[(x, y)] = ch
  571. if a_side in ("top", "bottom"):
  572. chars[start] = "┴" if a_side == "top" else "┬"
  573. in_line, beside = set(), {}
  574. if label:
  575. in_line, beside = self._route_label(
  576. chars, pts, dirs, self._lines(label), label_seg, a, a_side, inline)
  577. for i, (x, y, _, _) in enumerate(path):
  578. ch = chars[(x, y)]
  579. old = self.cells.get((x, y))
  580. if ch == " ": # gap cut into a line by a label
  581. if old and old[1] == "arrow" and old[0] in "─│":
  582. del self.cells[(x, y)]
  583. continue
  584. if (x, y) in in_line and old and old[1] == "arrow" and old[0] == "─":
  585. del self.cells[(x, y)]
  586. allow = ("shadow", "border") if i == 0 else ("shadow",)
  587. self._put(x, y, ch, "label" if (x, y) in in_line else "arrow", allow=allow)
  588. for (x, y), ch in beside.items():
  589. self._put(x, y, ch, "label")
  590. def _route_label(self, chars, pts, dirs, lines, label_seg, a, a_side, inline):
  591. """Choose a segment for the label. A label on an across segment replaces
  592. cells of the line (changes chars, returns their positions); a label on an
  593. up/down segment goes beside the line, or is cut into it (returned as a dict
  594. of text cells; the line cells that it cuts are set to a space in chars)."""
  595. s, n = len(dirs), len(lines)
  596. label = lines[0] if n == 1 else ""
  597. seg = " " + label + " "
  598. options = [] # (kind, k, lo, hi)
  599. for k, d in enumerate(dirs):
  600. p, q = pts[k], pts[k + 1]
  601. if d in "RL":
  602. if n != 1 or inline:
  603. continue
  604. lo, hi = (p[0] + (k > 0), q[0] - (k < s - 1)) if d == "R" else \
  605. (q[0] + (k < s - 1), p[0] - (k > 0))
  606. need = len(seg) + 2 * MIN_DASH + (1 if k == s - 1 else 0)
  607. if hi - lo + 1 >= need:
  608. options.append(("h", k, lo, hi))
  609. else:
  610. lo, hi = (p[1] + 1, q[1] - 1) if d == "D" else (q[1] + 1, p[1] - 1)
  611. shadowed = k == 0 and a_side == "bottom" and a.role == "component"
  612. if inline: # keep one line cell next to the corner, head or shadow
  613. lo, hi = lo + 1, hi - 1
  614. elif shadowed:
  615. lo += 2 # beside the line: not right under the shadow
  616. if hi - lo + 1 >= (n + 2 if inline else n):
  617. options.append(("v", k, lo, hi))
  618. if label_seg is not None:
  619. options = [o for o in options if o[1] == label_seg]
  620. pool = [o for o in options if o[0] == "h"] or options
  621. if not pool:
  622. raise DiagramError(f"no room for the label: move the boxes or the via lanes")
  623. kind, k, lo, hi = max(pool, key=lambda o: o[3] - o[2])
  624. if kind == "h":
  625. y = pts[k][1]
  626. extra = (hi - lo + 1) - len(seg)
  627. head_at_lo = k == s - 1 and dirs[k] == "L"
  628. off = extra - extra // 2 if head_at_lo else extra // 2
  629. in_line = set()
  630. for i, ch in enumerate(seg):
  631. chars[(lo + off + i, y)] = ch
  632. if ch != " ":
  633. in_line.add((lo + off + i, y))
  634. return in_line, {}
  635. x = pts[k][0]
  636. if inline:
  637. blanks, cells = self._inline_v(x, lo, hi, lines)
  638. for r in blanks:
  639. chars[(x, r)] = " "
  640. return set(), cells
  641. row = max((lo + hi - (n - 1)) // 2, lo)
  642. return set(), {(x + 2 + j, row + i): ch for i, line in enumerate(lines)
  643. for j, ch in enumerate(line) if ch != " "}
  644. def arrow_elbow(self, a, b, label="", mode="vh", head="filled"):
  645. """Arrow with one bend (a route with no via lane).
  646. mode 'vh': leave the bottom of a, go down, turn into the side of b.
  647. mode 'hv': leave the side of a, go across, turn down into the top of b.
  648. The direction (left or right) follows the position of b."""
  649. if mode == "vh":
  650. self.route(a, "bottom", b, "left" if b.x > a.cx else "right",
  651. label=label, head=head)
  652. elif mode == "hv":
  653. self.route(a, "right" if b.cx > a.right else "left", b, "top",
  654. label=label, head=head)
  655. else:
  656. raise DiagramError("mode must be 'vh' or 'hv'")
  657. def fan_out(self, a, targets, trunk, a_side="right", b_side="left", label="",
  658. head="filled", a_row=None, inline=False):
  659. """One line from a that splits at lane `trunk` into one arrow per target
  660. (a bus). trunk is an x when a_side is left/right, a y when top/bottom. The
  661. label goes on the shared line."""
  662. for i, b in enumerate(targets):
  663. last = i == len(targets) - 1 # draw the label last: it cuts the line
  664. self.route(a, a_side, b, b_side, via=[trunk], a_row=a_row, head=head,
  665. label=label if last else "", label_seg=0, inline=inline)
  666. def annotate(self, x, y, lines, align="left"):
  667. """Free text with no box (a note beside the diagram). Returns a Box (role
  668. 'text') for layout. lines: a str ('\\n' starts a new line) or a list."""
  669. lines = self._lines(lines) if isinstance(lines, str) else [cap(l) for l in lines]
  670. w = max(len(l) for l in lines)
  671. for i, line in enumerate(lines):
  672. self.text(x, y + i, line.center(w) if align == "center" else line, "label")
  673. return Box(x, y, w, len(lines), "text")
  674. # ---- output ----------------------------------------------------------
  675. def render(self):
  676. self._place_deferred()
  677. if not self.cells:
  678. return ""
  679. W = max(x for x, _ in self.cells) + 1
  680. H = max(y for _, y in self.cells) + 1
  681. grid = [[" "] * W for _ in range(H)]
  682. for (x, y), (ch, _) in self.cells.items():
  683. grid[y][x] = ch
  684. out = "\n".join("".join(r).rstrip() for r in grid)
  685. self.check(out)
  686. return out
  687. def check(self, out):
  688. for n, line in enumerate(out.split("\n"), 1):
  689. if len(line) > self.max_width:
  690. raise DiagramError(f"line {n} is {len(line)} cols (max {self.max_width})")
  691. for ch in line:
  692. if unicodedata.east_asian_width(ch) in ("W", "F"):
  693. raise DiagramError(f"wide character '{ch}' on line {n}")
  694. ```
README.md · README · 47 lines
  1. # unicode-diagrams
  2. A Claude Code skill that draws architecture, system design and flow diagrams as Unicode
  3. box-drawing art with light shadows. A small Python engine places every box and arrow on a
  4. grid, so the lines always line up.
  5. ```
  6. ┌────────────┐ ╔══════════════════╗ ┌───────────────┐
  7. │ ACME INC │ ║ ORDER PLATFORM ║ │ *~~~~~~~~~* │
  8. │ RFC 9000 │ ║ ARCHITECTURE ║ │ DEEP DIVE │
  9. │ NOV 2026 │ ║ · ║ │ *~~~~~~~~~* │
  10. └────────────┘ ╚══════════════════╝ └───────────────┘
  11. ┌──────────┐ ┌───────────┐ ┌─────────┐
  12. │ CLIENT │── HTTPS ──▶│ GATEWAY │░ │ AUDIT │░
  13. └──────────┘░ └─────┬─────┘░ └─────────┘░
  14. ░░░░░▲░░░░░░ ░░░░░│░░░░░░░ ░░░░▲░░░░░░
  15. │ │ │
  16. │ │ │
  17. │ └───── CALLS ─────┐ │
  18. │ │ │
  19. │ ▼ │
  20. │ ┌─ SERVICES ────┐ │
  21. │ │ AUTH │─── EVENTS ───┘
  22. │ ┌─────────┐ ├───────────────┤░
  23. │ │ CACHE │◀─ READS ───│ ORDERS │░
  24. │ └─────────┘░ ├───────────────┤░
  25. │ ░░░░░░░░░░░ │ BILLING │────┐
  26. │ └───────────────┘░ │
  27. │ ░░░░░░░░░░░░░░░░░ │
  28. │ │
  29. └─────────────────────── RETRY ────────────────────────┘
  30. ```
  31. ## Install
  32. ```
  33. git clone https://github.com/rohalrafael/unicode-diagrams ~/.claude/skills/unicode-diagrams
  34. ```
  35. Python 3 is the only requirement. Then ask Claude for a text diagram, or type `/unicode-diagrams`.
  36. The style rules, the API and the engine source are in [SKILL.md](SKILL.md).
  37. ## Inspiration
  38. The look comes from the TX-02 box-drawing sample by [US Graphics](https://usgraphics.com).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.