context-mapper 0.20.2__tar.gz → 0.22.0__tar.gz

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.
Files changed (35) hide show
  1. context_mapper-0.22.0/.github/workflows/ci.yml +31 -0
  2. context_mapper-0.22.0/.github/workflows/pages.yml +45 -0
  3. context_mapper-0.22.0/.github/workflows/publish.yml +41 -0
  4. context_mapper-0.22.0/.gitignore +7 -0
  5. {context_mapper-0.20.2/src/context_mapper.egg-info → context_mapper-0.22.0}/PKG-INFO +15 -7
  6. {context_mapper-0.20.2 → context_mapper-0.22.0}/README.md +14 -6
  7. context_mapper-0.22.0/docs/screenshot.png +0 -0
  8. context_mapper-0.22.0/example/context-map.style.yml +103 -0
  9. context_mapper-0.22.0/example/context-map.yml +87 -0
  10. {context_mapper-0.20.2 → context_mapper-0.22.0}/pyproject.toml +4 -2
  11. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/build.py +24 -5
  12. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/mermaid.py +15 -1
  13. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/template/app.js +26 -3
  14. context_mapper-0.22.0/src/context_mapper/template/download.js +84 -0
  15. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/template/index.html +17 -0
  16. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/template/style.css +9 -0
  17. {context_mapper-0.20.2 → context_mapper-0.22.0/src/context_mapper.egg-info}/PKG-INFO +15 -7
  18. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper.egg-info/SOURCES.txt +11 -0
  19. context_mapper-0.22.0/src/context_mapper.egg-info/scm_file_list.json +29 -0
  20. context_mapper-0.22.0/src/context_mapper.egg-info/scm_version.json +8 -0
  21. context_mapper-0.22.0/tests/conftest.py +122 -0
  22. {context_mapper-0.20.2 → context_mapper-0.22.0}/tests/test_build.py +57 -2
  23. {context_mapper-0.20.2 → context_mapper-0.22.0}/tests/test_mermaid.py +10 -0
  24. {context_mapper-0.20.2 → context_mapper-0.22.0}/LICENSE +0 -0
  25. {context_mapper-0.20.2 → context_mapper-0.22.0}/setup.cfg +0 -0
  26. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/__init__.py +0 -0
  27. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/__main__.py +0 -0
  28. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/graph.py +0 -0
  29. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper/serve.py +0 -0
  30. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper.egg-info/dependency_links.txt +0 -0
  31. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper.egg-info/entry_points.txt +0 -0
  32. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper.egg-info/requires.txt +0 -0
  33. {context_mapper-0.20.2 → context_mapper-0.22.0}/src/context_mapper.egg-info/top_level.txt +0 -0
  34. {context_mapper-0.20.2 → context_mapper-0.22.0}/tests/test_graph.py +0 -0
  35. {context_mapper-0.20.2 → context_mapper-0.22.0}/tests/test_serve.py +0 -0
@@ -0,0 +1,31 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ build:
10
+ # ubuntu-24.04: 26.04 runners no longer offer Python 3.9, which CI still tests.
11
+ runs-on: ubuntu-24.04
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.9", "3.13"]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - name: Install
22
+ run: pip install -e ".[dev]"
23
+ - name: Lint
24
+ run: ruff check .
25
+ - name: Test
26
+ run: pytest
27
+ - name: Build the example
28
+ run: |
29
+ context-mapper
30
+ test -f public/index.html
31
+ working-directory: example
@@ -0,0 +1,45 @@
1
+ name: Pages
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+ pages: write
11
+ id-token: write
12
+
13
+ concurrency:
14
+ group: pages
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ build:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+ - uses: actions/setup-python@v5
23
+ with:
24
+ python-version: "3.13"
25
+ - name: Install
26
+ run: pip install .
27
+ - name: Build the example
28
+ run: |
29
+ context-mapper
30
+ test -f public/index.html
31
+ working-directory: example
32
+ - uses: actions/configure-pages@v5
33
+ - uses: actions/upload-pages-artifact@v3
34
+ with:
35
+ path: example/public
36
+
37
+ deploy:
38
+ needs: build
39
+ runs-on: ubuntu-latest
40
+ environment:
41
+ name: github-pages
42
+ url: ${{ steps.deployment.outputs.page_url }}
43
+ steps:
44
+ - id: deployment
45
+ uses: actions/deploy-pages@v4
@@ -0,0 +1,41 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ with:
14
+ fetch-depth: 0 # setuptools-scm reads the version from the git tags
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.13"
18
+ - name: Build the package
19
+ run: |
20
+ python -m pip install --upgrade pip build
21
+ python -m build
22
+ - uses: actions/upload-artifact@v4
23
+ with:
24
+ name: dist
25
+ path: dist/
26
+
27
+ publish:
28
+ needs: build
29
+ runs-on: ubuntu-latest
30
+ environment: pypi
31
+ permissions:
32
+ id-token: write # Required for trusted publishing
33
+ steps:
34
+ - uses: actions/download-artifact@v4
35
+ with:
36
+ name: dist
37
+ path: dist/
38
+ - name: Publish to PyPI
39
+ uses: pypa/gh-action-pypi-publish@release/v1
40
+ with:
41
+ print-hash: true
@@ -0,0 +1,7 @@
1
+ public/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .pytest_cache/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: context-mapper
3
- Version: 0.20.2
3
+ Version: 0.22.0
4
4
  Summary: Builds an interactive context map and Mermaid diagrams from a YAML domain model.
5
5
  Author-email: Henrique Moody <henriquemoody@gmail.com>
6
6
  License-Expression: ISC
@@ -48,10 +48,10 @@ The build fails on unknown ids, duplicates, dependency cycles between bounded co
48
48
  Requires Python 3.9+; Mermaid itself is loaded from a CDN when you view a page, so the only build dependency is PyYAML.
49
49
 
50
50
  ```sh
51
- pip install git+https://github.com/henriquemoody/context-mapper.git
51
+ pip install context-mapper
52
52
  ```
53
53
 
54
- Pin a tag (as above) or a branch, so a change here cannot break your build unannounced.
54
+ Pin the version (`context-mapper==<version>`) so a change here cannot break your build unannounced.
55
55
 
56
56
  Run `context-mapper` in a directory that has a `context-map.yml` and a `context-map.style.yml`. The paths are flags:
57
57
 
@@ -109,8 +109,8 @@ At domain level, context dependencies are lifted to their domains and merged, an
109
109
 
110
110
  | Output | What it is |
111
111
  | --- | --- |
112
- | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details. |
113
- | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page. |
112
+ | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details, download the view as a PNG or SVG image. |
113
+ | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page, download the diagram as a PNG or SVG image. |
114
114
  | `<out>/markdown/*.md` | The same diagrams as Markdown. GitLab renders them natively, and they can go to Confluence. |
115
115
 
116
116
  ## Run locally
@@ -143,6 +143,14 @@ context-map:
143
143
 
144
144
  A style also fills in a readable text `color` when you don't set one.
145
145
 
