Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow nested parameterized objects on ReactiveHTML #2533

Merged
merged 7 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions panel/layout/tabs.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,25 +82,25 @@ def _process_close(self, ref, attr, old, new):
new = [old[i] for i in inds]
return old, new

def _comm_change(self, doc, ref, comm, attr, old, new):
def _comm_change(self, doc, ref, comm, subpath, attr, old, new):
if attr in self._changing.get(ref, []):
self._changing[ref].remove(attr)
return
if attr == 'tabs':
old, new = self._process_close(ref, attr, old, new)
if new is None:
return
super()._comm_change(doc, ref, comm, attr, old, new)
super()._comm_change(doc, ref, comm, subpath, attr, old, new)

def _server_change(self, doc, ref, attr, old, new):
def _server_change(self, doc, ref, subpath, attr, old, new):
if attr in self._changing.get(ref, []):
self._changing[ref].remove(attr)
return
if attr == 'tabs':
old, new = self._process_close(ref, attr, old, new)
if new is None:
return
super()._server_change(doc, ref, attr, old, new)
super()._server_change(doc, ref, subpath, attr, old, new)

def _update_active(self, *events):
for event in events:
Expand Down
37 changes: 33 additions & 4 deletions panel/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import bokeh.core.properties as bp
import param as pm
import bokeh

from bokeh.model import DataModel
from bokeh.models import ColumnDataSource, CustomJS, Model as BkModel
Expand All @@ -18,13 +19,37 @@
from .viewable import Viewable


class Parameterized(bokeh.core.property.bases.Property):
""" Accept a Parameterized object.

This property only exists to support type validation, e.g. for "accepts"
clauses. It is not serializable itself, and is not useful to add to
Bokeh models directly.

"""
def validate(self, value, detail=True):
super().validate(value, detail)

if isinstance(value, param.Parameterized):
return

msg = "" if not detail else f"expected param.Parameterized, got {value!r}"
raise ValueError(msg)



_DATA_MODELS = weakref.WeakKeyDictionary()

PARAM_MAPPING = {
pm.Array: lambda p, kwargs: bp.Array(bp.Any, **kwargs),
pm.Boolean: lambda p, kwargs: bp.Bool(**kwargs),
pm.CalendarDate: lambda p, kwargs: bp.Date(**kwargs),
pm.CalendarDateRange: lambda p, kwargs: bp.Tuple(bp.Date, bp.Date, **kwargs),
pm.ClassSelector: lambda p, kwargs: (
(bp.Instance(DataModel, **kwargs), [(Parameterized, create_linked_datamodel)])
if isinstance(p.class_, type) and issubclass(p.class_, param.Parameterized) else
bp.Any(**kwargs)
),
pm.Color: lambda p, kwargs: bp.Color(**kwargs),
pm.DataFrame: lambda p, kwargs: (
bp.ColumnData(bp.Any, bp.Seq(bp.Any), **kwargs),
Expand Down Expand Up @@ -105,7 +130,7 @@ def create_linked_datamodel(obj, root=None):
---------
obj: param.Parameterized
The Parameterized class to create a linked DataModel for.

Returns
-------
DataModel instance linked to the Parameterized object.
Expand All @@ -122,7 +147,7 @@ def create_linked_datamodel(obj, root=None):
_DATA_MODELS[cls] = model = construct_data_model(obj)
model = model(**dict(obj.param.get_param_values()))
_changing = []

def cb_bokeh(attr, old, new):
if attr in _changing:
return
Expand All @@ -131,7 +156,7 @@ def cb_bokeh(attr, old, new):
obj.param.set_param(**{attr: new})
finally:
_changing.remove(attr)

def cb_param(*events):
update = {
event.name: event.new for event in events
Expand All @@ -140,15 +165,19 @@ def cb_param(*events):
try:
_changing.extend(list(update))
model.update(**update)
tags = [tag for tag in model.tags if tag.startswith('__ref:')]
if root:
push_on_root(root.ref['id'])
elif tags:
ref = tags[0].split('__ref:')[-1]
push_on_root(ref)
finally:
for attr in update:
_changing.remove(attr)

for p in obj.param:
model.on_change(p, cb_bokeh)

obj.param.watch(cb_param, list(obj.param))

return model
Expand Down
2 changes: 1 addition & 1 deletion panel/models/reactive_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def handle_data(self, data):
match = match[2:-1]
if match.startswith('model.'):
continue
if match not in self.cls.param:
if match not in self.cls.param and '.' not in match:
params = difflib.get_close_matches(match, list(self.cls.param))
raise ValueError(f"{self.cls.__name__} HTML template references "
f"unknown parameter '{match}', similar parameters "
Expand Down
65 changes: 44 additions & 21 deletions panel/models/reactive_html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,32 +97,45 @@ export class ReactiveHTMLView extends PanelHTMLBoxView {
this.html = htmlDecode(this.model.html) || this.model.html
}

connect_signals(): void {
super.connect_signals()

this.connect(this.model.properties.children.change, async () => {
this.html = htmlDecode(this.model.html) || this.model.html
await this.rebuild()
this.invalidate_layout()
})
for (const prop in this.model.data.properties) {
this.connect(this.model.data.properties[prop].change, () => {
for (const node in this.model.children) {
if (this.model.children[node] == prop) {
let children = this.model.data[prop]
if (!isArray(children))
children = [children]
this._render_node(node, children)
this.invalidate_layout()
return
_recursive_connect(model: any, update_children: boolean, path: string): void {
for (const prop in model.properties) {
let subpath: string
if (path.length)
subpath = `${path}.${prop}`
else
subpath = prop
const obj = model[prop]
if (obj.properties != null)
this._recursive_connect(obj, true, subpath)
this.connect(model.properties[prop].change, () => {
if (update_children) {
for (const node in this.model.children) {
if (this.model.children[node] == prop) {
let children = model[prop]
if (!isArray(children))
children = [children]
this._render_node(node, children)
this.invalidate_layout()
return
}
}
}
if (!this._changing) {
this._update(prop)
this._update(subpath)
this.invalidate_layout()
}
})
}
}

connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.children.change, async () => {
this.html = htmlDecode(this.model.html) || this.model.html
await this.rebuild()
this.invalidate_layout()
})
this._recursive_connect(this.model.data, true, '')
this.connect(this.model.properties.events.change, () => {
this._remove_event_listeners()
this._setup_event_listeners()
Expand All @@ -132,13 +145,23 @@ export class ReactiveHTMLView extends PanelHTMLBoxView {

connect_scripts(): void {
const id = this.model.data.id
for (const prop in this.model.scripts) {
for (let prop in this.model.scripts) {
const scripts = this.model.scripts[prop]
let data_model = this.model.data
let attr: string
if (prop.indexOf('.') >= 0) {
const path = prop.split('.')
attr = path[path.length-1]
for (const p of path.slice(0, -1))
data_model = data_model[p]
} else {
attr = prop
}
for (const script of scripts) {
const decoded_script = htmlDecode(script) || script
const script_fn = this._render_script(decoded_script, id)
this._script_fns[prop] = script_fn
const property = this.model.data.properties[prop]
const property = data_model.properties[attr]
if (property == null)
continue
this.connect(property.change, () => {
Expand Down
Loading