Skip to content

Commit

Permalink
Only add/remove model from Document once
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr committed Feb 14, 2024
1 parent d35ad7a commit ad4c651
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
14 changes: 10 additions & 4 deletions panel/io/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from contextlib import contextmanager
from typing import (
TYPE_CHECKING, Any, Iterable, List, Optional,
TYPE_CHECKING, Any, Iterable, List, Optional, Set,
)

import numpy as np
Expand Down Expand Up @@ -92,27 +92,33 @@ def diff(
msg.add_buffer(buffer)
return msg

def remove_root(obj: Model, replace: Document | None = None) -> None:
def remove_root(obj: Model, replace: Document | None = None, skip: Set[Model] | None = None) -> None:
"""
Removes the document from any previously displayed bokeh object
"""
models = set()
for model in obj.select({'type': Model}):
if skip and model in skip:
continue
prev_doc = model.document
model._document = None
if prev_doc:
prev_doc.remove_root(model)
if replace:
model._document = replace
models.add(model)
return models

def add_to_doc(obj: Model, doc: Document, hold: bool = False):
def add_to_doc(obj: Model, doc: Document, hold: bool = False, skip: Set[Model] | None = None):
"""
Adds a model to the supplied Document removing it from any existing Documents.
"""
# Add new root
remove_root(obj)
models = remove_root(obj, skip=skip)
doc.add_root(obj)
if doc.callbacks.hold_value is None and hold:
doc.hold()
return models

def patch_cds_msg(model, msg):
"""
Expand Down
3 changes: 2 additions & 1 deletion panel/template/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ def _init_doc(
# Add all render items to the document
objs, models = [], []
sizing_modes = {}
tracked_models = set()
for name, (obj, tags) in self._render_items.items():

# Render root without pre-processing
Expand Down Expand Up @@ -241,7 +242,7 @@ def _init_doc(
objs.append(obj)
models.append(model)

add_to_doc(model, document, hold=bool(comm))
tracked_models |= add_to_doc(model, document, hold=bool(comm), skip=tracked_models)
document.on_session_destroyed(obj._server_destroy) # type: ignore

# Here we ensure that the preprocessor is run across all roots
Expand Down

0 comments on commit ad4c651

Please sign in to comment.