Skip to content

Commit

Permalink
Ensure a session context is present when widgets are closed (#171)
Browse files Browse the repository at this point in the history
  • Loading branch information
cpsievert authored Dec 18, 2024
1 parent b1d0bfe commit 63e1ea1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ All notable changes to shinywidgets will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [UNRELEASED]

* Fixed an issue where `@render_widget` would sometimes incorrectly render a new widget without removing the old one. (#167)

## [0.4.1] - 2024-12-17

* Fixed a Python 3.9 compatibility issue.
Expand Down
10 changes: 8 additions & 2 deletions shinywidgets/_shinywidgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from shiny import Session, reactive
from shiny.http_staticfiles import StaticFiles
from shiny.reactive._core import get_current_context
from shiny.session import get_current_session, require_active_session
from shiny.session import get_current_session, require_active_session, session_context

from ._as_widget import as_widget
from ._cdn import SHINYWIDGETS_CDN_ONLY, SHINYWIDGETS_EXTENSION_WARNING
Expand All @@ -37,6 +37,7 @@

if TYPE_CHECKING:
from typing import TypeGuard

from traitlets.traitlets import Instance


Expand Down Expand Up @@ -129,7 +130,12 @@ def _cleanup_session_state():
# If we're in a reactive context, close this widget when the context is invalidated
if has_current_context():
ctx = get_current_context()
ctx.on_invalidate(lambda: w.close())

def on_close():
with session_context(session):
w.close()

ctx.on_invalidate(on_close)

# Keep track of what session this widget belongs to (so we can close it when the
# session ends)
Expand Down

0 comments on commit 63e1ea1

Please sign in to comment.