Skip to content

Commit

Permalink
fix: cleaned up code and fixed the feedbacks by saairam
Browse files Browse the repository at this point in the history
  • Loading branch information
dakshpokar committed Aug 15, 2024
1 parent 243ff5c commit 7cc65b9
Showing 1 changed file with 59 additions and 50 deletions.
109 changes: 59 additions & 50 deletions maidr/core/maidr.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations

from typing import Literal
import html as pyhtml

Expand All @@ -14,6 +15,7 @@
from IPython.display import display_html
from maidr.core.context_manager import HighlightContextManager
from maidr.core.plot import MaidrPlot
import urllib.parse


class Maidr:
Expand Down Expand Up @@ -96,41 +98,6 @@ def show(self, renderer: Literal["auto", "ipython", "browser"] = "auto") -> obje
The renderer to use for the HTML preview.
"""
html = self._create_html_tag()
clean_html = pyhtml.escape(html.get_html_string())

if self._check_if_notebook():
# If this is a Jupyter Notebook, display the HTML content using an iframe to fix interactivity issues.

# The random_id is used to identify the iframe and its content
random_id = str(uuid.uuid4())

# Resizing script to fit the chart content within the iframe
resizing_script = f"""
<script>
function resizeIframe() {{
var iframe = document.getElementById('{random_id}');
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 50 + 'px';
}}
var iframe = document.getElementById('{random_id}');
iframe.onload = function() {{
resizeIframe();
iframe.contentWindow.addEventListener('resize', resizeIframe);
}};
window.onresize = resizeIframe;
</script>
"""

iframe = (
'<iframe id="' + random_id + '" '
'srcdoc="' + clean_html + '" frameBorder=0 scrolling=auto '
'style="width: 100%; height:100%" backgroundColor: #fff"></iframe>'
)
display_html(
iframe + resizing_script,
raw=True,
)
return None

return html.show(renderer)

def clear(self):
Expand All @@ -140,20 +107,6 @@ def destroy(self) -> None:
del self._plots
del self._fig

def _check_if_notebook(self) -> bool:
"""Returns True if the current environment is a IPython notebook."""
try:
import IPython # pyright: ignore[reportMissingModuleSource, reportUnknownVariableType]

ipy = ( # pyright: ignore[reportUnknownVariableType]
IPython.get_ipython() # pyright: ignore[reportUnknownMemberType, reportPrivateImportUsage]
)
if ipy:
return True
return False
except ImportError:
return False

def _create_html_tag(self) -> Tag:
"""Create the MAIDR HTML using HTML tags."""
tagged_elements = [element for plot in self._plots for element in plot.elements]
Expand Down Expand Up @@ -209,10 +162,43 @@ def _unique_id() -> str:
"""Generate a unique identifier string using UUID4."""
return str(uuid.uuid4())

@staticmethod
def _check_if_notebook() -> bool:
"""Returns True if the current environment is a IPython notebook."""
try:
from IPython.core.interactiveshell import InteractiveShell

return (
InteractiveShell.initialized()
and InteractiveShell.instance() is not None
)
except ImportError:
return False

@staticmethod
def _inject_plot(plot: HTML, maidr: str) -> Tag:
"""Embed the plot and associated MAIDR scripts into the HTML structure."""
return tags.html(

# The random_id is used to identify the iframe and its content
random_id = Maidr._unique_id()

# Resizing script to fit the chart content within the iframe
resizing_script = f"""
<script type="text/javascript">
function resizeIframe() {{
var iframe = document.getElementById('{random_id}');
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 50 + 'px';
}}
var iframe = document.getElementById('{random_id}');
iframe.onload = function() {{
resizeIframe();
iframe.contentWindow.addEventListener('resize', resizeIframe);
}};
window.onresize = resizeIframe;
</script>
"""

base_html = tags.html(
tags.head(
tags.meta(charset="UTF-8"),
tags.title("MAIDR"),
Expand All @@ -230,3 +216,26 @@ def _inject_plot(plot: HTML, maidr: str) -> Tag:
),
tags.script(maidr),
)

if Maidr._check_if_notebook():
# If this is a Jupyter Notebook, display the HTML
# content using an iframe to fix interactivity issues.
clean_html = pyhtml.escape(base_html.get_html_string())

iframe = f"""
<iframe
id='{random_id}'
srcdoc="{clean_html}"
frameBorder=0
scrolling=auto
style="width: 100%; height:100%"
backgroundColor: #fff"
>
</iframe>
"""

display_html(iframe + resizing_script, raw=True)

return tags.br()

return base_html

0 comments on commit 7cc65b9

Please sign in to comment.