146
+ Links sit in a `links` section of their own: a map from the link's text to where it goes, shown in the header of the interactive page in the order written. A repository — on GitHub, GitLab or anywhere else — an issue tracker, a document, anything. Without the section, the header shows none.
147
+
148
+ ```yaml
149
+ links:
150
+ Repository: https://github.com/henriquemoody/context-mapper
151
+ Issues: https://github.com/henriquemoody/context-mapper/issues
152
+ ```
153
+
146
154
  The rest lives in the `mermaid` section. Every style in it is a map of the same Mermaid attributes as above, so `focus_style`, `domain_style` and `edge_styles` read like `types`, `clusters` and `context-map`. It styles the interactive page (`index.html`) and the static pages alike, since both are drawn with Mermaid. The interactive page uses the view `defaults` (such as `display` and `hide`) as its starting state. Unknown keys fail the build, so a typo tells you instead of doing nothing.
147
155
 
148
156
  | Option | Values | What it does |
@@ -185,13 +193,13 @@ A view can also set `id`, `title`, `focus` (a domain, context or cluster id), `d
185
193
 
186
194
  ## Use it in another repository
187
195
 
188
- Keep only the model in your repository and let CI install this tool. Pin a tag so the build is reproducible; when you want a newer version, bump the tag. This GitLab Pages job is all it takes (the GitHub tag tarball works everywhere, and needs no `git` in the image):
196
+ Keep only the model in your repository and let CI install this tool. Pin the version so the build is reproducible; when you want a newer one, bump it. This GitLab Pages job is all it takes:
189
197
 
190
198
  ```yaml
191
199
  pages:
192
200
  image: python:3.12-slim
193
201
  script:
194
- - pip install --quiet https://github.com/henriquemoody/context-mapper/archive/refs/tags/v0.20.2.tar.gz
202
+ - pip install --quiet context-mapper==<version>
195
203
  - context-mapper
196
204
  artifacts:
197
205
  paths:
@@ -19,10 +19,10 @@ The build fails on unknown ids, duplicates, dependency cycles between bounded co
19
19
  Requires Python 3.9+; Mermaid itself is loaded from a CDN when you view a page, so the only build dependency is PyYAML.
20
20
 
21
21
  ```sh
22
- pip install git+https://github.com/henriquemoody/context-mapper.git
22
+ pip install context-mapper
23
23
  ```
24
24
 
25
- Pin a tag (as above) or a branch, so a change here cannot break your build unannounced.
25
+ Pin the version (`context-mapper==<version>`) so a change here cannot break your build unannounced.
26
26
 
27
27
  Run `context-mapper` in a directory that has a `context-map.yml` and a `context-map.style.yml`. The paths are flags:
28
28
 
@@ -80,8 +80,8 @@ At domain level, context dependencies are lifted to their domains and merged, an
80
80
 
81
81
  | Output | What it is |
82
82
  | --- | --- |
83
- | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details. |
84
- | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page. |
83
+ | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details, download the view as a PNG or SVG image. |
84
+ | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page, download the diagram as a PNG or SVG image. |
85
85
  | `<out>/markdown/*.md` | The same diagrams as Markdown. GitLab renders them natively, and they can go to Confluence. |
86
86
 
87
87
  ## Run locally
@@ -114,6 +114,14 @@ context-map:
114
114
 
115
115
  A style also fills in a readable text `color` when you don't set one.
116
116
 
117
+ Links sit in a `links` section of their own: a map from the link's text to where it goes, shown in the header of the interactive page in the order written. A repository — on GitHub, GitLab or anywhere else — an issue tracker, a document, anything. Without the section, the header shows none.
118
+
119
+ ```yaml
120
+ links:
121
+ Repository: https://github.com/henriquemoody/context-mapper
122
+ Issues: https://github.com/henriquemoody/context-mapper/issues
123
+ ```
124
+
117
125
  The rest lives in the `mermaid` section. Every style in it is a map of the same Mermaid attributes as above, so `focus_style`, `domain_style` and `edge_styles` read like `types`, `clusters` and `context-map`. It styles the interactive page (`index.html`) and the static pages alike, since both are drawn with Mermaid. The interactive page uses the view `defaults` (such as `display` and `hide`) as its starting state. Unknown keys fail the build, so a typo tells you instead of doing nothing.
118
126
 
119
127
  | Option | Values | What it does |
@@ -156,13 +164,13 @@ A view can also set `id`, `title`, `focus` (a domain, context or cluster id), `d
156
164
 
157
165
  ## Use it in another repository
158
166
 
159
- Keep only the model in your repository and let CI install this tool. Pin a tag so the build is reproducible; when you want a newer version, bump the tag. This GitLab Pages job is all it takes (the GitHub tag tarball works everywhere, and needs no `git` in the image):
167
+ Keep only the model in your repository and let CI install this tool. Pin the version so the build is reproducible; when you want a newer one, bump it. This GitLab Pages job is all it takes:
160
168
 
161
169
  ```yaml
162
170
  pages:
163
171
  image: python:3.12-slim
164
172
  script:
165
- - pip install --quiet https://github.com/henriquemoody/context-mapper/archive/refs/tags/v0.20.2.tar.gz
173
+ - pip install --quiet context-mapper==<version>
166
174
  - context-mapper
167
175
  artifacts:
168
176
  paths:
