Skip to content

Commit

Permalink
make graphviz svg interactive (#858)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gertjan van Zwieten committed Feb 28, 2024
2 parents 99349c0 + ad33d53 commit 59890da
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion nutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'Numerical Utilities for Finite Element Analysis'

__version__ = version = '9a16'
__version__ = version = '9a17'
version_name = 'jook-sing'
31 changes: 30 additions & 1 deletion nutils/_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import subprocess
import abc
import html
import re

Metadata = TypeVar('Metadata')
GraphvizColorCallback = Callable[['Node'], Optional[str]]
Expand Down Expand Up @@ -68,7 +69,35 @@ def export_graphviz(self, *, fill_color: Optional[GraphvizColorCallback] = None,
for i, line in enumerate(src.split('\n'), 1):
print('{:04d} {}'.format(i, line))
treelog.warning('graphviz failed for error code', status.returncode)
img.write(status.stdout)
graph = status.stdout
if image_type == 'svg':
graph = re.sub(b'<svg width="(\d+)pt" height="(\d+)pt"', lambda match:
b'<svg width="%dpt" height="%dpt"' % tuple((int(l)*2)//3 for l in match.groups()), graph, count=1)
i = graph.rindex(b'</svg>')
graph = graph[:i] + clickHandler + graph[i:]
img.write(graph)

clickHandler = b'''
<style>
g.edge, g.node { cursor: pointer; }
.highlight path { stroke: orange; stroke-width: 2; }
.highlight polygon:first-of-type { fill: orange; }
.highlight polygon { stroke: orange; }
.highlight text { fill: white; }
</style>
<script>
document.addEventListener("click", function (event) {
const g = event.target.closest("g");
if (g.classList.contains("edge")) {
g.classList.toggle("highlight"); }
else if (g.classList.contains("node")) {
const index = g.firstElementChild.textContent;
const pattern = new RegExp("(^|[^0-9])" + index + "($|[^0-9])");
const isnew = g.classList.toggle("highlight");
for (const edge of document.getElementsByClassName("edge")) {
if (pattern.test(edge.firstElementChild.textContent)) {
edge.classList.toggle("highlight", isnew); } } } });
</script>'''


class RegularNode(Node[Metadata]):
Expand Down

0 comments on commit 59890da

Please sign in to comment.