Skip to content

Commit

Permalink
refactor: let target be a trait
Browse files Browse the repository at this point in the history
This way target can be updated, and works better in combination with
Reacton and Solara.
  • Loading branch information
maartenbreddels committed Oct 17, 2023
1 parent 8bc692e commit fb13a6a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
30 changes: 26 additions & 4 deletions ipypopout/popout_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class PopoutButton(v.VuetifyTemplate):
template_file = (__file__, "popout_button.vue")
kernel_id = traitlets.Unicode('').tag(sync=True)
target_model_id = traitlets.Unicode().tag(sync=True)
target = traitlets.Instance(ipywidgets.Widget, allow_none=True)
echo_available = traitlets.Bool(False).tag(sync=True)

is_displayed = traitlets.Bool(False).tag(sync=True)
Expand All @@ -48,17 +49,38 @@ class PopoutButton(v.VuetifyTemplate):
# See: https://developer.mozilla.org/en-US/docs/Web/API/Window/open#window_features
window_features = traitlets.Unicode('popup').tag(sync=True)

def __init__(self, target, **kwargs):
self.kernel_id = get_kernel_id()
self.target_model_id = target._model_id
self.window_name = target._model_id
def __init__(self, target=None, **kwargs):
kwargs = kwargs.copy()

if os.environ.get("JUPYTER_WIDGETS_ECHO") is None:
ipywidgets.widgets.widget.JUPYTER_WIDGETS_ECHO = True

self.echo_available = ipywidgets.widgets.widget.JUPYTER_WIDGETS_ECHO
if target is not None:
kwargs = {**kwargs, **{'target': target}}
super(PopoutButton, self).__init__(**kwargs)

@traitlets.observe('target')
def _on_target_change(self, change):
if change['new'] is not None:
self.target_model_id = change['new']._model_id
self.window_name = change['new']._model_id

@traitlets.default("target_model_id")
def _default_target_model_id(self):
if self.target is not None:
return self.target._model_id
return ""

@traitlets.default("window_name")
def _default_window_name(self):
return self.target_model_id or ""

@traitlets.default("kernel_id")
def _default_kernel_id(self):
return get_kernel_id()


def open_window(self):
if self.is_displayed:
self.send({
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/popout_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import ipypopout
import ipywidgets as widgets


def test_create_target():
box = widgets.VBox()
button = ipypopout.PopoutButton(target=box)
assert button.target_model_id == box._model_id
assert button.window_name == box._model_id

box2 = widgets.VBox()
button.target = box2
assert button.target_model_id == box2._model_id
assert button.window_name == box2._model_id

0 comments on commit fb13a6a

Please sign in to comment.