@@ -0,0 +1,103 @@
1
+ # How the context map looks. What it describes lives in context-map.yml.
2
+ #
3
+ # Output: public/index.html, public/mermaid/*.html and public/markdown/*.md.
4
+ # Unknown keys fail the build.
5
+
6
+ # How the map looks. The sections mirror context-map.yml — `types`, `clusters`,
7
+ # `context-map` — keyed by the same ids. The keys are Mermaid's own classDef
8
+ # attributes (fill, stroke, stroke-width, ...), plus `defaultDisplay` on any
9
+ # entry, saying how it first renders: expanded, collapsed, contents or hidden
10
+ # for a domain or a cluster; a bounded context — one box with nothing inside —
11
+ # only expanded or hidden. The build checks them all, so a typo fails the
12
+ # build instead of drawing nothing.
13
+ types:
14
+ core: { fill: "#dedaff", stroke: "#6631d7" }
15
+ supporting: { fill: "#c6dcff", stroke: "#305bab" }
16
+ generic: { fill: "#adf0c7", stroke: "#067429" }
17
+
18
+ clusters:
19
+ foundations: { fill: "#eaf9ef", stroke: "#067429", stroke-dasharray: "4 3", defaultDisplay: collapsed }
20
+
21
+ # An entry takes any attributes: a domain's overrides `mermaid.domain_style`
22
+ # below and, drawn as one box, its type colors; a bounded context's styles its
23
+ # own box. Any entry also takes `defaultDisplay`, saying how it first renders —
24
+ # a bounded context, which holds nothing inside, only expanded or hidden.
25
+ context-map:
26
+ catalog: { fill: "#f7f7ff", stroke: "#6631d7" }
27
+
28
+ # Links the interactive page shows in its header, in this order: the link's
29
+ # text, then where it goes — a repository, an issue tracker, anything.
30
+ # Without this section the header shows no links.
31
+ links:
32
+ Repository: https://github.com/henriquemoody/context-mapper
33
+ Issues: https://github.com/henriquemoody/context-mapper/issues
34
+
35
+ mermaid:
36
+ direction: BT # BT: upstream on top. Also TB, LR, RL.
37
+ theme: base # base, default, neutral, dark, forest
38
+ layout: elk # dagre (default) or elk
39
+ look: handDrawn # classic or handDrawn
40
+ curve: step # basis, linear, step, stepBefore, stepAfter, ...
41
+ theme_variables: # https://mermaid.js.org/config/theming.html
42
+ fontFamily: "system-ui, sans-serif"
43
+ fontSize: "14px"
44
+ lineColor: "#313131"
45
+ # Anything else Mermaid accepts: https://mermaid.js.org/config/schema-docs/config.html
46
+ config:
47
+ elk:
48
+ mergeEdges: false
49
+ nodePlacementStrategy: BRANDES_KOEPF
50
+ # Merged over the above for public/markdown/*.md only. GitLab's built-in Mermaid has no ELK.
51
+ markdown_config:
52
+ layout: dagre
53
+
54
+ # Defaults for every view. Each view below can override any of these.
55
+ defaults:
56
+ level: context # context (bounded contexts inside domain boxes) or domain (one box per domain)
57
+ depth: 1 # Hops out from the focus. 99 means everything.
58
+ dir: both # both, up (depends on), down (used by)
59
+ display: {} # How containers first render: expanded, collapsed, contents, hidden — or a map by id
60
+ hide: [] # Ids this view never draws: a domain or cluster (with what's inside), or a bounded context
61
+ child_labels: true # A collapsed container names what it holds, in the box and on each arrow
62
+ group_by_type: false # Wrap Core, Supporting, Generic in their own boxes
63
+
64
+ # Styles are maps of Mermaid attributes here too, like the ones above.
65
+ focus_style: # The focused item
66
+ stroke-width: "4px"
67
+ font-weight: bold
68
+ domain_style: # The box around a domain's contexts
69
+ fill: "#ffffff"
70
+ stroke: "#b0b0b0"
71
+ edge_styles:
72
+ solid:
73
+ stroke: "#313131"
74
+ stroke-width: "1.5px"
75
+ dotted:
76
+ stroke: "#313131"
77
+ stroke-width: "1.5px"
78
+ stroke-dasharray: "3 3"
79
+
80
+ # Which pages to generate, each focused on one item: all, domains, contexts, or a list of ids.
81
+ pages: all
82
+
83
+ # Extra named views. Use any key from defaults, plus id, title, focus, description and direction.
84
+ views:
85
+ - id: overview
86
+ title: Domains
87
+ level: domain
88
+ depth: 99
89
+ hide: [crm] # the whole system, without CRM
90
+ - id: foundations-detail
91
+ title: Shared Foundations in detail
92
+ focus: foundations
93
+ depth: 1
94
+ - id: checkout-upstreams
95
+ title: Everything Checkout depends on
96
+ focus: checkout
97
+ dir: up
98
+ depth: 99
99
+ - id: orders-detail
100
+ title: Orders, without Fulfillment
101
+ focus: orders
102
+ depth: 99
103
+ hide: [fulfillment] # a domain view can hide one of its bounded contexts
@@ -0,0 +1,87 @@
1
+ # Source of truth for the context map.
2
+ #
3
+ # Three kinds of thing, in three sections:
4
+ # - `types` is the role vocabulary of the model: a domain or bounded context
5
+ # has one, and it colors the box.
6
+ # - `clusters` names a set of domains or contexts treated together; its members
7
+ # point at it with `cluster:`.
8
+ # - `context-map` maps each id to what it is, so nothing can be described
9
+ # twice: an entry with a `domain:` key is a bounded context of that domain,
10
+ # and any other entry is a domain — one no context points at is a single
11
+ # bounded context. Every entry can carry `downstreams`, who depends on it and
12
+ # why, and the interactive page shows the reason as a tooltip when you hover
13
+ # over that arrow:
14
+ #
15
+ # billing:
16
+ # downstreams:
17
+ # packaging: Charges for Packages and Subscriptions
18
+ # pro-account: Charges the monthly subscription
19
+ #
20
+ # Every entry can also carry a `description`: the interactive page shows it as
21
+ # a tooltip when you hover over its box, and the item's page shows it in text.
22
+ #
23
+ # A dependency can point at a domain when we don't know yet which of its
24
+ # contexts is involved. Move it to the right context once we know.
25
+ #
26
+ # How it looks (colors, layout, views) lives in context-map.style.yml.
27
+
28
+ types:
29
+ core: { name: Core }
30
+ supporting: { name: Supporting }
31
+ generic: { name: Generic }
32
+
33
+ # A cluster: its members point at it with `cluster:`.
34
+ clusters:
35
+ foundations: { name: Shared Foundations }
36
+
37
+ # A context takes its domain's `type` unless it sets its own.
38
+ context-map:
39
+ # Shared foundations: used by most domains.
40
+ identity:
41
+ name: Identity
42
+ type: generic
43
+ cluster: foundations
44
+ description: Accounts and logins. Everyone signs in here.
45
+ downstreams:
46
+ checkout: Creates an account for guests who check out.
47
+ crm: # a bare key: depends on it, no comment yet
48
+ payments:
49
+ name: Payments
50
+ type: generic
51
+ cluster: foundations
52
+ downstreams:
53
+ checkout: Charges the payment method and signals whether it went through.
54
+ fulfillment: Captures the payment once the order ships, and refunds returns.
55
+
56
+ catalog:
57
+ name: Catalog
58
+ type: core
59
+ description: Everything that can be bought, with its prices and availability.
60
+ downstreams: # the whole catalog: we don't know which context yet
61
+ checkout:
62
+ comment: Reads prices and availability at checkout time.
63
+ style: dotted # a styled edge: colors live in context-map.style.yml
64
+ browsing:
65
+ name: Browsing
66
+ domain: catalog
67
+ search:
68
+ name: Search
69
+ domain: catalog
70
+
71
+ orders:
72
+ name: Orders
73
+ type: core
74
+ downstreams: # a dependency pointing at a whole domain
75
+ crm: Reads orders to sync them into the ticket system.
76
+ checkout:
77
+ name: Checkout
78
+ domain: orders
79
+ description: Takes a cart and turns it into a paid order.
80
+ fulfillment:
81
+ name: Fulfillment
82
+ domain: orders
83
+ type: supporting # a context can override its domain's type
84
+
85
+ crm:
86
+ name: CRM
87
+ type: supporting
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["setuptools>=77"]
2
+ requires = ["setuptools>=77", "setuptools-scm>=8"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "context-mapper"
7
- version = "0.20.2"
7
+ dynamic = ["version"]
8
8
  description = "Builds an interactive context map and Mermaid diagrams from a YAML domain model."
9
9
  readme = "README.md"
10
10
  license = "ISC"
@@ -44,6 +44,8 @@ Issues = "https://github.com/henriquemoody/context-mapper/issues"
44
44
  [project.scripts]
45
45
  context-mapper = "context_mapper.build:main"
46
46
 
47
+ [tool.setuptools_scm]
48
+
47
49
  [tool.setuptools.packages.find]
48
50
  where = ["src"]
49
51
 
@@ -18,7 +18,7 @@ import yaml
18
18
  from . import graph, mermaid
19
19
 
20
20
  TEMPLATE_DIR = Path(__file__).parent / "template"
21
- DIAGRAMS_KEYS = {"types", "clusters", "context-map", "mermaid"}
21
+ DIAGRAMS_KEYS = {"types", "clusters", "context-map", "mermaid", "links"}
22
22
 
23
23
 
24
24
  class StrictLoader(yaml.SafeLoader):
@@ -48,6 +48,21 @@ def read_yaml(path):
48
48
  sys.exit(f"error: {path}: {err}")
49
49
 
50
50
 
51
+ def check_links(links, errors):
52
+ """The style file's `links`: a map from a link's label to its URL, shown in the
53
+ header of the interactive page — a repository, an issue tracker, anything."""
54
+ if links is None:
55
+ return {}
56
+ if not isinstance(links, dict):
57
+ errors.append("context-map.style.yml: links must be a map from label to URL, "
58
+ "such as `Repository: https://github.com/org/repo`")
59
+ return {}
60
+ for label, url in links.items():
61
+ if not isinstance(url, str) or not url.strip():
62
+ errors.append(f"context-map.style.yml: links.{label}: must be a URL string")
63
+ return links
64
+
65
+
51
66
  def add_input_flags(parser):
52
67
  """The flags shared by the build and the serve commands."""
53
68
  parser.add_argument("--model", type=Path, default=Path("context-map.yml"),
@@ -73,6 +88,7 @@ def load(model_path, diagrams_path):
73
88
  model = read_yaml(model_path)
74
89
  diagrams = read_yaml(diagrams_path) or {}
75
90
  data, errors = graph.normalize(model, diagrams)
91
+ links = check_links(diagrams.get("links"), errors)
76
92
 
77
93
  for key in diagrams:
78
94
  if key not in DIAGRAMS_KEYS:
@@ -96,14 +112,16 @@ def load(model_path, diagrams_path):
96
112
  _, _, _, names = graph.index(data)
97
113
  print("warning: domains depend on each other: " + " -> ".join(names[node] for node in cycle), file=sys.stderr)
98
114
 
99
- return data, diagrams.get("mermaid")
115
+ return data, diagrams.get("mermaid"), links
100
116
 
101
117
 
102
118
  def render_index(payload):
103
119
  """The interactive page: the skeleton with the stylesheet, the script and the model spliced in."""
104
120
  html = (TEMPLATE_DIR / "index.html").read_text()
105
121
  css = (TEMPLATE_DIR / "style.css").read_text().strip()
106
- js = (TEMPLATE_DIR / "app.js").read_text().replace("/*__MODEL__*/null", payload).strip()
122
+ download = (TEMPLATE_DIR / "download.js").read_text().strip()
123
+ js = (TEMPLATE_DIR / "app.js").read_text().replace("/*__MODEL__*/null", payload)
124
+ js = js.replace("/*__DOWNLOAD__*/", download).strip()
107
125
  return html.replace("/*__STYLE__*/", css).replace("/*__SCRIPT__*/", js)
108
126
 
109
127
 
@@ -112,9 +130,10 @@ def build_site(args):
112
130
  for flag, path in (("--model", args.model), ("--diagrams", args.diagrams)):
113
131
  if not path.exists():
114
132
  sys.exit(f"error: {path} not found. Pass {flag} to set the path.")
115
- data, mermaid_section = load(args.model, args.diagrams)
133
+ data, mermaid_section, links = load(args.model, args.diagrams)
116
134
  mermaid_cfg, _ = mermaid.settings(mermaid_section)
117
- payload = json.dumps({**data, "mermaid": mermaid.client_settings(mermaid_cfg)}, ensure_ascii=False).replace("</", "<\\/")
135
+ payload = json.dumps({**data, "mermaid": mermaid.client_settings(mermaid_cfg), "links": links},
136
+ ensure_ascii=False).replace("</", "<\\/")
118
137
  html = render_index(payload)
119
138
  index = args.out / "index.html"
120
139
  args.out.mkdir(parents=True, exist_ok=True)
@@ -6,6 +6,7 @@ there and the README for every option. build.py calls `build(data, config, out)`
6
6
  import html
7
7
  import json
8
8
  import re
9
+ import textwrap
9
10
  from pathlib import Path
10
11
 
11
12
  from . import graph
@@ -451,6 +452,10 @@ def check(data, cfg):
451
452
  return errors
452
453
 
453
454
 
455
+ # The download script is shared with the interactive page: build.py splices it
456
+ # into app.js, here it goes into every static diagram page's script.
457
+ DOWNLOAD_JS = (Path(__file__).parent / "template" / "download.js").read_text().strip()
458
+
454
459
  PAGE = """<!doctype html>
455
460
  <html lang="en">
456
461
  <head>
@@ -485,7 +490,8 @@ PAGE = """<!doctype html>
485
490
  </html>
486
491
  """
487
492
 
488
- DIAGRAM = """<div id="diagram">Loading diagram...</div>
493
+ DIAGRAM = """<p class="hint">Download: <a href="#" data-download="png">PNG</a> · <a href="#" data-download="svg">SVG</a></p>
494
+ <div id="diagram">Loading diagram...</div>
489
495
  {relations}
490
496
  <details><summary>Mermaid source</summary><pre>{escaped}</pre></details>
491
497
  <script type="text/plain" id="source">{raw}</script>
@@ -502,6 +508,12 @@ DIAGRAM = """<div id="diagram">Loading diagram...</div>
502
508
  }} catch (err) {{
503
509
  el.textContent = "Could not render this diagram: " + err.message;
504
510
  }}
