Skip to content

Commit

Permalink
Implement repr for pyodide/pyscript (#3651)
Browse files Browse the repository at this point in the history
* Implement repr for pyodide/pyscript

* Generalize
  • Loading branch information
philippjfr committed Jun 26, 2022
1 parent e39e409 commit 33df87c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
40 changes: 40 additions & 0 deletions panel/io/pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

from bokeh import __version__
from bokeh.document import Document
from bokeh.embed.elements import script_for_render_items
from bokeh.embed.util import standalone_docs_json_and_render_items
from bokeh.embed.wrappers import wrap_in_script_tag
from bokeh.io.doc import set_curdoc
from bokeh.protocol.messages.patch_doc import process_document_events
from js import JSON
Expand Down Expand Up @@ -92,10 +94,48 @@ def pysync(event):

pydoc.on_change(pysync)

async def _link_model(ref, doc):
from js import Bokeh
rendered = Bokeh.index.object_keys()
if ref not in rendered:
await asyncio.sleep(0.1)
await _link_model(ref, doc)
return
views = Bokeh.index.object_values()
view = views[rendered.indexOf(ref)]
_link_docs(doc, view.model.document)

#---------------------------------------------------------------------
# Public API
#---------------------------------------------------------------------

def render_script(obj, target):
"""
Generates a script to render the supplied object to the target.
Arguments
---------
obj: Viewable
Object to render into the DOM node
target: str
Target ID of the DOM node to render the object into.
"""
from js import document

from ..pane import panel as as_panel

doc = Document()
as_panel(obj).server_doc(doc, location=False)
docs_json, [render_item,] = standalone_docs_json_and_render_items(
doc.roots, suppress_callback_warning=True
)
for root in doc.roots:
render_item.roots._roots[root] = target
document.getElementById(target).classList.add('bk-root')
script = script_for_render_items(docs_json, [render_item])
asyncio.create_task(_link_model(doc.roots[0].ref['id'], doc))
return wrap_in_script_tag(script)

def serve(*args, **kwargs):
"""
Stub to replace Tornado based serve function.
Expand Down
8 changes: 8 additions & 0 deletions panel/viewable.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,14 @@ def __str__(self) -> str:
return self.__repr__()

def _repr_mimebundle_(self, include=None, exclude=None):
if state._is_pyodide:
from .io.pyodide import render_script
if hasattr(sys.stdout, '_out'):
target = sys.stdout._out # type: ignore
else:
raise ValueError("Could not determine target node to write to.")
return {'text/html': render_script(self, target)}, {}

loaded = panel_extension._loaded
if not loaded and 'holoviews' in sys.modules:
import holoviews as hv # type: ignore
Expand Down

0 comments on commit 33df87c

Please sign in to comment.