From f1d580a27e3a32d73a5c825caf665018728df1cb Mon Sep 17 00:00:00 2001 From: "Maarten A. Breddels" Date: Fri, 14 Apr 2023 14:53:01 +0200 Subject: [PATCH] feat: implement output widget by using a display hook Similar to what is proposed in: https://github.com/jupyter-widgets/ipywidgets/issues/3253#issuecomment-932464163 --- solara/server/patch.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/solara/server/patch.py b/solara/server/patch.py index fbad6fba9..c5f898ea4 100644 --- a/solara/server/patch.py +++ b/solara/server/patch.py @@ -10,6 +10,7 @@ import ipykernel.kernelbase import IPython.display import ipywidgets +import ipywidgets.widgets.widget_output from IPython.core.interactiveshell import InteractiveShell from . import app, reload, settings @@ -228,6 +229,22 @@ def Thread_debug_run(self): _patched = False +def Output_enter(self): + self._flush() + + def hook(msg): + if msg["msg_type"] == "display_data": + self.outputs += ({"output_type": "display_data", "data": msg["content"]["data"], "metadata": msg["content"]["metadata"]},) + return None + return msg + + get_ipython().display_pub.register_hook(hook) + + +def Output_exit(self, exc_type, exc_value, traceback): + get_ipython().display_pub._hooks.pop() + + def patch(): global _patched if _patched: @@ -274,10 +291,11 @@ def patch(): # not sure why we cannot reproduce that locally ipykernel.kernelbase.Kernel.initialized = classmethod(kernel_initialized_dispatch) # type: ignore ipywidgets.widgets.widget.get_ipython = get_ipython - # TODO: find a way to actually monkeypatch get_ipython IPython.get_ipython = get_ipython - ipywidgets.widgets.widget_output.get_ipython = get_ipython + + ipywidgets.widgets.widget_output.Output.__enter__ = Output_enter + ipywidgets.widgets.widget_output.Output.__exit__ = Output_exit def model_id_debug(self: ipywidgets.widgets.widget.Widget): from ipyvue.ForceLoad import force_load_instance