11import uuid
2-
32from typing import Any
3+ from urllib .parse import urlsplit , urlunsplit
4+ from IPython import display as _ipy_display
45
56
67def display (kind : str , * args : Any , ** kwargs : Any ) -> Any :
@@ -18,31 +19,52 @@ def display(kind: str, *args: Any, **kwargs: Any) -> Any:
1819class JupyterWigdet :
1920 """Output for IDOM within a Jupyter Notebook."""
2021
21- _shown = False
22- __slots__ = "_url"
23- _script = """
24- import React from '{url}/web-modules/react.js';
25- import ReactDOM from '{url}/web-modules/react-dom.js';
26- import Layout from '{url}/js/idom-layout';
27-
28- function IdomWidgetMount(endpoint, mountId) {
29- const mount = document.getElementById(mountId);
30- const element = React.createElement(Layout, {{endpoint: endpoint}})
31- ReactDOM.render(element, mount);
32- };
33- """
22+ _idom_server_exists_displayed = False
23+ __slots__ = ("_ws" , "_http" )
24+
25+ def __init__ (self , url : str , secure = True ) -> None :
26+ uri = urlunsplit (("" ,) + urlsplit (url )[1 :])
27+ if uri .endswith ("/" ):
28+ uri = uri [:- 1 ]
29+ if secure :
30+ ws_proto = "wss"
31+ http_proto = "https"
32+ else :
33+ ws_proto = "ws"
34+ http_proto = "http"
35+ self ._ws = ws_proto + ":" + uri
36+ self ._http = http_proto + ":" + uri
37+ if not type (self )._idom_server_exists_displayed :
38+ _ipy_display .display_html (
39+ "<script>document.idomServerExists = true;</script>" , raw = True ,
40+ )
41+ _ipy_display .clear_output (wait = True )
42+ type(self )._idom_server_exists_displayed = True
3443
35- def __init__ (self , url : str ) -> None :
36- self ._url = url
44+ def _script (self , mount_id ):
45+ return f"""
46+ <script type="module">
47+ // we want to avoid making this request (in case of CORS)
48+ // unless we know an IDOM server is expected to respond
49+ if (document.idomServerExists) {{
50+ import("{ self ._http } /client/core_modules/layout.js").then(
51+ module => {{
52+ module.renderLayout(
53+ document.getElementById("{ mount_id } "), "{ self ._ws } /stream"
54+ )
55+ }}
56+ )
57+ }}
58+ </script>
59+ """
3760
3861 def _repr_html_ (self ) -> str :
3962 """Rich HTML display output."""
4063 mount_id = uuid .uuid4 ().hex
4164 return f"""
4265 <div id="{ mount_id } "/>
43- { '' if JupyterWigdet ._shown else '<script>' + self ._script + '</script>' }
44- <script>window.IdomWidgetMount("{ self ._url } ", "{ mount_id } ")</script>
66+ { self ._script (mount_id )}
4567 """
4668
4769 def __repr__ (self ) -> str :
48- return "%s(%r)" % (type (self ).__name__ , self ._url )
70+ return "%s(%r)" % (type (self ).__name__ , self ._http )
0 commit comments