dotdoc 0.1.0rc1__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.
- dotdoc-0.1.0rc1/LICENSE +21 -0
- dotdoc-0.1.0rc1/PKG-INFO +66 -0
- dotdoc-0.1.0rc1/README.md +42 -0
- dotdoc-0.1.0rc1/pyproject.toml +104 -0
- dotdoc-0.1.0rc1/pyproject.toml.orig +109 -0
- dotdoc-0.1.0rc1/src/dotdoc/__init__.py +22 -0
- dotdoc-0.1.0rc1/src/dotdoc/hamilton.py +403 -0
- dotdoc-0.1.0rc1/src/dotdoc/html.py +403 -0
dotdoc-0.1.0rc1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Marsh Rossney
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
dotdoc-0.1.0rc1/PKG-INFO
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dotdoc
|
|
3
|
+
Version: 0.1.0rc1
|
|
4
|
+
Summary: Make Graphviz drawings a navigable part of your documentation: nodes link to their API entries, with previews on hover.
|
|
5
|
+
Keywords: graphviz,documentation,hamilton,mkdocs,zensical
|
|
6
|
+
Author: Joe Marsh Rossney
|
|
7
|
+
Author-email: Joe Marsh Rossney <17361029+jmarshrossney@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
16
|
+
Requires-Dist: graphviz>=0.20
|
|
17
|
+
Requires-Dist: apache-hamilton>=1.90.0 ; extra == 'hamilton'
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Project-URL: Homepage, https://jmarshrossney.github.io/dotdoc
|
|
20
|
+
Project-URL: Repository, https://github.com/jmarshrossney/dotdoc
|
|
21
|
+
Project-URL: Documentation, https://jmarshrossney.github.io/dotdoc
|
|
22
|
+
Provides-Extra: hamilton
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# dotdoc
|
|
26
|
+
|
|
27
|
+
Make Graphviz drawings a navigable part of your documentation: nodes link to their API entries, with previews on hover.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import graphviz
|
|
31
|
+
|
|
32
|
+
from dotdoc import autoref, graph_html
|
|
33
|
+
|
|
34
|
+
drawing = graphviz.Digraph(graph_attr={"rankdir": "LR"}, node_attr={"shape": "box"})
|
|
35
|
+
drawing.node("autoref", URL=autoref("dotdoc.html.autoref"))
|
|
36
|
+
drawing.node("graph_html", URL=autoref("dotdoc.html.graph_html"))
|
|
37
|
+
drawing.edge("autoref", "graph_html")
|
|
38
|
+
|
|
39
|
+
print(graph_html(drawing))
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
<picture>
|
|
43
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/jmarshrossney/dotdoc/main/.github/assets/example-dark.svg">
|
|
44
|
+
<img alt="A drawing of two boxes, autoref and graph_html, joined by an arrow" src="https://raw.githubusercontent.com/jmarshrossney/dotdoc/main/.github/assets/example-light.svg">
|
|
45
|
+
</picture>
|
|
46
|
+
|
|
47
|
+
In the [documentation](https://jmarshrossney.github.io/dotdoc), each node's name links to its API entry, with a preview on hover.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
uv add dotdoc
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
or
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pip install dotdoc
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Rendering needs Graphviz's `dot` program, from your system's package manager.
|
|
62
|
+
For Apache Hamilton DAGs, see [Hamilton](https://jmarshrossney.github.io/dotdoc/hamilton.html).
|
|
63
|
+
|
|
64
|
+
## Development
|
|
65
|
+
|
|
66
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# dotdoc
|
|
2
|
+
|
|
3
|
+
Make Graphviz drawings a navigable part of your documentation: nodes link to their API entries, with previews on hover.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import graphviz
|
|
7
|
+
|
|
8
|
+
from dotdoc import autoref, graph_html
|
|
9
|
+
|
|
10
|
+
drawing = graphviz.Digraph(graph_attr={"rankdir": "LR"}, node_attr={"shape": "box"})
|
|
11
|
+
drawing.node("autoref", URL=autoref("dotdoc.html.autoref"))
|
|
12
|
+
drawing.node("graph_html", URL=autoref("dotdoc.html.graph_html"))
|
|
13
|
+
drawing.edge("autoref", "graph_html")
|
|
14
|
+
|
|
15
|
+
print(graph_html(drawing))
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
<picture>
|
|
19
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/jmarshrossney/dotdoc/main/.github/assets/example-dark.svg">
|
|
20
|
+
<img alt="A drawing of two boxes, autoref and graph_html, joined by an arrow" src="https://raw.githubusercontent.com/jmarshrossney/dotdoc/main/.github/assets/example-light.svg">
|
|
21
|
+
</picture>
|
|
22
|
+
|
|
23
|
+
In the [documentation](https://jmarshrossney.github.io/dotdoc), each node's name links to its API entry, with a preview on hover.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
uv add dotdoc
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
or
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install dotdoc
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Rendering needs Graphviz's `dot` program, from your system's package manager.
|
|
38
|
+
For Apache Hamilton DAGs, see [Hamilton](https://jmarshrossney.github.io/dotdoc/hamilton.html).
|
|
39
|
+
|
|
40
|
+
## Development
|
|
41
|
+
|
|
42
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dotdoc"
|
|
7
|
+
version = "0.1.0rc1"
|
|
8
|
+
description = "Make Graphviz drawings a navigable part of your documentation: nodes link to their API entries, with previews on hover."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.12"
|
|
13
|
+
dependencies = ["graphviz>=0.20"]
|
|
14
|
+
keywords = [
|
|
15
|
+
"graphviz",
|
|
16
|
+
"documentation",
|
|
17
|
+
"hamilton",
|
|
18
|
+
"mkdocs",
|
|
19
|
+
"zensical",
|
|
20
|
+
]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 3 - Alpha",
|
|
23
|
+
"Intended Audience :: Developers",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Programming Language :: Python :: 3.14",
|
|
27
|
+
"Programming Language :: Python :: 3.15",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[[project.authors]]
|
|
31
|
+
name = "Joe Marsh Rossney"
|
|
32
|
+
email = "17361029+jmarshrossney@users.noreply.github.com"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
hamilton = ["apache-hamilton>=1.90.0"]
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://jmarshrossney.github.io/dotdoc"
|
|
39
|
+
Repository = "https://github.com/jmarshrossney/dotdoc"
|
|
40
|
+
Documentation = "https://jmarshrossney.github.io/dotdoc"
|
|
41
|
+
|
|
42
|
+
[dependency-groups]
|
|
43
|
+
dev = [
|
|
44
|
+
"pre-commit>=4.6.1",
|
|
45
|
+
"pyright>=1.1.411",
|
|
46
|
+
"ruff>=0.16.1",
|
|
47
|
+
"rust-just>=1.57.0",
|
|
48
|
+
{ include-group = "docs" },
|
|
49
|
+
{ include-group = "test" },
|
|
50
|
+
]
|
|
51
|
+
docs = [
|
|
52
|
+
"apache-hamilton>=1.90.0",
|
|
53
|
+
"markdown-exec>=1.13.0",
|
|
54
|
+
"mkdocstrings-python>=2.0.5",
|
|
55
|
+
"zensical>=0.0.52",
|
|
56
|
+
]
|
|
57
|
+
test = [
|
|
58
|
+
"apache-hamilton>=1.90.0",
|
|
59
|
+
"coverage>=7.15.2",
|
|
60
|
+
"pytest>=9.1.1",
|
|
61
|
+
"pytest-cov>=7.1.0",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
[tool.pytest]
|
|
65
|
+
testpaths = ["tests"]
|
|
66
|
+
|
|
67
|
+
[tool.pyright]
|
|
68
|
+
venvPath = "."
|
|
69
|
+
venv = ".venv"
|
|
70
|
+
include = [
|
|
71
|
+
"src/",
|
|
72
|
+
"tests/",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
[tool.ruff]
|
|
76
|
+
line-length = 88
|
|
77
|
+
indent-width = 4
|
|
78
|
+
target-version = "py312"
|
|
79
|
+
|
|
80
|
+
[tool.ruff.lint]
|
|
81
|
+
select = [
|
|
82
|
+
"E",
|
|
83
|
+
"D",
|
|
84
|
+
"W",
|
|
85
|
+
"F",
|
|
86
|
+
"UP",
|
|
87
|
+
"B",
|
|
88
|
+
"SIM",
|
|
89
|
+
"RUF",
|
|
90
|
+
"PT",
|
|
91
|
+
"I",
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
[tool.ruff.lint.per-file-ignores]
|
|
95
|
+
"tests/**" = [
|
|
96
|
+
"D",
|
|
97
|
+
"E501",
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
[tool.ruff.lint.pydocstyle]
|
|
101
|
+
convention = "google"
|
|
102
|
+
|
|
103
|
+
[tool.uv]
|
|
104
|
+
exclude-newer = "1 week"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# The whole minor of the uv-pre-commit hook's rev. `just bump` keeps the two in
|
|
2
|
+
# step with the uv you have installed.
|
|
3
|
+
[build-system]
|
|
4
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
5
|
+
build-backend = "uv_build"
|
|
6
|
+
|
|
7
|
+
[project]
|
|
8
|
+
name = "dotdoc"
|
|
9
|
+
version = "0.1.0rc1"
|
|
10
|
+
description = "Make Graphviz drawings a navigable part of your documentation: nodes link to their API entries, with previews on hover."
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "Joe Marsh Rossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
|
|
13
|
+
]
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
license = "MIT"
|
|
16
|
+
license-files = ["LICENSE"]
|
|
17
|
+
requires-python = ">=3.12"
|
|
18
|
+
dependencies = [
|
|
19
|
+
"graphviz>=0.20",
|
|
20
|
+
]
|
|
21
|
+
keywords = ["graphviz", "documentation", "hamilton", "mkdocs", "zensical"]
|
|
22
|
+
classifiers = [
|
|
23
|
+
"Development Status :: 3 - Alpha",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Programming Language :: Python :: 3.14",
|
|
28
|
+
"Programming Language :: Python :: 3.15",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
# Style functions for drawings of Apache Hamilton DAGs; see `dotdoc.hamilton`.
|
|
33
|
+
hamilton = ["apache-hamilton>=1.90.0"]
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://jmarshrossney.github.io/dotdoc"
|
|
37
|
+
Repository = "https://github.com/jmarshrossney/dotdoc"
|
|
38
|
+
Documentation = "https://jmarshrossney.github.io/dotdoc"
|
|
39
|
+
|
|
40
|
+
# These bounds are floors, not pins: `uv sync` already resolves to the newest
|
|
41
|
+
# version each one allows, so raising them changes nothing for anyone. Do not
|
|
42
|
+
# "freshen" them, by hand or by bot. They exist only to stop resolution
|
|
43
|
+
# reaching for something ancient, and `[tool.uv] exclude-newer` below means a
|
|
44
|
+
# floor above the version that existed a week ago fails resolution outright.
|
|
45
|
+
# So these want to be low. Raise one only to reach a feature you need.
|
|
46
|
+
[dependency-groups]
|
|
47
|
+
dev = [
|
|
48
|
+
"pre-commit>=4.6.1",
|
|
49
|
+
"pyright>=1.1.411",
|
|
50
|
+
"ruff>=0.16.1",
|
|
51
|
+
"rust-just>=1.57.0",
|
|
52
|
+
{include-group = "docs"},
|
|
53
|
+
{include-group = "test"},
|
|
54
|
+
]
|
|
55
|
+
docs = [
|
|
56
|
+
"apache-hamilton>=1.90.0",
|
|
57
|
+
"markdown-exec>=1.13.0",
|
|
58
|
+
"mkdocstrings-python>=2.0.5",
|
|
59
|
+
"zensical>=0.0.52",
|
|
60
|
+
]
|
|
61
|
+
test = [
|
|
62
|
+
"apache-hamilton>=1.90.0",
|
|
63
|
+
"coverage>=7.15.2",
|
|
64
|
+
"pytest>=9.1.1",
|
|
65
|
+
"pytest-cov>=7.1.0",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
[tool.pytest]
|
|
69
|
+
testpaths = ["tests"]
|
|
70
|
+
|
|
71
|
+
[tool.pyright]
|
|
72
|
+
venvPath = "."
|
|
73
|
+
venv = ".venv"
|
|
74
|
+
include = ["src/", "tests/"]
|
|
75
|
+
|
|
76
|
+
[tool.ruff]
|
|
77
|
+
line-length = 88
|
|
78
|
+
indent-width = 4
|
|
79
|
+
target-version = "py312"
|
|
80
|
+
|
|
81
|
+
[tool.ruff.lint]
|
|
82
|
+
# Ruff broadened its default rule set in 0.16, so always select explicitly:
|
|
83
|
+
# that way a version bump cannot change which rules apply.
|
|
84
|
+
select = [
|
|
85
|
+
"E", # pycodestyle errors
|
|
86
|
+
"D", # pydocstyle
|
|
87
|
+
"W", # pycodestyle warnings
|
|
88
|
+
"F", # pyflakes
|
|
89
|
+
"UP", # pyupgrade
|
|
90
|
+
"B", # flake8-bugbear
|
|
91
|
+
"SIM", # flake8-simplify
|
|
92
|
+
"RUF", # ruff-specific rules
|
|
93
|
+
"PT", # flake8-pytest-style
|
|
94
|
+
"I", # isort
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
[tool.ruff.lint.per-file-ignores]
|
|
98
|
+
# Exempt tests from docstring requirements.
|
|
99
|
+
"tests/**" = ["D", "E501"]
|
|
100
|
+
|
|
101
|
+
[tool.ruff.lint.pydocstyle]
|
|
102
|
+
convention = "google"
|
|
103
|
+
|
|
104
|
+
[tool.uv]
|
|
105
|
+
# Resolve against the index as it was a week ago, so a same-day release cannot
|
|
106
|
+
# break a fresh `uv sync`. Note the corollary: a lower bound in
|
|
107
|
+
# [dependency-groups] must be at or below the version that existed a week ago,
|
|
108
|
+
# or resolution fails outright.
|
|
109
|
+
exclude-newer = "1 week"
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Make Graphviz drawings a navigable part of your documentation.
|
|
2
|
+
|
|
3
|
+
Give a node a `URL` attribute and render the drawing with `graph_html`: the
|
|
4
|
+
node's name then links to that URL, and themes that preview links on hover,
|
|
5
|
+
such as Zensical and Material for MkDocs, preview its target too. A `URL` made
|
|
6
|
+
by `autoref` names an mkdocstrings identifier instead, and the documentation
|
|
7
|
+
build writes the link, whatever the site's URL style.
|
|
8
|
+
|
|
9
|
+
`dotdoc.hamilton` builds the attributes for drawings of Apache Hamilton DAGs,
|
|
10
|
+
linking each node to the documentation of the function that defines it. It
|
|
11
|
+
needs the `hamilton` extra.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .html import AUTOREF_PREFIX, PREVIEW_OVERLAY, DarkColours, autoref, graph_html
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"AUTOREF_PREFIX",
|
|
18
|
+
"PREVIEW_OVERLAY",
|
|
19
|
+
"DarkColours",
|
|
20
|
+
"autoref",
|
|
21
|
+
"graph_html",
|
|
22
|
+
]
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Style functions for drawings of Apache Hamilton DAGs.
|
|
2
|
+
|
|
3
|
+
Hamilton's `Driver` display methods (`display_all_functions`,
|
|
4
|
+
`display_upstream_of` and the rest) take a single `custom_style_function`,
|
|
5
|
+
called once per node with that node and its class, and returning the node's
|
|
6
|
+
Graphviz attributes, its base class and its legend entry. The functions here
|
|
7
|
+
build style functions that link nodes to their documentation, give them a
|
|
8
|
+
tooltip from their docstring, fill them by a tag or any per-node value, and
|
|
9
|
+
set any attribute by node name; `compose_styles` combines them with each other
|
|
10
|
+
and with your own.
|
|
11
|
+
|
|
12
|
+
Hamilton draws each legend entry with the style of the last node that named
|
|
13
|
+
it, so once nodes are linked, every legend swatch carries some node's link and
|
|
14
|
+
tooltip. `clean_legend` strips them from the drawing Hamilton returns.
|
|
15
|
+
|
|
16
|
+
Needs the `hamilton` extra: `pip install "dotdoc[hamilton]"`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import inspect
|
|
20
|
+
import re
|
|
21
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
22
|
+
from typing import TYPE_CHECKING
|
|
23
|
+
|
|
24
|
+
from hamilton import graph_types
|
|
25
|
+
from hamilton.driver import Driver
|
|
26
|
+
|
|
27
|
+
from .html import autoref
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
import graphviz
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"LinkFunction",
|
|
34
|
+
"StyleFunction",
|
|
35
|
+
"TooltipFunction",
|
|
36
|
+
"api_autoref",
|
|
37
|
+
"attribute_style",
|
|
38
|
+
"clean_legend",
|
|
39
|
+
"compose_styles",
|
|
40
|
+
"fill_by",
|
|
41
|
+
"fill_by_tag",
|
|
42
|
+
"link_style",
|
|
43
|
+
"summary",
|
|
44
|
+
"tooltip_style",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
type StyleFunction = Callable[..., tuple[dict[str, str], str | None, str | None]]
|
|
48
|
+
"""A Hamilton `custom_style_function`.
|
|
49
|
+
|
|
50
|
+
It is called with the keyword arguments `node` (a `HamiltonNode`) and
|
|
51
|
+
`node_class` (a string), and returns `(attributes, base_class, legend_entry)`.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
type LinkFunction = Callable[[graph_types.HamiltonNode, Callable | None], str | None]
|
|
55
|
+
"""Receives a node and the function that defines it, and returns the URL of its
|
|
56
|
+
documentation, or `None` for no link.
|
|
57
|
+
|
|
58
|
+
The function is `None` for inputs, config, and field nodes from
|
|
59
|
+
`@extract_fields`, which share their parent's function.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
type TooltipFunction = Callable[
|
|
63
|
+
[graph_types.HamiltonNode, Callable | None], str | Sequence[str] | None
|
|
64
|
+
]
|
|
65
|
+
"""Receives a node and the function that defines it, and returns its tooltip,
|
|
66
|
+
or `None` for no tooltip.
|
|
67
|
+
|
|
68
|
+
A string is one line; a sequence of strings is one line each. The function is
|
|
69
|
+
`None` for inputs, config, and field nodes from `@extract_fields`, which share
|
|
70
|
+
their parent's function.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def compose_styles(*style_functions: StyleFunction) -> StyleFunction:
|
|
75
|
+
"""Combine Hamilton style functions into one.
|
|
76
|
+
|
|
77
|
+
Hamilton's display methods take a single style function. Each node's
|
|
78
|
+
attributes are merged left to right, so a later function overrides an
|
|
79
|
+
earlier one's. The base class and legend entry come from the last function
|
|
80
|
+
that names a legend entry.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
*style_functions: The style functions to combine, in order.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
A style function to pass to Hamilton as `custom_style_function`.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def composed(
|
|
90
|
+
*, node: graph_types.HamiltonNode, node_class: str
|
|
91
|
+
) -> tuple[dict[str, str], str | None, str | None]:
|
|
92
|
+
style: dict[str, str] = {}
|
|
93
|
+
base: str | None = node_class
|
|
94
|
+
legend: str | None = None
|
|
95
|
+
for function in style_functions:
|
|
96
|
+
attrs, fn_base, fn_legend = function(node=node, node_class=node_class)
|
|
97
|
+
style.update(attrs)
|
|
98
|
+
if fn_legend is not None:
|
|
99
|
+
base, legend = fn_base, fn_legend
|
|
100
|
+
return style, base, legend
|
|
101
|
+
|
|
102
|
+
return composed
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _own_functions(dr: Driver) -> dict[str, Callable]:
|
|
106
|
+
"""Return `node -> function` for the nodes a function itself defines.
|
|
107
|
+
|
|
108
|
+
A field node (one per `@extract_fields` output) shares its originating
|
|
109
|
+
function with the node it depends on, so it is left out; external inputs,
|
|
110
|
+
which Hamilton gives the consuming function as their originating function,
|
|
111
|
+
are left out too.
|
|
112
|
+
"""
|
|
113
|
+
own: dict[str, Callable] = {}
|
|
114
|
+
for n in dr.graph.nodes.values():
|
|
115
|
+
if n.user_defined or not n.originating_functions:
|
|
116
|
+
continue
|
|
117
|
+
fn = n.originating_functions[0]
|
|
118
|
+
if any(
|
|
119
|
+
not dep.user_defined
|
|
120
|
+
and dep.originating_functions
|
|
121
|
+
and dep.originating_functions[0] is fn
|
|
122
|
+
for dep in n.dependencies
|
|
123
|
+
):
|
|
124
|
+
continue
|
|
125
|
+
own[n.name] = fn
|
|
126
|
+
return own
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _node_values[T](
|
|
130
|
+
dr: Driver, value: Callable[[graph_types.HamiltonNode, Callable | None], T]
|
|
131
|
+
) -> dict[str, T]:
|
|
132
|
+
own = _own_functions(dr)
|
|
133
|
+
return {
|
|
134
|
+
name: value(graph_types.HamiltonNode.from_node(n), own.get(name))
|
|
135
|
+
for name, n in dr.graph.nodes.items()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _api_link(node: graph_types.HamiltonNode, function: Callable | None) -> str | None:
|
|
140
|
+
return None if function is None else api_autoref(function)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _summary_tooltip(
|
|
144
|
+
node: graph_types.HamiltonNode, function: Callable | None
|
|
145
|
+
) -> str | None:
|
|
146
|
+
return None if function is None else summary(function)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def attribute_style(attribute: str, values: Mapping[str, str]) -> StyleFunction:
|
|
150
|
+
"""Build a style function that sets one Graphviz attribute by node name.
|
|
151
|
+
|
|
152
|
+
For values computed per node, such as tooltips, fill colours or pen
|
|
153
|
+
widths. A node absent from `values` is left alone, and no node gets a
|
|
154
|
+
legend entry.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
attribute: The name of the Graphviz attribute, such as `"penwidth"`.
|
|
158
|
+
values: Node name to the attribute's value.
|
|
159
|
+
|
|
160
|
+
Returns:
|
|
161
|
+
A style function to pass to Hamilton, alone or through
|
|
162
|
+
`compose_styles`.
|
|
163
|
+
|
|
164
|
+
Examples:
|
|
165
|
+
```python
|
|
166
|
+
widths = {"split": "3"}
|
|
167
|
+
digraph = dr.display_all_functions(
|
|
168
|
+
custom_style_function=attribute_style("penwidth", widths)
|
|
169
|
+
)
|
|
170
|
+
```
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def style(
|
|
174
|
+
*, node: graph_types.HamiltonNode, node_class: str
|
|
175
|
+
) -> tuple[dict[str, str], str | None, str | None]:
|
|
176
|
+
value = values.get(node.name)
|
|
177
|
+
return ({} if value is None else {attribute: value}), node_class, None
|
|
178
|
+
|
|
179
|
+
return style
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def api_autoref(function: Callable) -> str:
|
|
183
|
+
"""Link a function to its mkdocstrings entry, wherever that is in the site.
|
|
184
|
+
|
|
185
|
+
The identifier is the dotted path of the function where it is defined,
|
|
186
|
+
`function.__module__` then `function.__qualname__`, which is where
|
|
187
|
+
mkdocstrings registers it when that module is documented. See
|
|
188
|
+
`dotdoc.html.autoref`.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
function: The function to link to.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
A `URL` for `graph_html` to write as an `<autoref>` element.
|
|
195
|
+
|
|
196
|
+
Examples:
|
|
197
|
+
>>> from dotdoc import graph_html
|
|
198
|
+
>>> api_autoref(graph_html)
|
|
199
|
+
'autoref:dotdoc.html.graph_html'
|
|
200
|
+
"""
|
|
201
|
+
return autoref(f"{function.__module__}.{function.__qualname__}")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def link_style(dr: Driver, link: LinkFunction | None = None) -> StyleFunction:
|
|
205
|
+
"""Build a style function that links nodes to their documentation.
|
|
206
|
+
|
|
207
|
+
Each node gets `URL` set to `link(node, function)`, which
|
|
208
|
+
`dotdoc.html.graph_html` makes the node's name link to.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
dr: The driver whose DAG will be drawn.
|
|
212
|
+
link: Receives a node and the function that defines it, or `None` for
|
|
213
|
+
inputs, config and field nodes from `@extract_fields`, and returns
|
|
214
|
+
its URL, or `None` for no link. The default links each node a
|
|
215
|
+
function defines to the function's mkdocstrings entry, through
|
|
216
|
+
`api_autoref`; a function documented under another path, such as
|
|
217
|
+
where a package re-exports it, needs a link function of its own.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
A style function to pass to Hamilton, alone or through
|
|
221
|
+
`compose_styles`.
|
|
222
|
+
|
|
223
|
+
Examples:
|
|
224
|
+
Link each node to its function's mkdocstrings entry:
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
digraph = dr.display_all_functions(custom_style_function=link_style(dr))
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Or to a page outside the documentation build:
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
def source_url(node, fn):
|
|
234
|
+
if fn is not None:
|
|
235
|
+
return f"https://example.org/source/{fn.__module__}.html"
|
|
236
|
+
|
|
237
|
+
digraph = dr.display_all_functions(
|
|
238
|
+
custom_style_function=link_style(dr, source_url)
|
|
239
|
+
)
|
|
240
|
+
```
|
|
241
|
+
"""
|
|
242
|
+
urls = _node_values(dr, link or _api_link)
|
|
243
|
+
return attribute_style("URL", {k: v for k, v in urls.items() if v is not None})
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def summary(function: Callable) -> str | None:
|
|
247
|
+
"""Return the first paragraph of a function's docstring, as plain text.
|
|
248
|
+
|
|
249
|
+
The paragraph is put on one line and backticks are dropped, since a tooltip
|
|
250
|
+
shows them literally.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
function: The function whose docstring to read.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
The summary, or `None` if the function has no docstring.
|
|
257
|
+
|
|
258
|
+
Examples:
|
|
259
|
+
>>> def f():
|
|
260
|
+
... '''Add one to `x`,
|
|
261
|
+
... then double it.
|
|
262
|
+
...
|
|
263
|
+
... More detail.
|
|
264
|
+
... '''
|
|
265
|
+
>>> summary(f)
|
|
266
|
+
'Add one to x, then double it.'
|
|
267
|
+
"""
|
|
268
|
+
doc = inspect.getdoc(function)
|
|
269
|
+
if not doc:
|
|
270
|
+
return None
|
|
271
|
+
return " ".join(doc.split("\n\n", 1)[0].split()).replace("`", "")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def tooltip_style(dr: Driver, tooltip: TooltipFunction | None = None) -> StyleFunction:
|
|
275
|
+
r"""Build a style function that gives nodes a tooltip.
|
|
276
|
+
|
|
277
|
+
Each node gets `tooltip` set to `tooltip(node, function)`, which a browser
|
|
278
|
+
shows on hovering over the node in SVG output. By default that is the
|
|
279
|
+
first paragraph of the docstring of the function that defines the node.
|
|
280
|
+
Backslashes are escaped, so the text is shown as written rather than read
|
|
281
|
+
as Graphviz escape sequences, and the lines of a sequence are joined with
|
|
282
|
+
Graphviz's `\n` line break.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
dr: The driver whose DAG will be drawn.
|
|
286
|
+
tooltip: Receives a node and the function that defines it, or `None`
|
|
287
|
+
for inputs, config and field nodes from `@extract_fields`, and
|
|
288
|
+
returns its tooltip as a string or a sequence of lines, or `None`
|
|
289
|
+
for no tooltip. The default gives each node a function defines the
|
|
290
|
+
`summary` of that function.
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
A style function to pass to Hamilton, alone or through
|
|
294
|
+
`compose_styles`.
|
|
295
|
+
"""
|
|
296
|
+
tips = _node_values(dr, tooltip or _summary_tooltip)
|
|
297
|
+
return attribute_style(
|
|
298
|
+
"tooltip", {k: _tooltip_text(v) for k, v in tips.items() if v}
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _tooltip_text(lines: str | Sequence[str]) -> str:
|
|
303
|
+
if isinstance(lines, str):
|
|
304
|
+
lines = [lines]
|
|
305
|
+
return "\\n".join(line.replace("\\", "\\\\") for line in lines)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def fill_by(
|
|
309
|
+
value: Callable[[graph_types.HamiltonNode], str | None],
|
|
310
|
+
colours: Mapping[str, str],
|
|
311
|
+
) -> StyleFunction:
|
|
312
|
+
"""Build a style function that fills nodes by a value computed per node.
|
|
313
|
+
|
|
314
|
+
A node whose `value(node)` is a key of `colours` is filled with that colour
|
|
315
|
+
and gets a legend entry named after the value. Other nodes are left alone.
|
|
316
|
+
|
|
317
|
+
Hamilton names each legend entry's Graphviz node after the entry, so a
|
|
318
|
+
value that is also the name of a node draws that node inside the legend:
|
|
319
|
+
choose values that are not node names.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
value: Receives a node and returns its value, or `None` for none.
|
|
323
|
+
colours: Value to fill colour, in any form Graphviz accepts.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
A style function to pass to Hamilton, alone or through
|
|
327
|
+
`compose_styles`.
|
|
328
|
+
|
|
329
|
+
Examples:
|
|
330
|
+
```python
|
|
331
|
+
def kind(node):
|
|
332
|
+
return "input" if node.is_external_input else "step"
|
|
333
|
+
|
|
334
|
+
style = fill_by(kind, {"input": "#e7eef7", "step": "#d9ead3"})
|
|
335
|
+
digraph = dr.display_all_functions(custom_style_function=style)
|
|
336
|
+
```
|
|
337
|
+
"""
|
|
338
|
+
|
|
339
|
+
def style(
|
|
340
|
+
*, node: graph_types.HamiltonNode, node_class: str
|
|
341
|
+
) -> tuple[dict[str, str], str | None, str | None]:
|
|
342
|
+
v = value(node)
|
|
343
|
+
if v is None or v not in colours:
|
|
344
|
+
return {}, node_class, None
|
|
345
|
+
return {"fillcolor": colours[v]}, node_class, v
|
|
346
|
+
|
|
347
|
+
return style
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def fill_by_tag(tag: str, colours: Mapping[str, str]) -> StyleFunction:
|
|
351
|
+
"""Build a style function that fills nodes by the value of a tag.
|
|
352
|
+
|
|
353
|
+
`fill_by` with a node's `tag` value as its value; a value that is not a
|
|
354
|
+
string is ignored.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
tag: The name of the tag, as given to Hamilton's `@tag`.
|
|
358
|
+
colours: Tag value to fill colour, in any form Graphviz accepts.
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
A style function to pass to Hamilton, alone or through
|
|
362
|
+
`compose_styles`.
|
|
363
|
+
|
|
364
|
+
Examples:
|
|
365
|
+
```python
|
|
366
|
+
style = fill_by_tag("stage", {"clean": "#d9ead3", "model": "#fde9c4"})
|
|
367
|
+
digraph = dr.display_all_functions(custom_style_function=style)
|
|
368
|
+
```
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
def value(node: graph_types.HamiltonNode) -> str | None:
|
|
372
|
+
v = node.tags.get(tag)
|
|
373
|
+
return v if isinstance(v, str) else None
|
|
374
|
+
|
|
375
|
+
return fill_by(value, colours)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
_LEGEND_ATTR_RE = re.compile(r'(?:URL|tooltip)="(?:[^"\\]|\\.)*" ?')
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def clean_legend(digraph: "graphviz.Digraph") -> "graphviz.Digraph":
|
|
382
|
+
"""Drop links and tooltips from the entries of Hamilton's legend, in place.
|
|
383
|
+
|
|
384
|
+
Hamilton draws each legend entry with the style of the last node that
|
|
385
|
+
named it, so once nodes are linked, each swatch carries some node's link
|
|
386
|
+
and tooltip. A drawing without a legend is left unchanged.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
digraph: A drawing returned by one of Hamilton's display methods.
|
|
390
|
+
|
|
391
|
+
Returns:
|
|
392
|
+
`digraph` itself, for chaining.
|
|
393
|
+
"""
|
|
394
|
+
in_legend = False
|
|
395
|
+
for i, line in enumerate(digraph.body):
|
|
396
|
+
if "subgraph cluster__legend" in line:
|
|
397
|
+
in_legend = True
|
|
398
|
+
if not in_legend:
|
|
399
|
+
continue
|
|
400
|
+
if line.strip() == "}":
|
|
401
|
+
break
|
|
402
|
+
digraph.body[i] = _LEGEND_ATTR_RE.sub("", line).replace(" ]", "]")
|
|
403
|
+
return digraph
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Render a Graphviz drawing as an HTML fragment for a documentation page.
|
|
2
|
+
|
|
3
|
+
`graph_html` inlines the SVG and lays an invisible HTML link over the name of
|
|
4
|
+
each node with a `URL` attribute, so that the name is a link and a theme's link
|
|
5
|
+
previews work on it.
|
|
6
|
+
|
|
7
|
+
A node's `URL` may name an mkdocstrings identifier rather than a URL, through
|
|
8
|
+
`autoref`, and the documentation build then writes the link.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import colorsys
|
|
12
|
+
import html
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from types import MappingProxyType
|
|
17
|
+
from typing import Any, Literal
|
|
18
|
+
|
|
19
|
+
import graphviz
|
|
20
|
+
|
|
21
|
+
__all__ = ["AUTOREF_PREFIX", "PREVIEW_OVERLAY", "DarkColours", "autoref", "graph_html"]
|
|
22
|
+
|
|
23
|
+
PREVIEW_OVERLAY: Mapping[str, str] = MappingProxyType({"data-preview": ""})
|
|
24
|
+
"""Overlay attributes that turn on instant previews in Zensical and Material for
|
|
25
|
+
MkDocs."""
|
|
26
|
+
|
|
27
|
+
AUTOREF_PREFIX = "autoref:"
|
|
28
|
+
"""Marks a node's `URL` as an identifier for the documentation build to resolve."""
|
|
29
|
+
|
|
30
|
+
_SVG_SIZE_RE = re.compile(r'\s(?:width|height)="(?P<value>[\d.]+)pt"')
|
|
31
|
+
_VIEWBOX_RE = re.compile(r'viewBox="(?P<box>[^"]+)"')
|
|
32
|
+
_TRANSFORM_RE = re.compile(
|
|
33
|
+
r'id="graph0"[^>]*transform="scale\((?P<scale>[^)]+)\)'
|
|
34
|
+
r'[^"]*translate\((?P<translate>[^)]+)\)"'
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Themes underline every link in page content, which includes the `<a>` that
|
|
38
|
+
# Graphviz wraps around any node with a tooltip. Only a linked node's name (its
|
|
39
|
+
# first label line), which its overlay covers, keeps the underline. No square
|
|
40
|
+
# brackets anywhere in the fragment: Markdown escapes them, even inside
|
|
41
|
+
# `<style>` and attributes.
|
|
42
|
+
_CSS = (
|
|
43
|
+
# Themes colour links too, which `currentColor` in the drawing would pick up.
|
|
44
|
+
".dotdoc-graph svg a{text-decoration:none;color:inherit}"
|
|
45
|
+
".dotdoc-graph svg a.dotdoc-link text:first-of-type{text-decoration:underline}"
|
|
46
|
+
# An unfilled shape shows its tooltip only on its outline otherwise.
|
|
47
|
+
".dotdoc-graph svg a *{pointer-events:visible}"
|
|
48
|
+
# As wide as the page allows, up to the drawing's own size, times the zoom.
|
|
49
|
+
".dotdoc-scroll{overflow:auto}"
|
|
50
|
+
".dotdoc-drawing{position:relative;margin:0 auto;"
|
|
51
|
+
"width:calc(min(100%,var(--dotdoc-width,100%))*var(--dotdoc-zoom,1))}"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Expanded, the drawing covers the window, under the theme's previews, and is
|
|
55
|
+
# as large as fits it, up or down. Labels are swapped by CSS.
|
|
56
|
+
_CONTROLS_CSS = (
|
|
57
|
+
".dotdoc-controls .md-button{margin:0 0.4em 0.5em 0;padding:0.2em 0.9em}"
|
|
58
|
+
".dotdoc-graph.dotdoc-expanded{position:fixed;inset:0;z-index:4;"
|
|
59
|
+
"display:flex;flex-direction:column;padding:1rem;"
|
|
60
|
+
"background:var(--md-default-bg-color,#fff)}"
|
|
61
|
+
".dotdoc-expanded .dotdoc-scroll{flex:1;min-height:0}"
|
|
62
|
+
".dotdoc-expanded .dotdoc-drawing{width:calc("
|
|
63
|
+
"min(100%,(100vh - 5rem)*var(--dotdoc-ratio,1))*var(--dotdoc-zoom,1))}"
|
|
64
|
+
".dotdoc-expanded .dotdoc-expand,"
|
|
65
|
+
".dotdoc-graph:not(.dotdoc-expanded) .dotdoc-close{display:none}"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _zoom(operation: str) -> str:
|
|
70
|
+
return (
|
|
71
|
+
"var d=this.closest('.dotdoc-graph').querySelector('.dotdoc-drawing');"
|
|
72
|
+
"var z=+d.style.getPropertyValue('--dotdoc-zoom')||1;"
|
|
73
|
+
f"d.style.setProperty('--dotdoc-zoom',{operation})"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Inline handlers rather than a script, so they need no JavaScript file and
|
|
78
|
+
# survive a theme's instant navigation, which does not rerun page scripts.
|
|
79
|
+
_CONTROLS = (
|
|
80
|
+
'<div class="dotdoc-controls">'
|
|
81
|
+
'<button type="button" class="md-button" '
|
|
82
|
+
"onclick=\"this.closest('.dotdoc-graph').classList.toggle('dotdoc-expanded')\">"
|
|
83
|
+
'<span class="dotdoc-expand">Expand</span>'
|
|
84
|
+
'<span class="dotdoc-close">Close</span></button>'
|
|
85
|
+
'<button type="button" class="md-button" aria-label="Zoom out" '
|
|
86
|
+
f'onclick="{_zoom("Math.max(1,z/1.25)")}">−</button>'
|
|
87
|
+
'<button type="button" class="md-button" aria-label="Zoom in" '
|
|
88
|
+
f'onclick="{_zoom("Math.min(8,z*1.25)")}">+</button>'
|
|
89
|
+
"</div>"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
_CLOSE_ON_ESCAPE = (
|
|
93
|
+
" onkeydown=\"if(event.key==='Escape')this.classList.remove('dotdoc-expanded')\""
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_SVG_NODE_LINK_RE = re.compile(r'(?P<start><g id="a_node\d+"><a) xlink:href="[^"]*"')
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def autoref(identifier: str) -> str:
|
|
101
|
+
"""Return a node `URL` that links to an identifier's documentation.
|
|
102
|
+
|
|
103
|
+
`graph_html` writes the node's overlay as an `<autoref>` element, which
|
|
104
|
+
mkdocs-autorefs, and Zensical's own autorefs, replace with a link to the
|
|
105
|
+
identifier's entry, relative to the page and whatever the site's URL
|
|
106
|
+
style. An identifier the build cannot find is reported as a warning.
|
|
107
|
+
The links work only in a page those tools build: in a notebook, for
|
|
108
|
+
instance, they lead nowhere.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
identifier: What the documentation registers the entry under; for
|
|
112
|
+
mkdocstrings, an object's dotted path, such as
|
|
113
|
+
`"dotdoc.html.graph_html"`.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
The identifier, prefixed with `AUTOREF_PREFIX`.
|
|
117
|
+
|
|
118
|
+
Examples:
|
|
119
|
+
>>> autoref("dotdoc.html.graph_html")
|
|
120
|
+
'autoref:dotdoc.html.graph_html'
|
|
121
|
+
"""
|
|
122
|
+
return AUTOREF_PREFIX + identifier
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _identifier(url: str) -> str | None:
|
|
126
|
+
if url.startswith(AUTOREF_PREFIX):
|
|
127
|
+
return url.removeprefix(AUTOREF_PREFIX)
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_GROUP_RE = re.compile(r'<g id="[^"]*" class="(?P<kind>node|edge|cluster|graph)"')
|
|
132
|
+
_SHAPE_RE = re.compile(r'<(?:ellipse|polygon|polyline|path) fill="(?P<fill>[^"]*)"')
|
|
133
|
+
_COLOUR_ATTR_RE = re.compile(r' (?P<attr>fill|stroke)="(?P<colour>[^"]*)"')
|
|
134
|
+
_HEX_RE = re.compile(r"#[0-9a-f]{6}")
|
|
135
|
+
_BACKGROUND = '<polygon fill="white" stroke="none"'
|
|
136
|
+
_NOT_COLOURS = frozenset({"none", "transparent", "black", "currentcolor"})
|
|
137
|
+
|
|
138
|
+
type DarkColours = Mapping[str, str] | Literal["auto"]
|
|
139
|
+
"""Light colours to the colours to draw them in on a dark background, or
|
|
140
|
+
`"auto"` to derive one for each colour."""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _auto_dark(colour: str) -> str | None:
|
|
144
|
+
"""Return `colour` with its lightness flipped, or `None` if not hex."""
|
|
145
|
+
colour = "#ffffff" if colour == "white" else colour
|
|
146
|
+
if not _HEX_RE.fullmatch(colour):
|
|
147
|
+
return None
|
|
148
|
+
rgb = (int(colour[i : i + 2], 16) / 255 for i in (1, 3, 5))
|
|
149
|
+
hue, lightness, saturation = colorsys.rgb_to_hls(*rgb)
|
|
150
|
+
dark = colorsys.hls_to_rgb(hue, 1 - lightness, saturation)
|
|
151
|
+
return "#" + "".join(f"{round(v * 255):02x}" for v in dark)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _theme_colours(svg: str, dark: DarkColours | None) -> str:
|
|
155
|
+
"""Draw Graphviz's default black in the page's text colour, on no background.
|
|
156
|
+
|
|
157
|
+
Strokes and arrowheads drawn in black, and text that sits on the page
|
|
158
|
+
rather than on a filled shape, become `currentColor`, which follows the
|
|
159
|
+
theme's light or dark scheme. Graphviz's white background is dropped.
|
|
160
|
+
|
|
161
|
+
A colour with a dark counterpart in `dark` is drawn with CSS
|
|
162
|
+
`light-dark()`, which the browser resolves by the page's `color-scheme`;
|
|
163
|
+
text on a fill with a counterpart becomes `currentColor` too. Text on any
|
|
164
|
+
other fill keeps its colour, to stay readable on light fills.
|
|
165
|
+
"""
|
|
166
|
+
table = (
|
|
167
|
+
None
|
|
168
|
+
if dark == "auto" or dark is None
|
|
169
|
+
else {k.lower(): v for k, v in dark.items()}
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def counterpart(colour: str) -> str | None:
|
|
173
|
+
colour = colour.lower()
|
|
174
|
+
if dark is None or colour in _NOT_COLOURS:
|
|
175
|
+
return None
|
|
176
|
+
return _auto_dark(colour) if table is None else table.get(colour)
|
|
177
|
+
|
|
178
|
+
def adapt(line: str) -> str:
|
|
179
|
+
line = line.replace('stroke="black"', 'stroke="currentColor"')
|
|
180
|
+
if not line.startswith("<text"):
|
|
181
|
+
line = line.replace('fill="black"', 'fill="currentColor"')
|
|
182
|
+
styles = [
|
|
183
|
+
f"{m['attr']}:light-dark({m['colour']},{html.escape(night)})"
|
|
184
|
+
for m in _COLOUR_ATTR_RE.finditer(line)
|
|
185
|
+
if (night := counterpart(m["colour"])) is not None
|
|
186
|
+
]
|
|
187
|
+
if not styles:
|
|
188
|
+
return line
|
|
189
|
+
tag, rest = line.split(" ", 1)
|
|
190
|
+
return f'{tag} style="{";".join(styles)}" {rest}'
|
|
191
|
+
|
|
192
|
+
lines = []
|
|
193
|
+
kind, keeps_text, shape_seen = "graph", False, False
|
|
194
|
+
for line in svg.splitlines():
|
|
195
|
+
if group := _GROUP_RE.match(line):
|
|
196
|
+
kind, keeps_text, shape_seen = group["kind"], False, False
|
|
197
|
+
elif line.startswith("<text"):
|
|
198
|
+
if not keeps_text and ' fill="' not in line:
|
|
199
|
+
line = line.replace("<text", '<text fill="currentColor"', 1)
|
|
200
|
+
line = adapt(line)
|
|
201
|
+
elif shape := _SHAPE_RE.match(line):
|
|
202
|
+
if kind == "graph" and not shape_seen and line.startswith(_BACKGROUND):
|
|
203
|
+
shape_seen = True
|
|
204
|
+
continue
|
|
205
|
+
if kind in ("node", "cluster") and not shape_seen:
|
|
206
|
+
fill = shape["fill"]
|
|
207
|
+
keeps_text = (
|
|
208
|
+
fill not in ("none", "transparent") and counterpart(fill) is None
|
|
209
|
+
)
|
|
210
|
+
shape_seen = True
|
|
211
|
+
line = adapt(line)
|
|
212
|
+
lines.append(line)
|
|
213
|
+
return "\n".join(lines)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _unlink_nodes(svg: str) -> str:
|
|
217
|
+
"""Drop the SVG's node links, which the overlays replace.
|
|
218
|
+
|
|
219
|
+
The `<a>` stays, without its `href`, for the tooltip Graphviz gives it.
|
|
220
|
+
"""
|
|
221
|
+
return _SVG_NODE_LINK_RE.sub(r'\g<start> class="dotdoc-link"', svg)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _numbers(text: str) -> list[float]:
|
|
225
|
+
return [float(v) for v in text.replace(",", " ").split()]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _view_box(svg: str) -> list[float]:
|
|
229
|
+
viewbox = _VIEWBOX_RE.search(svg)
|
|
230
|
+
if viewbox is None:
|
|
231
|
+
raise ValueError("Graphviz drew an SVG without the expected layout.")
|
|
232
|
+
return _numbers(viewbox["box"])
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _name_box(obj: Mapping[str, Any]) -> tuple[float, float, float, float]:
|
|
236
|
+
"""Return `(left, top, width, height)` of a node's first label line.
|
|
237
|
+
|
|
238
|
+
In Graphviz's layout coordinates: points, origin at the bottom left. The
|
|
239
|
+
first text drawn in the label is taken to be the node's name; its height is
|
|
240
|
+
taken from the font size. A node with no text falls back to its whole box.
|
|
241
|
+
"""
|
|
242
|
+
size = 14.0
|
|
243
|
+
for op in obj.get("_ldraw_", []):
|
|
244
|
+
if op["op"] == "F":
|
|
245
|
+
size = float(op["size"])
|
|
246
|
+
elif op["op"] == "T":
|
|
247
|
+
(x, y), width = op["pt"], float(op["width"])
|
|
248
|
+
x -= {"l": 0.0, "c": width / 2, "r": width}[op["align"]]
|
|
249
|
+
return x, y + 0.8 * size, width, size
|
|
250
|
+
x, y = _numbers(obj["pos"])
|
|
251
|
+
w, h = float(obj["width"]) * 72, float(obj["height"]) * 72
|
|
252
|
+
return x - w / 2, y + h / 2, w, h
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _name(obj: Mapping[str, Any]) -> str:
|
|
256
|
+
"""Return a node's first label line, or its id if it has no text."""
|
|
257
|
+
for op in obj.get("_ldraw_", []):
|
|
258
|
+
if op["op"] == "T":
|
|
259
|
+
return op["text"]
|
|
260
|
+
return obj["name"]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _overlays(
|
|
264
|
+
drawing: graphviz.Source | graphviz.Graph | graphviz.Digraph,
|
|
265
|
+
svg: str,
|
|
266
|
+
attrs: Mapping[str, str] | None,
|
|
267
|
+
) -> list[str]:
|
|
268
|
+
"""Return an absolutely positioned link over each linked node's name.
|
|
269
|
+
|
|
270
|
+
Name boxes come from Graphviz's JSON layout and are mapped through the
|
|
271
|
+
SVG's `graph0` transform into percentages of its `viewBox`, so they scale
|
|
272
|
+
with the drawing.
|
|
273
|
+
"""
|
|
274
|
+
vx, vy, vw, vh = _view_box(svg)
|
|
275
|
+
transform = _TRANSFORM_RE.search(svg)
|
|
276
|
+
if transform is None:
|
|
277
|
+
raise ValueError("Graphviz drew an SVG without the expected layout.")
|
|
278
|
+
sx, sy = _numbers(transform["scale"])
|
|
279
|
+
tx, ty = _numbers(transform["translate"])
|
|
280
|
+
layout = json.loads(drawing.pipe(format="json", encoding="utf-8"))
|
|
281
|
+
extra = "".join(f' {k}="{html.escape(v)}"' for k, v in (attrs or {}).items())
|
|
282
|
+
overlays = []
|
|
283
|
+
for obj in layout.get("objects", []):
|
|
284
|
+
url = obj.get("URL")
|
|
285
|
+
if not url or "pos" not in obj:
|
|
286
|
+
continue
|
|
287
|
+
x, y, w, h = _name_box(obj)
|
|
288
|
+
left = (sx * (x + tx) - vx) / vw * 100
|
|
289
|
+
top = (sy * (ty - y) - vy) / vh * 100
|
|
290
|
+
# `font-size:0` hides any icon a theme appends to the link.
|
|
291
|
+
box = (
|
|
292
|
+
f"position:absolute;font-size:0;left:{left:.3f}%;top:{top:.3f}%;"
|
|
293
|
+
f"width:{sx * w / vw * 100:.3f}%;height:{sy * h / vh * 100:.3f}%"
|
|
294
|
+
)
|
|
295
|
+
rest = f'aria-label="{html.escape(_name(obj))}" style="{box}"{extra}'
|
|
296
|
+
identifier = _identifier(url)
|
|
297
|
+
if identifier is None:
|
|
298
|
+
overlays.append(f'<a href="{html.escape(url)}" {rest}></a>')
|
|
299
|
+
else:
|
|
300
|
+
identifier = html.escape(identifier)
|
|
301
|
+
overlays.append(f'<autoref identifier="{identifier}" {rest}></autoref>')
|
|
302
|
+
return overlays
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def graph_html(
|
|
306
|
+
drawing: graphviz.Source | graphviz.Graph | graphviz.Digraph,
|
|
307
|
+
*,
|
|
308
|
+
overlay: Mapping[str, str] | None = PREVIEW_OVERLAY,
|
|
309
|
+
controls: bool = False,
|
|
310
|
+
theme_colours: bool = True,
|
|
311
|
+
dark: DarkColours | None = None,
|
|
312
|
+
) -> str:
|
|
313
|
+
"""Render a Graphviz drawing as an HTML fragment for a documentation page.
|
|
314
|
+
|
|
315
|
+
The SVG is inlined, so its tooltips work (an SVG shown through `<img>` has
|
|
316
|
+
none), and it scales down to fit the page. A node is linked by giving it a
|
|
317
|
+
`URL` attribute. Its name, taken to be the first line of its label, is then
|
|
318
|
+
the link: an invisible HTML link, carrying `overlay`'s attributes, is laid
|
|
319
|
+
over it and the name is underlined, whatever the theme does to links. The
|
|
320
|
+
rest of the node is not a link, so following one is always the same
|
|
321
|
+
gesture as previewing it, and themes that preview a link's target on hover
|
|
322
|
+
only handle HTML links anyway. The overlays must be in the page when it
|
|
323
|
+
loads, so write the fragment into the page source or a notebook's output
|
|
324
|
+
rather than adding it from a script.
|
|
325
|
+
|
|
326
|
+
A URL is written into the page as it is, so it must work from the built
|
|
327
|
+
page; a URL made by `autoref` names an identifier for the documentation
|
|
328
|
+
build to resolve, which works in any URL style. Links on edges and graphs
|
|
329
|
+
are left to the SVG.
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
drawing: The Graphviz drawing to render. Any graph works, directed or
|
|
333
|
+
not, cycles included.
|
|
334
|
+
overlay: Extra attributes for each overlay link, or `None` for none.
|
|
335
|
+
The default turns on instant previews in Zensical and Material for
|
|
336
|
+
MkDocs.
|
|
337
|
+
controls: Add buttons above the drawing that zoom in and out of it
|
|
338
|
+
and expand it to cover the window, for drawings too large to read
|
|
339
|
+
in the page; Esc closes it again. Links and previews work at any
|
|
340
|
+
size. The buttons carry the `md-button` class, so Zensical and
|
|
341
|
+
Material for MkDocs style them.
|
|
342
|
+
theme_colours: Drop Graphviz's white background, and draw what it
|
|
343
|
+
draws in its default black in the page's text colour instead, so
|
|
344
|
+
the drawing follows a theme's light and dark schemes. Text on a
|
|
345
|
+
filled shape keeps its colour, and colours set in the drawing are
|
|
346
|
+
kept. `False` keeps Graphviz's colours.
|
|
347
|
+
dark: Colours to draw in place of the drawing's own on a dark
|
|
348
|
+
background: a mapping from a colour, as given to Graphviz (case
|
|
349
|
+
ignored), to its dark counterpart, in any CSS form; or `"auto"`,
|
|
350
|
+
which flips the lightness of every colour given in hex, and of
|
|
351
|
+
white. Each is drawn with CSS `light-dark()`, which follows the
|
|
352
|
+
theme's light and dark schemes where the theme sets the CSS
|
|
353
|
+
`color-scheme`, as Zensical does. Text on a fill with a
|
|
354
|
+
counterpart is drawn in the page's text colour. Needs
|
|
355
|
+
`theme_colours`.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
A `<div class="dotdoc-graph">` holding a short stylesheet, the
|
|
359
|
+
optional buttons, and the SVG with its overlays, with no blank lines, so
|
|
360
|
+
a Markdown page can hold it as one raw HTML block.
|
|
361
|
+
|
|
362
|
+
Raises:
|
|
363
|
+
ValueError: If Graphviz drew an SVG without the layout the overlays are
|
|
364
|
+
positioned from, or if `dark` is given without `theme_colours`.
|
|
365
|
+
|
|
366
|
+
Examples:
|
|
367
|
+
In a markdown-exec block in a documentation page:
|
|
368
|
+
|
|
369
|
+
```python
|
|
370
|
+
drawing = graphviz.Digraph()
|
|
371
|
+
drawing.node("graph_html", URL=autoref("dotdoc.html.graph_html"))
|
|
372
|
+
print(graph_html(drawing))
|
|
373
|
+
```
|
|
374
|
+
"""
|
|
375
|
+
svg = drawing.pipe(format="svg", encoding="utf-8")
|
|
376
|
+
svg = svg[svg.index("<svg") :]
|
|
377
|
+
root_end = svg.index(">")
|
|
378
|
+
root = svg[:root_end]
|
|
379
|
+
width = next((m["value"] for m in _SVG_SIZE_RE.finditer(root)), None)
|
|
380
|
+
root = _SVG_SIZE_RE.sub("", root) + ' style="display:block;width:100%;height:auto"'
|
|
381
|
+
svg = "\n".join(line for line in (root + svg[root_end:]).splitlines() if line)
|
|
382
|
+
overlays = _overlays(drawing, svg, overlay)
|
|
383
|
+
svg = _unlink_nodes(svg)
|
|
384
|
+
if dark is not None and not theme_colours:
|
|
385
|
+
raise ValueError("`dark` needs `theme_colours`.")
|
|
386
|
+
if theme_colours:
|
|
387
|
+
svg = _theme_colours(svg, dark)
|
|
388
|
+
_, _, view_width, view_height = _view_box(svg)
|
|
389
|
+
size = f"--dotdoc-width:{width}pt;" if width is not None else ""
|
|
390
|
+
size += f"--dotdoc-ratio:{view_width / view_height:.4f}"
|
|
391
|
+
css = _CSS + (_CONTROLS_CSS if controls else "")
|
|
392
|
+
return "".join(
|
|
393
|
+
[
|
|
394
|
+
f'<div class="dotdoc-graph"{_CLOSE_ON_ESCAPE if controls else ""}>',
|
|
395
|
+
f"<style>{css}</style>",
|
|
396
|
+
_CONTROLS if controls else "",
|
|
397
|
+
'<div class="dotdoc-scroll">',
|
|
398
|
+
f'<div class="dotdoc-drawing" style="{size}">',
|
|
399
|
+
svg,
|
|
400
|
+
*overlays,
|
|
401
|
+
"</div></div></div>",
|
|
402
|
+
]
|
|
403
|
+
)
|