Skip to content

Commit

Permalink
Add html mime type (#82)
Browse files Browse the repository at this point in the history
Add html MIME type to the rendered html
  • Loading branch information
alan-cooney authored Oct 23, 2023
1 parent 17afa01 commit c93ecbb
Show file tree
Hide file tree
Showing 3 changed files with 2,074 additions and 2,056 deletions.
4,098 changes: 2,057 additions & 2,041 deletions python/Demonstration.ipynb

Large diffs are not rendered by default.

26 changes: 14 additions & 12 deletions python/circuitsvis/utils/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import subprocess
import os
from pathlib import Path
from typing import Dict, Tuple, Union
from urllib import request
from uuid import uuid4

Expand Down Expand Up @@ -42,28 +43,29 @@ def __init__(self, local_src: str, cdn_src: str):
self.local_src = local_src
self.cdn_src = cdn_src

def _repr_html_(self) -> str:
def _repr_html_(self) -> Tuple[str, Dict]:
"""Jupyter/Colab HTML Representation
When Jupyter sees this method, it renders the HTML.
Returns:
str: HTML for Jupyter/Colab
HTML for Jupyter/Colab
"""
# Use local source if we're in dev mode
if is_in_dev_mode():
return self.local_src
# Use local source if we're in dev mode, or offline. Otherwise use the CDN.
src: str
if is_in_dev_mode() or not internet_on():
src = self.local_src
else:
src = self.cdn_src

# Use local source if we're offline
if not internet_on():
return self.local_src

# Otherwise use the CDN
return self.cdn_src
# Return html
mime = {"Content-Type": "text/html"}
return src, mime

def __html__(self) -> str:
"""Used by some tooling as an alternative to _repr_html_"""
return self._repr_html_()
# Just return the source code (not the MIME data), as some tools may not support this.
return self._repr_html_()[0]

def show_code(self) -> str:
"""Show the code as HTML source code
Expand Down
6 changes: 3 additions & 3 deletions python/circuitsvis/utils/tests/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_jupyter_renders(self):
html = RenderedHTML(src, src)

# Check the _repr_html_ method is defined (as Jupyter Lab displays this)
assert html._repr_html_() == src
assert html._repr_html_()[0] == src

def test_show_code(self):
src = "<p>Hi</p>"
Expand Down Expand Up @@ -85,10 +85,10 @@ def test_stringified_render_is_from_cdn(self, monkeypatch):
res = render("Hello", name="Bob")
assert str(res) == str(prod)

def test_jupyter_verson_is_from_local(self, monkeypatch):
def test_jupyter_version_is_from_local(self, monkeypatch):
monkeypatch.setattr(circuitsvis.utils.render, "uuid4", lambda: "mock")
monkeypatch.setattr(circuitsvis, "__version__", "1.0.0")

dev = render_local("Hello", name="Bob")
res = render("Hello", name="Bob")
assert res._repr_html_() == dev
assert res._repr_html_()[0] == dev

0 comments on commit c93ecbb

Please sign in to comment.