Skip to content

Commit

Permalink
make svg graphs clickable
Browse files Browse the repository at this point in the history
This patch inserts a javascript snippet into generated svg graphs to make nodes
and edges highlightable in capable viewers (such as a web browser).
  • Loading branch information
gertjanvanzwieten committed Feb 27, 2024
1 parent 99349c0 commit f73fbd6
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 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,33 @@ 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 (.*?)>', insert_clickHandler, graph, count=1, flags=re.DOTALL)
img.write(graph)

insert_clickHandler = rb'''<svg \1 onload="document.addEventListener('click', clickHandler)">
<style>
.highlight path { stroke: orange; stroke-width: 2; }
.highlight polygon:first-of-type { fill: orange; }
.highlight polygon { stroke: orange; }
.highlight text { fill: white; }
</style>
<script>
<![CDATA[
function clickHandler(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 f73fbd6

Please sign in to comment.