context-mapper 0.20.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- context_mapper/__init__.py +1 -0
- context_mapper/__main__.py +6 -0
- context_mapper/build.py +137 -0
- context_mapper/graph.py +428 -0
- context_mapper/mermaid.py +647 -0
- context_mapper/serve.py +166 -0
- context_mapper/template/app.js +622 -0
- context_mapper/template/index.html +50 -0
- context_mapper/template/style.css +47 -0
- context_mapper-0.20.2.dist-info/METADATA +211 -0
- context_mapper-0.20.2.dist-info/RECORD +15 -0
- context_mapper-0.20.2.dist-info/WHEEL +5 -0
- context_mapper-0.20.2.dist-info/entry_points.txt +2 -0
- context_mapper-0.20.2.dist-info/licenses/LICENSE +15 -0
- context_mapper-0.20.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
"""Render the domain model as Mermaid flowcharts.
|
|
2
|
+
|
|
3
|
+
The `mermaid` section of context-map.style.yml controls how diagrams look. See the comments
|
|
4
|
+
there and the README for every option. build.py calls `build(data, config, out)`.
|
|
5
|
+
"""
|
|
6
|
+
import html
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import graph
|
|
12
|
+
|
|
13
|
+
VIEW_DEFAULTS = {
|
|
14
|
+
"level": "context",
|
|
15
|
+
"depth": 1,
|
|
16
|
+
"dir": "both",
|
|
17
|
+
"display": None,
|
|
18
|
+
"hide": [],
|
|
19
|
+
"child_labels": True,
|
|
20
|
+
"group_by_type": False,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
TOP_DEFAULTS = {
|
|
24
|
+
"direction": "BT",
|
|
25
|
+
"theme": "base",
|
|
26
|
+
"layout": "dagre",
|
|
27
|
+
"look": "classic",
|
|
28
|
+
"curve": "basis",
|
|
29
|
+
"theme_variables": {},
|
|
30
|
+
"config": {},
|
|
31
|
+
"markdown_config": {},
|
|
32
|
+
"defaults": {},
|
|
33
|
+
"focus_style": {"stroke-width": "4px", "font-weight": "bold"},
|
|
34
|
+
"domain_style": {"fill": "#ffffff", "stroke": "#b0b0b0"},
|
|
35
|
+
"edge_styles": {},
|
|
36
|
+
"pages": "all",
|
|
37
|
+
"views": [],
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
VIEW_ONLY = {"id", "title", "focus", "description", "direction"}
|
|
41
|
+
|
|
42
|
+
# The kinds of edge `edge_styles` can style: a plain one, and `style: dotted` on a downstream.
|
|
43
|
+
EDGE_KINDS = ("solid", "dotted")
|
|
44
|
+
|
|
45
|
+
ALLOWED = {
|
|
46
|
+
"direction": {"TB", "BT", "LR", "RL"},
|
|
47
|
+
"layout": {"dagre", "elk"},
|
|
48
|
+
"look": {"classic", "handDrawn"},
|
|
49
|
+
"curve": {"basis", "bumpX", "bumpY", "cardinal", "catmullRom", "linear", "monotoneX",
|
|
50
|
+
"monotoneY", "natural", "step", "stepAfter", "stepBefore"},
|
|
51
|
+
"level": {"context", "domain"},
|
|
52
|
+
"dir": {"both", "up", "down"},
|
|
53
|
+
"display": set(graph.DISPLAY_STATES),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def settings(config):
|
|
58
|
+
"""Fill in defaults and check every key and value. Returns (settings, errors)."""
|
|
59
|
+
config = config or {}
|
|
60
|
+
errors = []
|
|
61
|
+
for key in config:
|
|
62
|
+
if key not in TOP_DEFAULTS:
|
|
63
|
+
errors.append(f"mermaid.{key}: unknown option. Known: {', '.join(sorted(TOP_DEFAULTS))}")
|
|
64
|
+
cfg = {**TOP_DEFAULTS, **config}
|
|
65
|
+
cfg["defaults"] = {**VIEW_DEFAULTS, **(cfg.get("defaults") or {})}
|
|
66
|
+
|
|
67
|
+
for key in ("direction", "layout", "look", "curve"):
|
|
68
|
+
if cfg[key] not in ALLOWED[key]:
|
|
69
|
+
errors.append(f"mermaid.{key} must be one of: {', '.join(sorted(ALLOWED[key]))}")
|
|
70
|
+
|
|
71
|
+
for key in cfg["defaults"]:
|
|
72
|
+
if key not in VIEW_DEFAULTS:
|
|
73
|
+
errors.append(f"mermaid.defaults.{key}: unknown option. Known: {', '.join(sorted(VIEW_DEFAULTS))}")
|
|
74
|
+
for view in [cfg["defaults"], *cfg["views"]]:
|
|
75
|
+
where = "defaults" if view is cfg["defaults"] else f"views.{view.get('id', '?')}"
|
|
76
|
+
if view is not cfg["defaults"]:
|
|
77
|
+
if "id" not in view:
|
|
78
|
+
errors.append("mermaid.views: every view needs an id")
|
|
79
|
+
for key in view:
|
|
80
|
+
if key not in VIEW_DEFAULTS and key not in VIEW_ONLY:
|
|
81
|
+
errors.append(f"mermaid.{where}.{key}: unknown option. Known: "
|
|
82
|
+
f"{', '.join(sorted({*VIEW_DEFAULTS, *VIEW_ONLY}))}")
|
|
83
|
+
for key in ("level", "dir", "direction"):
|
|
84
|
+
if key in view and view[key] not in ALLOWED[key]:
|
|
85
|
+
errors.append(f"mermaid.{where}.{key} must be one of {', '.join(sorted(ALLOWED[key]))}")
|
|
86
|
+
display = view.get("display")
|
|
87
|
+
for mode in (display.values() if isinstance(display, dict) else [display]):
|
|
88
|
+
if mode is not None and mode not in ALLOWED["display"]:
|
|
89
|
+
errors.append(f"mermaid.{where}.display must be one of {', '.join(sorted(ALLOWED['display']))}, "
|
|
90
|
+
"or a map from domain id to one of those")
|
|
91
|
+
hide = view.get("hide")
|
|
92
|
+
if hide is not None and not isinstance(hide, list):
|
|
93
|
+
errors.append(f"mermaid.{where}.hide must be a list of ids, such as `hide: [crm]`")
|
|
94
|
+
|
|
95
|
+
# Styles are written like the ones in `types`, `clusters` and `context-map`: a map of
|
|
96
|
+
# Mermaid attributes. Past this point they are classDef strings, which is what the
|
|
97
|
+
# renderers (here and in the page's script) put straight into the diagram.
|
|
98
|
+
for key in ("focus_style", "domain_style"):
|
|
99
|
+
cfg[key] = attribute_string(f"mermaid.{key}", cfg[key], errors)
|
|
100
|
+
edge_styles = cfg["edge_styles"]
|
|
101
|
+
if isinstance(edge_styles, dict):
|
|
102
|
+
for kind in edge_styles:
|
|
103
|
+
if kind not in EDGE_KINDS:
|
|
104
|
+
errors.append(f"mermaid.edge_styles.{kind}: unknown option. Known: {', '.join(EDGE_KINDS)}")
|
|
105
|
+
cfg["edge_styles"] = {kind: attribute_string(f"mermaid.edge_styles.{kind}", attrs, errors)
|
|
106
|
+
for kind, attrs in edge_styles.items()}
|
|
107
|
+
else:
|
|
108
|
+
errors.append("mermaid.edge_styles must be a map from solid or dotted to Mermaid attributes")
|
|
109
|
+
cfg["edge_styles"] = {}
|
|
110
|
+
return cfg, errors
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def attribute_string(where, attrs, errors):
|
|
114
|
+
"""Check a map of Mermaid style attributes and return it as a classDef string."""
|
|
115
|
+
if not isinstance(attrs, dict):
|
|
116
|
+
errors.append(f"{where} must be a map of Mermaid attributes, "
|
|
117
|
+
"such as `stroke: \"#313131\"`")
|
|
118
|
+
return ""
|
|
119
|
+
for key in attrs:
|
|
120
|
+
if key not in graph.BOX_STYLE_KEYS:
|
|
121
|
+
errors.append(f"{where}.{key}: unknown option. Known: {', '.join(sorted(graph.BOX_STYLE_KEYS))}")
|
|
122
|
+
return graph.classdef({key: value for key, value in attrs.items() if key in graph.BOX_STYLE_KEYS}, {})
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def display_mode(view, domain):
|
|
126
|
+
"""How a container first renders: the view's `display`, else the domain's
|
|
127
|
+
own `defaultDisplay` from the style file, else expanded."""
|
|
128
|
+
display = view["display"]
|
|
129
|
+
mode = display.get(domain["id"]) if isinstance(display, dict) else display
|
|
130
|
+
return mode or domain.get("defaultDisplay") or "expanded"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def deep_merge(base, extra):
|
|
134
|
+
out = dict(base)
|
|
135
|
+
for key, value in (extra or {}).items():
|
|
136
|
+
out[key] = deep_merge(out[key], value) if isinstance(value, dict) and isinstance(out.get(key), dict) else value
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def mermaid_config(cfg, markdown=False):
|
|
141
|
+
base = {
|
|
142
|
+
"theme": cfg["theme"],
|
|
143
|
+
"layout": cfg["layout"],
|
|
144
|
+
"look": cfg["look"],
|
|
145
|
+
"flowchart": {"curve": cfg["curve"], "htmlLabels": True},
|
|
146
|
+
"themeVariables": cfg["theme_variables"],
|
|
147
|
+
}
|
|
148
|
+
merged = deep_merge(base, cfg["config"])
|
|
149
|
+
return deep_merge(merged, cfg["markdown_config"]) if markdown else merged
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def uses_elk(cfg):
|
|
153
|
+
return str(mermaid_config(cfg).get("layout", "")).startswith("elk")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def client_settings(cfg):
|
|
157
|
+
"""The parts of the Mermaid settings the interactive page needs to draw the same diagrams."""
|
|
158
|
+
client_config = mermaid_config(cfg)
|
|
159
|
+
defaults = cfg["defaults"]
|
|
160
|
+
return {
|
|
161
|
+
"config": client_config,
|
|
162
|
+
"elk": uses_elk(cfg),
|
|
163
|
+
"direction": cfg["direction"],
|
|
164
|
+
"curve": client_config["flowchart"].get("curve", cfg["curve"]),
|
|
165
|
+
"focus_style": cfg["focus_style"],
|
|
166
|
+
"domain_style": cfg["domain_style"],
|
|
167
|
+
"edge_styles": cfg["edge_styles"],
|
|
168
|
+
"display": defaults["display"],
|
|
169
|
+
"hide": defaults["hide"],
|
|
170
|
+
"child_labels": defaults["child_labels"],
|
|
171
|
+
"group_by_type": defaults["group_by_type"],
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def node_id(item_id):
|
|
176
|
+
return re.sub(r"\W", "_", item_id)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def text(value):
|
|
180
|
+
return value.replace('"', "#quot;")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def render(data, cfg, view, links=None, markdown=False):
|
|
184
|
+
"""Return Mermaid source for one view. `links` maps an id to a URL for click handlers.
|
|
185
|
+
With `markdown`, `markdown_config` is merged in, for renderers like GitLab's that lack ELK."""
|
|
186
|
+
domains, contexts, owner, names = graph.index(data)
|
|
187
|
+
types = data["types"]
|
|
188
|
+
level = view["level"]
|
|
189
|
+
level_graph = graph.level_graph(data, level)
|
|
190
|
+
starts = graph.focus_set(data, level, view.get("focus"))
|
|
191
|
+
|
|
192
|
+
# A container is a domain that holds bounded contexts, or a cluster that
|
|
193
|
+
# holds members. Its display comes from the view, its own `defaultDisplay`,
|
|
194
|
+
# or expanded; a focused domain opens up.
|
|
195
|
+
containers = {domain["id"]: domain for domain in data["domains"] if not domain["single"]}
|
|
196
|
+
containers.update({cluster["id"]: cluster for cluster in data["clusters"]})
|
|
197
|
+
display_states = {container_id: ("expanded" if container_id in starts else display_mode(view, containers[container_id]))
|
|
198
|
+
for container_id in containers}
|
|
199
|
+
|
|
200
|
+
# `hide` names what this view never draws: a domain or cluster goes with
|
|
201
|
+
# everything inside it, a bounded context with just its own box. A bounded
|
|
202
|
+
# context — a single domain is one too — with `defaultDisplay: hidden` in
|
|
203
|
+
# the style file hides the same way, everywhere but as the focus. The focus
|
|
204
|
+
# itself is never hidden — a page still shows what it is a page of.
|
|
205
|
+
hidden = graph.descendants(level_graph,
|
|
206
|
+
{container_id for container_id, mode in display_states.items() if mode == "hidden"}
|
|
207
|
+
| {context["id"] for context in data["contexts"]
|
|
208
|
+
if context.get("defaultDisplay") == "hidden"}
|
|
209
|
+
| set(view.get("hide") or []))
|
|
210
|
+
if view.get("focus"):
|
|
211
|
+
starts = (starts - hidden) | {view["focus"]}
|
|
212
|
+
if level == "domain" and view["focus"] in owner:
|
|
213
|
+
starts.add(owner[view["focus"]])
|
|
214
|
+
visible = graph.walk(level_graph, starts, view["depth"], view["dir"], hidden)
|
|
215
|
+
|
|
216
|
+
# What a container holds at this level, and what folded into a collapsed one.
|
|
217
|
+
kids_of = {}
|
|
218
|
+
for child, parent in level_graph["child_of"].items():
|
|
219
|
+
kids_of.setdefault(parent, []).append(child)
|
|
220
|
+
|
|
221
|
+
def held(container):
|
|
222
|
+
"""A container's children that are nodes at this level: a domain holds
|
|
223
|
+
bounded contexts there, a cluster holds members anywhere."""
|
|
224
|
+
inside = [child_id for child_id in container.get("contexts", []) if child_id != container["id"]] if level == "context" else []
|
|
225
|
+
return inside + [member for member in container.get("members", []) if member != container["id"]]
|
|
226
|
+
|
|
227
|
+
folded = {} # node -> the collapsed container it folded into
|
|
228
|
+
|
|
229
|
+
def fold(container_id, into_id):
|
|
230
|
+
for child in kids_of.get(container_id, []):
|
|
231
|
+
if child in starts:
|
|
232
|
+
continue
|
|
233
|
+
if child in visible:
|
|
234
|
+
folded[child] = into_id
|
|
235
|
+
fold(child, into_id)
|
|
236
|
+
|
|
237
|
+
def collapsed_ancestor(container_id):
|
|
238
|
+
parent = level_graph["child_of"].get(container_id)
|
|
239
|
+
while parent:
|
|
240
|
+
if display_states.get(parent) == "collapsed":
|
|
241
|
+
return True
|
|
242
|
+
parent = level_graph["child_of"].get(parent)
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
for container_id, mode in display_states.items():
|
|
246
|
+
if mode == "collapsed" and not collapsed_ancestor(container_id):
|
|
247
|
+
fold(container_id, container_id)
|
|
248
|
+
|
|
249
|
+
config_json = json.dumps({"config": mermaid_config(cfg, markdown)})
|
|
250
|
+
lines = ["---", config_json, "---", f"flowchart {view.get('direction', cfg['direction'])}"]
|
|
251
|
+
for type_id, type_entry in types.items():
|
|
252
|
+
lines.append(f" classDef {type_id} {type_entry['mermaid_style']}")
|
|
253
|
+
lines.append(f" classDef focus {cfg['focus_style']}")
|
|
254
|
+
|
|
255
|
+
plain_nodes = [] # ids drawn as plain boxes, for focus and click lines
|
|
256
|
+
drawn = set() # ids drawn at all: a box, or a wrapper around others
|
|
257
|
+
|
|
258
|
+
def box(item_id, label, type_id, indent):
|
|
259
|
+
plain_nodes.append(item_id)
|
|
260
|
+
drawn.add(item_id)
|
|
261
|
+
cls = f":::{type_id}" if type_id else ""
|
|
262
|
+
return f'{indent}{node_id(item_id)}["{label}"]{cls}'
|
|
263
|
+
|
|
264
|
+
def draw_child(child_id, indent):
|
|
265
|
+
"""One child of a container. A single bounded context is in both payloads;
|
|
266
|
+
the domain entry carries its style, so it wins."""
|
|
267
|
+
if child_id in contexts and child_id not in domains:
|
|
268
|
+
lines = [box(child_id, text(contexts[child_id]["name"]), contexts[child_id]["type"], indent)]
|
|
269
|
+
if contexts[child_id].get("mermaid_style"):
|
|
270
|
+
lines.append(f"{indent}style {node_id(child_id)} {contexts[child_id]['mermaid_style']}")
|
|
271
|
+
return lines
|
|
272
|
+
return draw_entry(domains[child_id], indent)
|
|
273
|
+
|
|
274
|
+
def draw_entry(container, indent):
|
|
275
|
+
"""Lines for one container: a plain box, a wrapper with the boxes inside it,
|
|
276
|
+
the boxes inside it without a wrapper of its own, or nothing."""
|
|
277
|
+
container_id = container["id"]
|
|
278
|
+
if container_id in folded or (container_id in hidden and container_id != view.get("focus")):
|
|
279
|
+
return []
|
|
280
|
+
mode = display_states.get(container_id, "expanded")
|
|
281
|
+
if mode == "hidden":
|
|
282
|
+
return []
|
|
283
|
+
is_cluster = container_id not in domains
|
|
284
|
+
kids = held(container)
|
|
285
|
+
folded_kids = [child_id for child_id in kids if folded.get(child_id) == container_id]
|
|
286
|
+
inside = [child_id for child_id in kids if child_id in visible and child_id not in folded]
|
|
287
|
+
if is_cluster:
|
|
288
|
+
# A cluster isn't a node in the walk: it draws only through what it holds.
|
|
289
|
+
# The focus is the exception: with everything it holds hidden, it is
|
|
290
|
+
# still one box of its own.
|
|
291
|
+
if mode == "collapsed" and not folded_kids:
|
|
292
|
+
return []
|
|
293
|
+
if mode == "expanded" and not inside and container_id != view.get("focus"):
|
|
294
|
+
return []
|
|
295
|
+
elif container_id not in visible and not folded_kids and not inside \
|
|
296
|
+
and not any(child_id in starts for child_id in kids):
|
|
297
|
+
# Not reached itself, holds nothing that was reached, and no start
|
|
298
|
+
# either. A domain that holds one of those — the focus of a
|
|
299
|
+
# bounded-context view, or a context reached on its own — still
|
|
300
|
+
# draws, so it has a box to appear in.
|
|
301
|
+
return []
|
|
302
|
+
if mode == "contents":
|
|
303
|
+
return [line for child_id in inside for line in draw_child(child_id, indent)]
|
|
304
|
+
if mode == "expanded" and kids:
|
|
305
|
+
if not inside:
|
|
306
|
+
# Nothing inside was reached: show what is there that isn't
|
|
307
|
+
# hidden. A start is never hidden, not even by `hide`.
|
|
308
|
+
inside = [child_id for child_id in kids
|
|
309
|
+
if child_id not in folded and (child_id not in hidden or child_id in starts)]
|
|
310
|
+
if inside:
|
|
311
|
+
entry_lines = [f'{indent}subgraph {node_id(container_id)}["{text(container["name"])}"]']
|
|
312
|
+
for child_id in inside:
|
|
313
|
+
entry_lines += draw_child(child_id, indent + " ")
|
|
314
|
+
entry_lines.append(f"{indent}end")
|
|
315
|
+
drawn.add(container_id)
|
|
316
|
+
style = container.get("mermaid_style") or cfg["domain_style"]
|
|
317
|
+
if container_id == view.get("focus"):
|
|
318
|
+
style += "," + cfg["focus_style"]
|
|
319
|
+
entry_lines.append(f"{indent}style {node_id(container_id)} {style}")
|
|
320
|
+
return entry_lines
|
|
321
|
+
# A plain box: the container alone. With `child_labels`, it names what it holds.
|
|
322
|
+
label = text(container["name"])
|
|
323
|
+
if view["child_labels"] and not container.get("single", False):
|
|
324
|
+
named = sorted(names[child_id] for child_id in container.get("contexts", [])
|
|
325
|
+
if child_id != container_id and child_id not in hidden)
|
|
326
|
+
named += sorted(names[member] for member in container.get("members", []) if folded.get(member) == container_id)
|
|
327
|
+
if named:
|
|
328
|
+
label = f"<b>{label}</b><br/>{text(', '.join(named))}"
|
|
329
|
+
entry_lines = [box(container_id, label, container.get("type"), indent)]
|
|
330
|
+
if container.get("mermaid_style"):
|
|
331
|
+
entry_lines.append(f"{indent}style {node_id(container_id)} {container['mermaid_style']}")
|
|
332
|
+
return entry_lines
|
|
333
|
+
|
|
334
|
+
# A domain drawn inside another container comes from that container's own drawing.
|
|
335
|
+
opens = {container_id for container_id, mode in display_states.items()
|
|
336
|
+
if mode in ("expanded", "contents") and container_id not in folded and container_id not in hidden
|
|
337
|
+
and (container_id not in domains or container_id in visible)}
|
|
338
|
+
|
|
339
|
+
def at_top(container):
|
|
340
|
+
return level_graph["child_of"].get(container["id"]) not in opens
|
|
341
|
+
|
|
342
|
+
if view["group_by_type"]:
|
|
343
|
+
for type_id, type_entry in types.items():
|
|
344
|
+
block = [line for domain in data["domains"] if domain["type"] == type_id and at_top(domain)
|
|
345
|
+
for line in draw_entry(domain, " ")]
|
|
346
|
+
if block:
|
|
347
|
+
lines += [f' subgraph type_{type_id}["{text(type_entry["name"])}"]', *block, " end"]
|
|
348
|
+
else:
|
|
349
|
+
for domain in data["domains"]:
|
|
350
|
+
if at_top(domain):
|
|
351
|
+
lines += draw_entry(domain, " ")
|
|
352
|
+
for cluster in data["clusters"]:
|
|
353
|
+
lines += draw_entry(cluster, " ")
|
|
354
|
+
|
|
355
|
+
# Merge edges that land on the same pair once containers are collapsed.
|
|
356
|
+
def folded_target(node):
|
|
357
|
+
return folded.get(node, node)
|
|
358
|
+
|
|
359
|
+
folded_boxes = set(folded.values())
|
|
360
|
+
merged = {}
|
|
361
|
+
for edge in level_graph["edges"]:
|
|
362
|
+
if edge["from"] not in visible or edge["to"] not in visible:
|
|
363
|
+
continue
|
|
364
|
+
from_id, to_id = folded_target(edge["from"]), folded_target(edge["to"])
|
|
365
|
+
if from_id == to_id or from_id not in drawn or to_id not in drawn:
|
|
366
|
+
continue
|
|
367
|
+
entry = merged.setdefault((from_id, to_id), {"styles": set(), "names": set()})
|
|
368
|
+
entry["styles"] |= edge["styles"]
|
|
369
|
+
if to_id in folded_boxes:
|
|
370
|
+
entry["names"].add(names[edge["to"]])
|
|
371
|
+
elif from_id in folded_boxes:
|
|
372
|
+
entry["names"].add(names[edge["from"]])
|
|
373
|
+
|
|
374
|
+
by_style = {}
|
|
375
|
+
for edge_index, ((from_id, to_id), entry) in enumerate(merged.items()):
|
|
376
|
+
edge_style = "solid" if "solid" in entry["styles"] else sorted(entry["styles"])[0]
|
|
377
|
+
arrow = "-.->" if edge_style == "dotted" else "-->"
|
|
378
|
+
label = ""
|
|
379
|
+
if entry["names"] and view["child_labels"]:
|
|
380
|
+
label = f'|"{text(", ".join(sorted(entry["names"])))}"|'
|
|
381
|
+
lines.append(f" {node_id(from_id)} {arrow}{label} {node_id(to_id)}")
|
|
382
|
+
by_style.setdefault(edge_style, []).append(str(edge_index))
|
|
383
|
+
|
|
384
|
+
# `interpolate` sets the curve per edge, which works even where the config is ignored.
|
|
385
|
+
for edge_style, edge_indexes in by_style.items():
|
|
386
|
+
extra = cfg["edge_styles"].get(edge_style, "")
|
|
387
|
+
curve = mermaid_config(cfg, markdown)["flowchart"].get("curve", cfg["curve"])
|
|
388
|
+
lines.append(f" linkStyle {','.join(edge_indexes)} interpolate {curve} {extra}".rstrip())
|
|
389
|
+
|
|
390
|
+
# Highlight only the focused item itself: a domain focus marks the domain box, not each context.
|
|
391
|
+
highlight = owner[view["focus"]] if level == "domain" and view.get("focus") in owner else view.get("focus")
|
|
392
|
+
for node in plain_nodes:
|
|
393
|
+
if node == highlight:
|
|
394
|
+
lines.append(f" class {node_id(node)} focus")
|
|
395
|
+
if links:
|
|
396
|
+
for node in plain_nodes:
|
|
397
|
+
if node in links:
|
|
398
|
+
lines.append(f' click {node_id(node)} href "{links[node]}"')
|
|
399
|
+
|
|
400
|
+
return "\n".join(lines) + "\n"
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def page_items(data, cfg):
|
|
404
|
+
"""Ids that get their own page."""
|
|
405
|
+
domains, contexts, _, _ = graph.index(data)
|
|
406
|
+
multi_context_domain_ids = [domain["id"] for domain in data["domains"] if not domain["single"]]
|
|
407
|
+
pages = cfg["pages"]
|
|
408
|
+
if pages == "all":
|
|
409
|
+
return multi_context_domain_ids + [context["id"] for context in data["contexts"]]
|
|
410
|
+
if pages == "domains":
|
|
411
|
+
return [domain["id"] for domain in data["domains"]]
|
|
412
|
+
if pages == "contexts":
|
|
413
|
+
return [context["id"] for context in data["contexts"]]
|
|
414
|
+
return list(pages or [])
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def views(data, cfg):
|
|
418
|
+
"""All views to generate: named views first, then one page per item."""
|
|
419
|
+
domains, _, _, names = graph.index(data)
|
|
420
|
+
all_views = [{**cfg["defaults"], **view} for view in cfg["views"]]
|
|
421
|
+
for item_id in page_items(data, cfg):
|
|
422
|
+
is_domain = item_id in domains and not domains[item_id]["single"]
|
|
423
|
+
title = f"{names[item_id]} (domain)" if is_domain else names[item_id]
|
|
424
|
+
all_views.append({**cfg["defaults"], "id": item_id, "title": title, "focus": item_id, "page": True})
|
|
425
|
+
return all_views
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def check(data, cfg):
|
|
429
|
+
errors = []
|
|
430
|
+
_, _, _, names = graph.index(data)
|
|
431
|
+
pages = cfg["pages"]
|
|
432
|
+
if not (pages in ("all", "domains", "contexts") or isinstance(pages, list)):
|
|
433
|
+
errors.append("mermaid.pages must be all, domains, contexts, or a list of ids")
|
|
434
|
+
elif isinstance(pages, list):
|
|
435
|
+
errors += [f"mermaid.pages: unknown id '{item_id}'" for item_id in pages if item_id not in names]
|
|
436
|
+
seen = set()
|
|
437
|
+
focusable = set(names) | {cluster["id"] for cluster in data["clusters"]}
|
|
438
|
+
for view in views(data, cfg) if not errors else []:
|
|
439
|
+
if view["id"] in seen:
|
|
440
|
+
errors.append(f"mermaid view id '{view['id']}' is used twice (pages use the domain or context id)")
|
|
441
|
+
seen.add(view["id"])
|
|
442
|
+
if view.get("focus") and view["focus"] not in focusable:
|
|
443
|
+
errors.append(f"mermaid view '{view['id']}': unknown focus '{view['focus']}'")
|
|
444
|
+
container_ids = ({domain["id"] for domain in data["domains"] if not domain["single"]}
|
|
445
|
+
| {cluster["id"] for cluster in data["clusters"]})
|
|
446
|
+
for where, view in [("defaults", cfg["defaults"]), *((f"views.{view['id']}", view) for view in cfg["views"])]:
|
|
447
|
+
if isinstance(view.get("display"), dict):
|
|
448
|
+
errors += [f"mermaid.{where}.display: unknown container '{item_id}'" for item_id in view["display"] if item_id not in container_ids]
|
|
449
|
+
errors += [f"mermaid.{where}.hide: unknown id '{item_id}'" for item_id in (view.get("hide") or [])
|
|
450
|
+
if item_id not in names and item_id not in {cluster["id"] for cluster in data["clusters"]}]
|
|
451
|
+
return errors
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
PAGE = """<!doctype html>
|
|
455
|
+
<html lang="en">
|
|
456
|
+
<head>
|
|
457
|
+
<meta charset="utf-8">
|
|
458
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
459
|
+
<title>{title} - Context Map</title>
|
|
460
|
+
<style>
|
|
461
|
+
body {{ margin: 0; padding: 16px 24px; font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; color: #1a1a1a; background: #fff; }}
|
|
462
|
+
a {{ color: #305bab; text-decoration: none; }}
|
|
463
|
+
a:hover {{ text-decoration: underline; }}
|
|
464
|
+
nav {{ display: flex; gap: 16px; font-size: 14px; }}
|
|
465
|
+
h1 {{ font-size: 24px; margin: 12px 0 4px; }}
|
|
466
|
+
h3 {{ margin-bottom: 4px; }}
|
|
467
|
+
.hint {{ color: #595959; margin: 0 0 16px; }}
|
|
468
|
+
#diagram {{ overflow: auto; border: 1px solid #e7e7e7; border-radius: 8px; padding: 16px; }}
|
|
469
|
+
#diagram svg {{ max-width: 100%; height: auto; }}
|
|
470
|
+
#diagram a, #diagram a *, #diagram .clickable, #diagram .clickable * {{ cursor: pointer; }}
|
|
471
|
+
ul {{ padding-left: 18px; margin-top: 4px; }}
|
|
472
|
+
.cols {{ display: flex; flex-wrap: wrap; gap: 8px 48px; }}
|
|
473
|
+
details {{ margin-top: 16px; }}
|
|
474
|
+
pre {{ background: #f7f7f7; padding: 12px; overflow: auto; }}
|
|
475
|
+
</style>
|
|
476
|
+
</head>
|
|
477
|
+
<body>
|
|
478
|
+
<nav><a href="index.html">All diagrams</a><a href="../{interactive}">Interactive view</a></nav>
|
|
479
|
+
<main>
|
|
480
|
+
<h1>{title}</h1>
|
|
481
|
+
{about}<p class="hint">{description}</p>
|
|
482
|
+
{body}
|
|
483
|
+
</main>
|
|
484
|
+
</body>
|
|
485
|
+
</html>
|
|
486
|
+
"""
|
|
487
|
+
|
|
488
|
+
DIAGRAM = """<div id="diagram">Loading diagram...</div>
|
|
489
|
+
{relations}
|
|
490
|
+
<details><summary>Mermaid source</summary><pre>{escaped}</pre></details>
|
|
491
|
+
<script type="text/plain" id="source">{raw}</script>
|
|
492
|
+
<script type="module">
|
|
493
|
+
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
|
|
494
|
+
{elk}
|
|
495
|
+
mermaid.initialize({{ startOnLoad: false, securityLevel: "loose" }});
|
|
496
|
+
const src = document.getElementById("source").textContent;
|
|
497
|
+
const el = document.getElementById("diagram");
|
|
498
|
+
try {{
|
|
499
|
+
const {{ svg, bindFunctions }} = await mermaid.render("domain-diagram", src);
|
|
500
|
+
el.innerHTML = svg;
|
|
501
|
+
bindFunctions?.(el);
|
|
502
|
+
}} catch (err) {{
|
|
503
|
+
el.textContent = "Could not render this diagram: " + err.message;
|
|
504
|
+
}}
|
|
505
|
+
</script>"""
|
|
506
|
+
|
|
507
|
+
ELK = ('const { default: elkLayouts } = await import("https://cdn.jsdelivr.net/npm/@mermaid-js/layout-elk@0/dist/mermaid-layout-elk.esm.min.mjs");\n'
|
|
508
|
+
" mermaid.registerLayoutLoaders(elkLayouts);")
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def describe(data, view):
|
|
512
|
+
domains, contexts, _, names = graph.index(data)
|
|
513
|
+
reading = "Arrows point to what something depends on. "
|
|
514
|
+
reading += "Upstream is at the top." if view.get("direction", "BT") == "BT" else ""
|
|
515
|
+
if view.get("hide"):
|
|
516
|
+
reading += " Some items are hidden in this view."
|
|
517
|
+
focus = view.get("focus")
|
|
518
|
+
if not focus:
|
|
519
|
+
return reading
|
|
520
|
+
hops = "all hops" if view["depth"] >= 99 else f"{view['depth']} hop" + ("s" if view["depth"] > 1 else "")
|
|
521
|
+
clusters = {cluster["id"]: cluster for cluster in data["clusters"]}
|
|
522
|
+
if focus in clusters:
|
|
523
|
+
return f"{clusters[focus]['name']}: what it holds, and what those touch, {hops}. {reading}"
|
|
524
|
+
what = {"both": "what it depends on and what uses it", "up": "what it depends on", "down": "what uses it"}[view["dir"]]
|
|
525
|
+
where = ""
|
|
526
|
+
if focus in contexts and not domains[contexts[focus]["domain"]]["single"]:
|
|
527
|
+
where = f", in the {names[contexts[focus]['domain']]} domain"
|
|
528
|
+
return f"{names[focus]}{where}: {what}, {hops}. {reading}"
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def item_description(data, view):
|
|
532
|
+
"""The description of the view's focus item, when it has one."""
|
|
533
|
+
focus = view.get("focus")
|
|
534
|
+
if not focus:
|
|
535
|
+
return None
|
|
536
|
+
domains, contexts, _, _ = graph.index(data)
|
|
537
|
+
item = domains.get(focus) or contexts.get(focus)
|
|
538
|
+
return (item or {}).get("description")
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def facts(data, view):
|
|
542
|
+
"""Membership and direct relations for a focused page, as (heading, [ids]) pairs."""
|
|
543
|
+
focus = view.get("focus")
|
|
544
|
+
if not focus:
|
|
545
|
+
return []
|
|
546
|
+
domains, contexts, _, names = graph.index(data)
|
|
547
|
+
clusters = {cluster["id"]: cluster for cluster in data["clusters"]}
|
|
548
|
+
sections = []
|
|
549
|
+
if focus in clusters:
|
|
550
|
+
sections.append(("Members", clusters[focus]["members"]))
|
|
551
|
+
elif focus in domains and not domains[focus]["single"]:
|
|
552
|
+
sections.append(("Bounded contexts", domains[focus]["contexts"]))
|
|
553
|
+
elif focus in contexts and not domains[contexts[focus]["domain"]]["single"]:
|
|
554
|
+
sections.append(("Domain", [contexts[focus]["domain"]]))
|
|
555
|
+
upstreams, downstreams = graph.relations(data, focus)
|
|
556
|
+
sections += [(f"Depends on ({len(upstreams)})", upstreams), (f"Used by ({len(downstreams)})", downstreams)]
|
|
557
|
+
|
|
558
|
+
# Dependencies written against the whole domain apply to this context too, we just don't know how yet.
|
|
559
|
+
if focus in contexts:
|
|
560
|
+
parent = contexts[focus]["domain"]
|
|
561
|
+
if not domains[parent]["single"]:
|
|
562
|
+
name = domains[parent]["name"]
|
|
563
|
+
domain_upstreams = sorted({edge["to"] for edge in data["edges"] if edge["from"] == parent}, key=names.get)
|
|
564
|
+
domain_downstreams = sorted({edge["from"] for edge in data["edges"] if edge["to"] == parent}, key=names.get)
|
|
565
|
+
if domain_upstreams:
|
|
566
|
+
sections.append((f"{name} as a whole depends on ({len(domain_upstreams)})", domain_upstreams))
|
|
567
|
+
if domain_downstreams:
|
|
568
|
+
sections.append((f"{name} as a whole is used by ({len(domain_downstreams)})", domain_downstreams))
|
|
569
|
+
return sections
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def build(data, config, out):
|
|
573
|
+
"""Write one HTML page per view under out/mermaid and one Markdown page under out/markdown."""
|
|
574
|
+
cfg, _ = settings(config)
|
|
575
|
+
_, _, _, names = graph.index(data)
|
|
576
|
+
all_views = views(data, cfg)
|
|
577
|
+
pages = {view["id"] for view in all_views if view.get("page")}
|
|
578
|
+
|
|
579
|
+
html_dir = Path(out) / "mermaid"
|
|
580
|
+
md_dir = Path(out) / "markdown"
|
|
581
|
+
for directory in (html_dir, md_dir):
|
|
582
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
583
|
+
# Drop pages for ids that no longer exist.
|
|
584
|
+
for stale in directory.glob("*.html" if directory == html_dir else "*.md"):
|
|
585
|
+
try:
|
|
586
|
+
stale.unlink()
|
|
587
|
+
except OSError:
|
|
588
|
+
pass
|
|
589
|
+
|
|
590
|
+
html_links = {item_id: f"{item_id}.html" for item_id in pages}
|
|
591
|
+
index_rows = []
|
|
592
|
+
|
|
593
|
+
for view in all_views:
|
|
594
|
+
title = view.get("title", view["id"])
|
|
595
|
+
desc = view.get("description") or describe(data, view)
|
|
596
|
+
about = item_description(data, view)
|
|
597
|
+
interactive = "index.html" + (f"#focus={view['focus']}" if view.get("focus") else "")
|
|
598
|
+
if view["level"] == "domain":
|
|
599
|
+
interactive += ("&" if view.get("focus") else "#") + "level=domain"
|
|
600
|
+
|
|
601
|
+
def html_link(item_id):
|
|
602
|
+
return (f"<a href='{item_id}.html'>{html.escape(names[item_id])}</a>" if item_id in pages
|
|
603
|
+
else html.escape(names[item_id]))
|
|
604
|
+
|
|
605
|
+
cols = "".join(
|
|
606
|
+
f"<div><h3>{html.escape(heading)}</h3>" + ("<ul>" + "".join(f"<li>{html_link(item_id)}</li>" for item_id in item_ids) + "</ul>"
|
|
607
|
+
if item_ids else "<p class='hint'>None</p>") + "</div>"
|
|
608
|
+
for heading, item_ids in facts(data, view))
|
|
609
|
+
source = render(data, cfg, view, links=html_links)
|
|
610
|
+
body = DIAGRAM.format(
|
|
611
|
+
relations=f"<div class='cols'>{cols}</div>" if cols else "",
|
|
612
|
+
escaped=html.escape(source),
|
|
613
|
+
raw=source,
|
|
614
|
+
elk=ELK if uses_elk(cfg) else "",
|
|
615
|
+
)
|
|
616
|
+
(html_dir / f"{view['id']}.html").write_text(PAGE.format(
|
|
617
|
+
title=html.escape(title),
|
|
618
|
+
about=f'<p class="hint">{html.escape(about)}</p>' if about else "",
|
|
619
|
+
description=html.escape(desc), interactive=interactive, body=body))
|
|
620
|
+
|
|
621
|
+
def md_link(item_id):
|
|
622
|
+
return f"[{names[item_id]}]({item_id}.md)" if item_id in pages else names[item_id]
|
|
623
|
+
|
|
624
|
+
md = [f"# {title}", ""]
|
|
625
|
+
if about:
|
|
626
|
+
md += [about, ""]
|
|
627
|
+
md += [desc, "", "```mermaid", render(data, cfg, view, markdown=True).rstrip(), "```", ""]
|
|
628
|
+
for heading, item_ids in facts(data, view):
|
|
629
|
+
md += [f"**{heading}:** " + (", ".join(md_link(item_id) for item_id in item_ids) or "None"), ""]
|
|
630
|
+
(md_dir / f"{view['id']}.md").write_text("\n".join(md))
|
|
631
|
+
|
|
632
|
+
index_rows.append(("Pages" if view.get("page") else "Views", title, view["id"]))
|
|
633
|
+
|
|
634
|
+
sections = []
|
|
635
|
+
readme_md = ["# Domain diagrams", "", "Generated from `context-map.yml` and `context-map.style.yml` by `context-mapper`. Do not edit by hand.", ""]
|
|
636
|
+
for group in ("Views", "Pages"):
|
|
637
|
+
rows = sorted((row_title, row_id) for row_group, row_title, row_id in index_rows if row_group == group)
|
|
638
|
+
if rows:
|
|
639
|
+
sections.append(f"<h2>{group}</h2><ul>" + "".join(
|
|
640
|
+
f"<li><a href='{row_id}.html'>{html.escape(row_title)}</a></li>" for row_title, row_id in rows) + "</ul>")
|
|
641
|
+
readme_md += [f"## {group}", ""] + [f"- [{row_title}]({row_id}.md)" for row_title, row_id in rows] + [""]
|
|
642
|
+
(html_dir / "index.html").write_text(PAGE.format(
|
|
643
|
+
title="All diagrams", about="",
|
|
644
|
+
description="Static Mermaid diagrams generated from the context map.",
|
|
645
|
+
interactive="index.html", body="".join(sections)))
|
|
646
|
+
(md_dir / "README.md").write_text("\n".join(readme_md))
|
|
647
|
+
return len(all_views)
|