Skip to content

Commit

Permalink
Merge pull request #8 from vlasenkoalexey/master
Browse files Browse the repository at this point in the history
added pan and zoom support for jupyter
  • Loading branch information
akimach committed Feb 11, 2021
2 parents e00298e + 0734ef1 commit 9c054b7
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
3 changes: 2 additions & 1 deletion tfgraphviz/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# coding: utf-8
from .graphviz_wrapper import board, add_digraph, add_digraph_node, add_digraph_edge
from .jupyter_helper import jupyter_pan_and_zoom, jupyter_show_as_svg


__author__ = "akimach"
__version__ = "0.0.6"
__version__ = "0.0.7"
__license__ = "MIT"
55 changes: 55 additions & 0 deletions tfgraphviz/jupyter_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import time
from IPython.display import HTML

def jupyter_show_as_svg(g):
"""
Shows object as SVG (by default it is rendered as image).
@param g: digraph object
"""
return HTML(g.pipe(format='svg').decode("utf-8"))

def jupyter_pan_and_zoom(
g,
element_styles="height:auto",
container_styles="overflow:hidden",
pan_zoom_json = "{controlIconsEnabled: true, zoomScaleSensitivity: 0.4, minZoom: 0.2}"):
"""
Embeds SVG object into Jupyter cell with ability to pan and zoom.
@param g: digraph object
@param element_styles: CSS styles for embedded SVG element.
@param container_styles: CSS styles for container div element.
@param pan_zoom_json: pan and zoom settings, see https://github.com/ariutta/svg-pan-zoom
"""
svg_txt = g.pipe(format='svg').decode("utf-8")
html_container_class_name = F"svg_container_{int(time.time())}"
html = F'''
<div class="{html_container_class_name}">
<style>
.{html_container_class_name} {{
{container_styles}
}}
.{html_container_class_name} SVG {{
{element_styles}
}}
</style>
<script src="https://ariutta.github.io/svg-pan-zoom/dist/svg-pan-zoom.min.js"></script>
<script type="text/javascript">
attempts = 5;
var existCondition = setInterval(function() {{
console.log(attempts);
svg_el = document.querySelector(".{html_container_class_name} svg");
if (svg_el != null) {{
console.log("Exists!");
clearInterval(existCondition);
svgPanZoom(svg_el, {pan_zoom_json});
}}
if (--attempts == 0) {{
console.warn("SVG element not found, zoom wont work");
clearInterval(existCondition);
}}
}}, 100); // check every 100ms
</script>
{svg_txt}
</div>
'''
return HTML(html)

0 comments on commit 9c054b7

Please sign in to comment.