Skip to content
33 changes: 25 additions & 8 deletions src/py/kaleido/_page_generator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from __future__ import annotations

from pathlib import Path
from urllib.parse import urlparse

import logistro

Expand All @@ -10,6 +13,14 @@
KJS_PATH = Path(__file__).resolve().parent / "vendor" / "kaleido_scopes.js"


def _ensure_path(path: Path | str):
_logger.debug(f"Ensuring path {path!s}")
if urlparse(str(path)).scheme.startswith("http"): # is url
return
if not Path(path).exists():
raise FileNotFoundError(f"{path!s} does not exist.")


class PageGenerator:
"""
A page generator can set the versions of the js libraries used to render.
Expand All @@ -35,7 +46,7 @@ class PageGenerator:
footer = f"""
<script src="{KJS_PATH.as_uri()}"></script>
</head>
<body style="{{margin: 0; padding: 0;}}"><img id="kaleido-image"><img></body>
<body style="{{margin: 0; padding: 0;}}"><img id="kaleido-image"></img></body>
</html>
"""
"""The footer is the HTML that always goes on the bottom. Rarely needs changing."""
Expand All @@ -45,13 +56,14 @@ def __init__(self, *, plotly=None, mathjax=None, others=None, force_cdn=False):
Create a PageGenerator.

Args:
plotly: the url to the plotly script to use. The default is the one
plotly.py is using, if not installed, it uses the constant declared.
mathjax: the url to the mathjax script. By default is constant above.
Can be set to false to turn off.
others: a list of other script urls to include. Usually strings, but can be
(str, str) where its (url, encoding).
force_cdn: (default False) Don't use plotly import, use CDN
plotly: The url to the plotly.js to use. Defaults to plotly.js
present in plotly.py, if installed. Otherwise fallback to
value of DEFAULT_PLOTLY.
mathjax: The url to the mathjax script. Defaults to values of
DEFAULT_MATHJAX. Can be set to false to disable mathjax.
others: A list of other script urls to include. Usually strings, but
can be (str, str) where it's (url, encoding).
force_cdn: Set True to force CDN use, defaults to False.

"""
self._scripts = []
Expand Down Expand Up @@ -81,14 +93,19 @@ def __init__(self, *, plotly=None, mathjax=None, others=None, force_cdn=False):
_logger.info("Plotly not installed. Using CDN.")
plotly = (DEFAULT_PLOTLY, "utf-8")
elif isinstance(plotly, str):
_ensure_path(plotly)
plotly = (plotly, "utf-8")
_logger.debug(f"Plotly script: {plotly}")
self._scripts.append(plotly)
if mathjax is not False:
if not mathjax:
mathjax = DEFAULT_MATHJAX
else:
_ensure_path(mathjax)
self._scripts.append(mathjax)
if others:
for o in others:
_ensure_path(o)
self._scripts.extend(others)

def generate_index(self, path=None):
Expand Down
2 changes: 1 addition & 1 deletion src/py/kaleido/vendor/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
<script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js"></script>
<script src="./kaleido_scopes.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
32 changes: 16 additions & 16 deletions src/py/tests/test_page_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<script src="https://cdn\.jsdelivr\.net/npm/mathjax@3\.2\.2/es5/tex-svg\.js"></script>
<script src="\S[^\n]*/kaleido_scopes\.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
""") # noqa: E501 line too long

Expand All @@ -50,7 +50,7 @@
<script src="https://cdn\.jsdelivr\.net/npm/mathjax@3\.2\.2/es5/tex-svg\.js"></script>
<script src="\S[^\n]*/kaleido_scopes\.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
""")

Expand All @@ -67,11 +67,11 @@
MathJax\.Hub\.Config\({ "SVG": { blacker: 0 }}\)
</script>

<script src="file:///with_plot" charset="utf-8"></script>
<script src="https://with_plot" charset="utf-8"></script>
<script src="https://cdn\.jsdelivr\.net/npm/mathjax@3\.2\.2/es5/tex-svg\.js"></script>
<script src="\S[^\n]*/kaleido_scopes\.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
""")

Expand All @@ -88,10 +88,10 @@
MathJax\.Hub\.Config\({ "SVG": { blacker: 0 }}\)
</script>

<script src="file:///with_plot" charset="utf-8"></script>
<script src="https://with_plot" charset="utf-8"></script>
<script src="\S[^\n]*/kaleido_scopes\.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
""")

Expand All @@ -108,13 +108,13 @@
MathJax\.Hub\.Config\({ "SVG": { blacker: 0 }}\)
</script>

<script src="file:///with_plot" charset="utf-8"></script>
<script src="file:///with_mathjax"></script>
<script src="1"></script>
<script src="2"></script>
<script src="https://with_plot" charset="utf-8"></script>
<script src="https://with_mathjax"></script>
<script src="https://1"></script>
<script src="https://2"></script>
<script src="\S[^\n]*/kaleido_scopes\.js"></script>
</head>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"><img></body>
<body style="{margin: 0; padding: 0;}"><img id="kaleido-image"></img></body>
</html>
""")

Expand Down Expand Up @@ -143,19 +143,19 @@ async def test_page_generator():
all_defaults = PageGenerator().generate_index()
assert all_defaults_re.findall(all_defaults)

with_plot = PageGenerator(plotly="file:///with_plot").generate_index()
with_plot = PageGenerator(plotly="https://with_plot").generate_index()
assert with_plot_result_re.findall(with_plot)

without_math = PageGenerator(
plotly="file:///with_plot",
plotly="https://with_plot",
mathjax=False,
).generate_index()
assert without_math_result_re.findall(without_math)

with_others = PageGenerator(
plotly="file:///with_plot",
mathjax="file:///with_mathjax",
others=["1", "2"],
plotly="https://with_plot",
mathjax="https://with_mathjax",
others=["https://1", "https://2"],
).generate_index()
assert with_others_result_re.findall(with_others)

Expand Down
Loading