511
+ document.querySelectorAll("[data-download]").forEach(a => a.addEventListener("click", ev => {{
512
+ ev.preventDefault();
513
+ const svg = el.querySelector("svg");
514
+ if (svg) downloadDiagram(svg, a.dataset.download, {name});
515
+ }}));
516
+ __DOWNLOAD__
505
517
  </script>"""
506
518
 
507
519
  ELK = ('const { default: elkLayouts } = await import("https://cdn.jsdelivr.net/npm/@mermaid-js/layout-elk@0/dist/mermaid-layout-elk.esm.min.mjs");\n'
@@ -612,7 +624,9 @@ def build(data, config, out):
612
624
  escaped=html.escape(source),
613
625
  raw=source,
614
626
  elk=ELK if uses_elk(cfg) else "",
627
+ name=json.dumps(view["id"]),
615
628
  )
629
+ body = body.replace("__DOWNLOAD__", textwrap.indent(DOWNLOAD_JS, " "))
616
630
  (html_dir / f"{view['id']}.html").write_text(PAGE.format(
617
631
  title=html.escape(title),
618
632
  about=f'<p class="hint">{html.escape(about)}</p>' if about else "",
@@ -114,6 +114,20 @@ const levelSel = $("level"), focusSel = $("focus"), depthSel = $("depth"), dirSe
114
114
  group(`Bounded contexts: ${d.name}`, MODEL.contexts.filter(c => c.domain === d.id && !domainById[c.id])));
115
115
  })();
116
116
 
117
+ // Header links from the style file: every label goes in as text, never as
118
+ // HTML, in the order the file lists them. With nothing to show, the nav
119
+ // leaves the header entirely, so no empty flex child holds a stray gap.
120
+ (function fillLinks() {
121
+ const nav = $("links");
122
+ Object.entries(MODEL.links || {}).forEach(([label, url]) => {
123
+ const a = document.createElement("a");
124
+ a.href = url;
125
+ a.textContent = label;
126
+ nav.appendChild(a);
127
+ });
128
+ if (!nav.childElementCount) nav.remove();
129
+ })();
130
+
117
131
  const DIAGRAM = MODEL.mermaid;
118
132
 
119
133
  // A container first renders as the view says, else as its own `defaultDisplay` says, else expanded.
@@ -556,10 +570,9 @@ const chip = type => { const t = MODEL.types[type]; return `<span class="chip" s
556
570
 
557
571
  function renderInfo(s, visible) {
558
572
  const legend = '<div class="legend">' + Object.keys(MODEL.types).map(chip).join("") + "</div>";
559
- const howTo = `<h3>How to read</h3><p class="hint">An arrow from A to B means A depends on B. Upstream is at the top. The outer boxes are domains, the coloured boxes inside them are bounded contexts. The Show &amp; hide form in the right panel has a control for every domain and cluster: a multi-context domain or a cluster can be expanded (the boxes inside it), collapsed (one box), or hidden — a dashed underline marks a cluster's — and a one-box domain hides with a toggle. Focusing on a domain or a cluster lists what it holds, and each item there can be hidden too. Click a box to focus on it.</p>`;
560
573
  if (!s.focus) {
561
574
  $("info").innerHTML = `<h2>Whole system</h2><p class="hint">${visible.size} items shown. Pick a domain, cluster or bounded context to see only what it touches.</p>
562
- <p><a href="mermaid/index.html">Static diagrams</a></p>${legend}${howTo}`;
575
+ <p><a href="mermaid/index.html">Static diagrams</a></p>${legend}`;
563
576
  return;
564
577
  }
565
578
  const id = s.focus;
@@ -594,7 +607,7 @@ function renderInfo(s, visible) {
594
607
  if (dDowns.length) html += `<h3>${pname} as a whole is used by</h3>${list(dDowns)}`;
595
608
  }
596
609
  }
597
- $("info").innerHTML = html + `<h3>Legend</h3>${legend}${howTo}`;
610
+ $("info").innerHTML = html + `<h3>Legend</h3>${legend}`;
598
611
  }
599
612
 
600
613
  const setHidden = (id, hide) => {
@@ -618,5 +631,15 @@ Object.entries(displaySels).forEach(([id, sel]) => sel.addEventListener("change"
618
631
  $("reset").addEventListener("click", () => { history.replaceState(null, "", location.pathname); readHash(); render(); });
619
632
  window.addEventListener("hashchange", () => { readHash(); render(); });
620
633
 
634
+ // Downloading the diagram as it stands, named after what it shows.
635
+ $("download").addEventListener("click", () => {
636
+ const svg = $("graph").querySelector("svg");
637
+ if (!svg) return; // nothing rendered to download
638
+ const s = state();
639
+ const name = ["context-map", s.focus, s.level === "domain" ? "domain" : null].filter(Boolean).join("-");
640
+ downloadDiagram(svg, $("image").value, name);
641
+ });
642
+
621
643
  readHash();
622
644
  render();
645
+ /*__DOWNLOAD__*/
@@ -0,0 +1,84 @@
1
+ // Downloading the rendered diagram as an image. build.py splices this into
2
+ // app.js for the interactive page; mermaid.py splices it into the script of
3
+ // every static diagram page, so both offer the same export.
4
+
5
+ // The diagram as a standalone SVG: a text the file holds, and the size it
6
+ // opens at. What only makes sense on the page goes out — the wide
7
+ // transparent copies that catch hover on an arrow, the accent arrowheads
8
+ // hover lights up (a hovered arrow points at its copy, so point it back at
9
+ // the original before dropping it), and the links that navigate within the
10
+ // site. A file of its own has none of the page's CSS either: the size comes
11
+ // from the viewBox, in pixels, instead of the stylesheet's width rules.
12
+ function standaloneSvg(svg) {
13
+ const clone = svg.cloneNode(true);
14
+ clone.classList.remove("hovering");
15
+ clone.querySelectorAll(".edge-hit").forEach(n => n.remove());
16
+ clone.querySelectorAll("[id$='-on']").forEach(copy => {
17
+ const original = copy.id.slice(0, -3);
18
+ clone.querySelectorAll("[marker-end]").forEach(el => {
19
+ if (el.getAttribute("marker-end").includes(copy.id))
20
+ el.setAttribute("marker-end", `url(#${original})`);
21
+ });
22
+ copy.remove();
23
+ });
24
+ clone.querySelectorAll("a").forEach(a => {
25
+ a.removeAttribute("href");
26
+ a.removeAttributeNS("http://www.w3.org/1999/xlink", "href");
27
+ });
28
+ const parts = (clone.getAttribute("viewBox") || "").trim().split(/\s+/).map(Number);
29
+ const width = parts.length === 4 ? parts[2] : svg.getBoundingClientRect().width;
30
+ const height = parts.length === 4 ? parts[3] : svg.getBoundingClientRect().height;
31
+ clone.setAttribute("width", Math.round(width));
32
+ clone.setAttribute("height", Math.round(height));
33
+ clone.removeAttribute("style");
34
+ // The page paints the diagram's background; a file of its own needs one of
35
+ // its own, the same color, or a dark slide or a dark-mode README turns it
36
+ // into dark text on a dark page. The viewBox need not start at 0, so the
37
+ // rect covers it, not the corner the axes cross at.
38
+ const background = document.createElementNS("http://www.w3.org/2000/svg", "rect");
39
+ if (parts.length === 4) {
40
+ background.setAttribute("x", parts[0]);
41
+ background.setAttribute("y", parts[1]);
42
+ }
43
+ background.setAttribute("width", "100%");
44
+ background.setAttribute("height", "100%");
45
+ const pageBg = getComputedStyle(document.body).backgroundColor;
46
+ background.setAttribute("fill", pageBg === "rgba(0, 0, 0, 0)" ? "#ffffff" : pageBg);
47
+ clone.insertBefore(background, clone.firstChild);
48
+ return { text: '<?xml version="1.0" encoding="UTF-8"?>\n' + new XMLSerializer().serializeToString(clone),
49
+ width: Math.round(width), height: Math.round(height) };
50
+ }
51
+
52
+ function saveBlob(blob, filename) {
53
+ const a = document.createElement("a");
54
+ a.href = URL.createObjectURL(blob);
55
+ a.download = filename;
56
+ a.click();
57
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
58
+ }
59
+
60
+ // `svg` is the rendered diagram, `format` "png" or "svg", `name` the file
61
+ // name without its extension. The PNG draws the SVG on a canvas at twice
62
+ // its size, on the page's own background, so the image looks like the
63
+ // diagram does on screen.
64
+ function downloadDiagram(svg, format, name) {
65
+ const { text, width, height } = standaloneSvg(svg);
66
+ if (format === "svg") {
67
+ saveBlob(new Blob([text], { type: "image/svg+xml;charset=utf-8" }), name + ".svg");
68
+ return;
69
+ }
70
+ const scale = Math.min(2, 16384 / Math.max(width, height)); // stay under the canvas limit
71
+ const canvas = document.createElement("canvas");
72
+ canvas.width = Math.round(width * scale);
73
+ canvas.height = Math.round(height * scale);
74
+ const img = new Image();
75
+ img.onload = () => {
76
+ const ctx = canvas.getContext("2d");
77
+ const bg = getComputedStyle(document.body).backgroundColor;
78
+ ctx.fillStyle = bg === "rgba(0, 0, 0, 0)" ? "#ffffff" : bg;
79
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
80
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
81
+ canvas.toBlob(blob => blob && saveBlob(blob, name + ".png"), "image/png");
82
+ };
83
+ img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(text);
84
+ }
@@ -11,6 +11,7 @@
11
11
  <body>
12
12
  <header>
13
13
  <h1>Context Map</h1>
14
+ <nav id="links"></nav>
14
15
  <label>Show
15
16
  <select id="level">
16
17
  <option value="context">Bounded contexts</option>
@@ -40,7 +41,23 @@
40
41
  <div id="graph"></div>
41
42
  <aside id="panel">
42
43
  <div id="info"></div>
44
+ <div id="export">
45
+ <h3>Download</h3>
46
+ <div class="row">
47
+ <label>Image
48
+ <select id="image">
49
+ <option value="png">PNG</option>
50
+ <option value="svg">SVG</option>
51
+ </select>
52
+ </label>
53
+ <button id="download">Download</button>
54
+ </div>
55
+ </div>
43
56
  <div id="display"><h3>Show &amp; hide</h3></div>
57
+ <div id="howto">
58
+ <h3>How to read</h3>
59
+ <p class="hint">An arrow from A to B means A depends on B. Upstream is at the top. The outer boxes are domains, the coloured boxes inside them are bounded contexts. The Show &amp; hide form in the right panel has a control for every domain and cluster: a multi-context domain or a cluster can be expanded (the boxes inside it), collapsed (one box), or hidden — a dashed underline marks a cluster's — and a one-box domain hides with a toggle. Focusing on a domain or a cluster lists what it holds, and each item there can be hidden too. Click a box to focus on it. Download saves the diagram you are looking at as a PNG or SVG image.</p>
60
+ </div>
44
61
  </aside>
45
62
  </main>
46
63
  <script type="module">
@@ -6,6 +6,12 @@
6
6
  body { margin: 0; font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; color: var(--ink); background: var(--bg); }
7
7
  header { display: flex; flex-wrap: wrap; gap: 12px 20px; align-items: center; padding: 12px 16px; border-bottom: 1px solid var(--line); }
8
8
  header h1 { font-size: 18px; margin: 0 8px 0 0; }
9
+ /* Page links from the style file: one quiet group beside the title, joined by
10
+ the middle dot the info panel already puts between its links. */
11
+ #links { display: flex; flex-wrap: wrap; gap: 2px 0; align-items: baseline; }
12
+ #links a { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; }
13
+ #links a:hover { text-decoration: underline; }
14
+ #links a + a::before { content: "·"; display: inline-block; margin: 0 8px; color: var(--muted); }
9
15
  label { display: inline-flex; gap: 6px; align-items: center; color: var(--muted); }
10
16
  select, button { font: inherit; padding: 4px 8px; border: 1px solid #b0b0b0; border-radius: 6px; background: #fff; color: var(--ink); }
11
17
  button { cursor: pointer; }
@@ -41,6 +47,9 @@ aside a:hover { text-decoration: underline; }
41
47
  #display .cluster { border-bottom: 2px dashed var(--muted); }
42
48
  aside .toggle { color: var(--muted); font-size: 13px; }
43
49
  aside .toggle::before { content: "· "; color: var(--line); }
50
+ /* The panel's download controls: the image format on the left, the button that saves with it on the right. */
51
+ #export .row { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 13px; }
52
+ #export .row select { padding: 2px 6px; }
44
53
  @media (max-width: 800px) {
45
54
  main { grid-template-columns: 1fr; grid-template-rows: 60vh auto; height: auto; }
46
55
  aside { border-left: 0; border-top: 1px solid var(--line); }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: context-mapper
3
- Version: 0.20.2
3
+ Version: 0.22.0
4
4
  Summary: Builds an interactive context map and Mermaid diagrams from a YAML domain model.
5
5
  Author-email: Henrique Moody <henriquemoody@gmail.com>
6
6
  License-Expression: ISC
@@ -48,10 +48,10 @@ The build fails on unknown ids, duplicates, dependency cycles between bounded co
48
48
  Requires Python 3.9+; Mermaid itself is loaded from a CDN when you view a page, so the only build dependency is PyYAML.
49
49
 
50
50
  ```sh
51
- pip install git+https://github.com/henriquemoody/context-mapper.git
51
+ pip install context-mapper
52
52
  ```
53
53
 
54
- Pin a tag (as above) or a branch, so a change here cannot break your build unannounced.
54
+ Pin the version (`context-mapper==<version>`) so a change here cannot break your build unannounced.
55
55
 
56
56
  Run `context-mapper` in a directory that has a `context-map.yml` and a `context-map.style.yml`. The paths are flags:
57
57
 
@@ -109,8 +109,8 @@ At domain level, context dependencies are lifted to their domains and merged, an
109
109
 
110
110
  | Output | What it is |
111
111
  | --- | --- |
112
- | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details. |
113
- | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page. |
112
+ | `<out>/index.html` | Interactive view. Switch between bounded contexts and domains, click anything to focus on it, hide anything from the side panel, hover a box or an arrow for the details, download the view as a PNG or SVG image. |
113
+ | `<out>/mermaid/*.html` | One static Mermaid page per domain, per bounded context, and per named view. Click a box to jump to its page, download the diagram as a PNG or SVG image. |
114
114
  | `<out>/markdown/*.md` | The same diagrams as Markdown. GitLab renders them natively, and they can go to Confluence. |
115
115
 
116
116
  ## Run locally
@@ -143,6 +143,14 @@ context-map:
143
143
 
144
144
  A style also fills in a readable text `color` when you don't set one.
145
145
 
146
+ Links sit in a `links` section of their own: a map from the link's text to where it goes, shown in the header of the interactive page in the order written. A repository — on GitHub, GitLab or anywhere else — an issue tracker, a document, anything. Without the section, the header shows none.
147
+
148
+ ```yaml
149
+ links:
150
+ Repository: https://github.com/henriquemoody/context-mapper
151
+ Issues: https://github.com/henriquemoody/context-mapper/issues
152
+ ```
153
+
146
154
  The rest lives in the `mermaid` section. Every style in it is a map of the same Mermaid attributes as above, so `focus_style`, `domain_style` and `edge_styles` read like `types`, `clusters` and `context-map`. It styles the interactive page (`index.html`) and the static pages alike, since both are drawn with Mermaid. The interactive page uses the view `defaults` (such as `display` and `hide`) as its starting state. Unknown keys fail the build, so a typo tells you instead of doing nothing.
147
155
 
148
156
  | Option | Values | What it does |
@@ -185,13 +193,13 @@ A view can also set `id`, `title`, `focus` (a domain, context or cluster id), `d
185
193
 
186
194
  ## Use it in another repository
187
195
 
188
- Keep only the model in your repository and let CI install this tool. Pin a tag so the build is reproducible; when you want a newer version, bump the tag. This GitLab Pages job is all it takes (the GitHub tag tarball works everywhere, and needs no `git` in the image):
196
+ Keep only the model in your repository and let CI install this tool. Pin the version so the build is reproducible; when you want a newer one, bump it. This GitLab Pages job is all it takes:
189
197
 
190
198
  ```yaml
191
199
  pages:
192
200
  image: python:3.12-slim
193
201
  script:
194
- - pip install --quiet https://github.com/henriquemoody/context-mapper/archive/refs/tags/v0.20.2.tar.gz
202
+ - pip install --quiet context-mapper==<version>
195
203
  - context-mapper
196
204
  artifacts:
197
205
  paths:
@@ -1,6 +1,13 @@
1
+ .gitignore
1
2
  LICENSE
2
3
  README.md
3
4
  pyproject.toml
5
+ .github/workflows/ci.yml
6
+ .github/workflows/pages.yml
7
+ .github/workflows/publish.yml
8
+ docs/screenshot.png
9
+ example/context-map.style.yml
10
+ example/context-map.yml
4
11
  src/context_mapper/__init__.py
5
12
  src/context_mapper/__main__.py
6
13
  src/context_mapper/build.py
@@ -12,10 +19,14 @@ src/context_mapper.egg-info/SOURCES.txt
12
19
  src/context_mapper.egg-info/dependency_links.txt
13
20
  src/context_mapper.egg-info/entry_points.txt
14
21
  src/context_mapper.egg-info/requires.txt
22
+ src/context_mapper.egg-info/scm_file_list.json
23
+ src/context_mapper.egg-info/scm_version.json
15
24
  src/context_mapper.egg-info/top_level.txt
16
25
  src/context_mapper/template/app.js
26
+ src/context_mapper/template/download.js
17
27
  src/context_mapper/template/index.html
18
28
  src/context_mapper/template/style.css
29
+ tests/conftest.py
19
30
  tests/test_build.py
20
31
  tests/test_graph.py
21
32
  tests/test_mermaid.py
@@ -0,0 +1,29 @@
1
+ {
2
+ "files": [
3
+ ".github/workflows/ci.yml",
4
+ ".github/workflows/pages.yml",
5
+ ".github/workflows/publish.yml",
6
+ ".gitignore",
7
+ "LICENSE",
8
+ "README.md",
9
+ "docs/screenshot.png",
10
+ "example/context-map.style.yml",
11
+ "example/context-map.yml",
12
+ "pyproject.toml",
13
+ "src/context_mapper/__init__.py",
14
+ "src/context_mapper/__main__.py",
15
+ "src/context_mapper/build.py",
16
+ "src/context_mapper/graph.py",
17
+ "src/context_mapper/mermaid.py",
18
+ "src/context_mapper/serve.py",
19
+ "src/context_mapper/template/app.js",
20
+ "src/context_mapper/template/download.js",
21
+ "src/context_mapper/template/index.html",
22
+ "src/context_mapper/template/style.css",
23
+ "tests/conftest.py",
24
+ "tests/test_build.py",
25
+ "tests/test_graph.py",
26
+ "tests/test_mermaid.py",
27
+ "tests/test_serve.py"
28
+ ]
29
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.22.0",
3
+ "distance": 0,
4
+ "node": "g8bd3abf42e6c18f94ff586ce2951a648887d83f7",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-11-18"
8
+ }
@@ -0,0 +1,122 @@
1
+ """Shared fixtures for the context-mapper test suite.
2
+
3
+ The files under `example/` are read as fixtures and never modified. The inline
4
+ model below is a deliberately small map used by the unit tests: two domains
5
+ holding two bounded contexts each, one single domain, and one cluster.
6
+ """
7
+ import copy
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+ import yaml
12
+
13
+ from context_mapper import graph, mermaid
14
+
15
+ ROOT = Path(__file__).resolve().parent.parent
16
+
17
+ EXAMPLE_MODEL = ROOT / "example" / "context-map.yml"
18
+ EXAMPLE_STYLE = ROOT / "example" / "context-map.style.yml"
19
+
20
+ # A small map: `core` (clustered, two contexts), `web` (two contexts) and
21
+ # `solo` (a domain nobody points at, so a single bounded context).
22
+ TINY_MODEL = {
23
+ "types": {
24
+ "core": {"name": "Core"},
25
+ "aux": {"name": "Aux"},
26
+ },
27
+ "clusters": {
28
+ "base": {"name": "Base"},
29
+ },
30
+ "context-map": {
31
+ "core": {"name": "Core", "type": "core", "cluster": "base"},
32
+ "web": {"name": "Web", "type": "aux"},
33
+ "core_lib": {
34
+ "name": "Core Lib",
35
+ "domain": "core",
36
+ "type": "core",
37
+ "downstreams": {"core_db": "Lib reads the db."},
38
+ },
39
+ "core_db": {"name": "Core DB", "domain": "core", "type": "core"},
40
+ "web_ui": {
41
+ "name": "Web UI",
42
+ "domain": "web",
43
+ "type": "aux",
44
+ "downstreams": {"core_lib": "UI reads the lib."},
45
+ },
46
+ "web_api": {
47
+ "name": "Web API",
48
+ "domain": "web",
49
+ "type": "aux",
50
+ "downstreams": {
51
+ "core_db": {"comment": "API reads the db.", "style": "dotted"},
52
+ },
53
+ },
54
+ "solo": {"name": "Solo", "type": "aux"},
55
+ },
56
+ }
57
+
58
+ TINY_STYLE = {
59
+ "types": {
60
+ "core": {"fill": "#dedaff", "stroke": "#6631d7"},
61
+ "aux": {"fill": "#adf0c7", "stroke": "#067429"},
62
+ },
63
+ "clusters": {
64
+ "base": {"fill": "#eaf9ef", "stroke": "#067429"},
65
+ },
66
+ }
67
+
68
+
69
+ @pytest.fixture
70
+ def find_view():
71
+ """Find a view by id in a list of views."""
72
+
73
+ def _find(views, view_id):
74
+ for view in views:
75
+ if view["id"] == view_id:
76
+ return view
77
+ raise AssertionError(f"no view {view_id!r} in {[v['id'] for v in views]}")
78
+
79
+ return _find
80
+
81
+
82
+ @pytest.fixture
83
+ def example_model():
84
+ return yaml.safe_load(EXAMPLE_MODEL.read_text())
85
+
86
+
87
+ @pytest.fixture
88
+ def example_style():
89
+ return yaml.safe_load(EXAMPLE_STYLE.read_text())
90
+
91
+
92
+ @pytest.fixture
93
+ def example_data(example_model, example_style):
94
+ """The example model, normalized with the example style."""
95
+ data, errors = graph.normalize(example_model, example_style)
96
+ assert errors == []
97
+ return data
98
+
99
+
100
+ @pytest.fixture
101
+ def example_cfg(example_style):
102
+ """The example style's mermaid section, filled in with the defaults."""
103
+ cfg, errors = mermaid.settings(example_style["mermaid"])
104
+ assert errors == []
105
+ return cfg
106
+
107
+
108
+ @pytest.fixture
109
+ def tiny_model():
110
+ return copy.deepcopy(TINY_MODEL)
111
+
112
+
113
+ @pytest.fixture
114
+ def tiny_style():
115
+ return copy.deepcopy(TINY_STYLE)
116
+
117
+
118
+ @pytest.fixture
119
+ def tiny_data(tiny_model, tiny_style):
120
+ data, errors = graph.normalize(tiny_model, tiny_style)
121
+ assert errors == []
122
+ return data
@@ -4,10 +4,20 @@ import sys
4
4
  from pathlib import Path
5
5
 
6
6
  import pytest
7
+ import yaml
7
8
  from conftest import EXAMPLE_MODEL, EXAMPLE_STYLE
8
9
 
9
10
  from context_mapper import build
10
11
 
12
+
13
+ def example_style_without_links(tmp_path, extra=""):
14
+ """The example style file with its `links` section taken out, plus `extra` YAML."""
15
+ sections = yaml.safe_load(EXAMPLE_STYLE.read_text())
16
+ sections.pop("links", None)
17
+ style = tmp_path / "style.yml"
18
+ style.write_text(yaml.safe_dump(sections, sort_keys=False) + extra)
19
+ return style
20
+
11
21
  CYCLE_MODEL = """\
12
22
  types:
13
23
  core: { name: Core }
@@ -97,12 +107,37 @@ def test_parse_args_takes_the_flags():
97
107
 
98
108
 
99
109
  def test_load_reads_the_example():
100
- data, mermaid_config = build.load(EXAMPLE_MODEL, EXAMPLE_STYLE)
110
+ data, mermaid_config, links = build.load(EXAMPLE_MODEL, EXAMPLE_STYLE)
101
111
  assert len(data["domains"]) == 5
102
112
  assert len(data["contexts"]) == 7
103
113
  assert len(data["edges"]) == 6
104
114
  assert mermaid_config["direction"] == "BT"
105
115
  assert len(mermaid_config["views"]) == 4
116
+ assert links == {"Repository": "https://github.com/henriquemoody/context-mapper",
117
+ "Issues": "https://github.com/henriquemoody/context-mapper/issues"}
118
+
119
+
120
+ def test_load_reads_the_links_section(tmp_path):
121
+ style = example_style_without_links(tmp_path, "links:\n Repository: https://github.com/org/repo\n"
122
+ " Issue tracker: https://github.com/org/repo/issues\n")
123
+ _, _, links = build.load(EXAMPLE_MODEL, style)
124
+ assert list(links) == ["Repository", "Issue tracker"] # in the order written
125
+ assert links["Repository"] == "https://github.com/org/repo"
126
+ assert links["Issue tracker"] == "https://github.com/org/repo/issues"
127
+
128
+
129
+ def test_load_refuses_links_that_are_not_a_map(tmp_path, capsys):
130
+ style = example_style_without_links(tmp_path, "links:\n - https://github.com/org/repo\n")
131
+ with pytest.raises(SystemExit):
132
+ build.load(EXAMPLE_MODEL, style)
133
+ assert "links must be a map from label to URL" in capsys.readouterr().err
134
+
135
+
136
+ def test_load_refuses_a_link_without_a_url(tmp_path, capsys):
137
+ style = example_style_without_links(tmp_path, "links:\n Repository:\n")
138
+ with pytest.raises(SystemExit):
139
+ build.load(EXAMPLE_MODEL, style)
140
+ assert "links.Repository: must be a URL string" in capsys.readouterr().err
106
141
 
107
142
 
108
143
  def test_load_warns_when_the_domains_depend_on_each_other(tmp_path, capsys):
@@ -110,7 +145,7 @@ def test_load_warns_when_the_domains_depend_on_each_other(tmp_path, capsys):
110
145
  model.write_text(CYCLE_MODEL)
111
146
  style = tmp_path / "style.yml"
112
147
  style.write_text(STYLE)
113
- data, _ = build.load(model, style)
148
+ data, _, _ = build.load(model, style)
114
149
  assert len(data["domains"]) == 2
115
150
  assert "domains depend on each other" in capsys.readouterr().err
116
151
 
@@ -183,6 +218,26 @@ def test_box_tooltips_map_node_ids_back_to_items(tmp_path):
183
218
  assert "descriptionOf" not in text # no lookup by SVG id left
184
219
 
185
220
 
221
+ def test_the_interactive_page_can_download_the_diagram(tmp_path):
222
+ out = tmp_path / "public"
223
+ build.main(["--model", str(EXAMPLE_MODEL), "--diagrams", str(EXAMPLE_STYLE), "--out", str(out)])
224
+ text = (out / "index.html").read_text()
225
+ assert '<select id="image">' in text # PNG or SVG
226
+ assert '<option value="png">PNG</option>' in text
227
+ assert '<option value="svg">SVG</option>' in text
228
+ assert '<button id="download">Download</button>' in text
229
+ assert "function downloadDiagram" in text # the shared export script, spliced in
230
+ assert "/*__DOWNLOAD__*/" not in text # never left behind
231
+
232
+
233
+ def test_main_puts_the_links_in_the_page(tmp_path):
234
+ style = example_style_without_links(tmp_path, "links:\n Repository: https://github.com/org/repo\n")
235
+ out = tmp_path / "public"
236
+ build.main(["--model", str(EXAMPLE_MODEL), "--diagrams", str(style), "--out", str(out)])
237
+ text = (out / "index.html").read_text()
238
+ assert '"links": {"Repository": "https://github.com/org/repo"}' in text
239
+
240
+
186
241
  def test_main_refuses_a_model_file_that_is_not_there(tmp_path):
187
242
  with pytest.raises(SystemExit) as excinfo:
188
243
  build.main([
@@ -529,6 +529,16 @@ def test_build_writes_the_diagram_into_the_page(tmp_path, example_data, example_
529
529
  assert "```mermaid" in markdown
530
530
 
531
531
 
532
+ def test_build_writes_the_download_links_into_the_page(tmp_path, example_data, example_style):
533
+ mermaid.build(example_data, example_style["mermaid"], tmp_path)
534
+ page = (tmp_path / "mermaid" / "overview.html").read_text()
535
+ assert 'data-download="png"' in page
536
+ assert 'data-download="svg"' in page
537
+ assert "function downloadDiagram" in page # the shared export script, spliced in
538
+ assert "__DOWNLOAD__" not in page # never left behind
539
+ assert 'downloadDiagram(svg, a.dataset.download, "overview")' in page
540
+
541
+
532
542
  # --- describe and item_description -------------------------------------------
533
543
 
534
544
 
File without changes