/
__init__.py
160 lines (133 loc) · 5.19 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""
Editable template
"""
from __future__ import annotations
import pathlib
from typing import (
TYPE_CHECKING, ClassVar, Dict, Optional,
)
import param
from bokeh.models import CustomJS
from ...config import config
from ...reactive import ReactiveHTML
from ..vanilla import VanillaTemplate
if TYPE_CHECKING:
from bokeh.document import Document
from pyviz_comms import Comm
from ...io.location import Location
class TemplateEditor(ReactiveHTML):
"""
Component responsible for watching the template for changes and syncing
the current layout state with Python.
"""
layout = param.List()
_scripts = {
'render': """
var grid = window.muuriGrid;
function save_layout() {
const layout = [];
for (const item of grid.getItems()) {
const el = item.getElement();
let height = el.style.height.slice(null, -2);
if (!height) {
const {top} = item.getMargin();
height = item.getHeight()-top;
} else {
height = parseFloat(height);
}
let width;
if (el.style.width.length) {
width = parseFloat(el.style.width.split('(')[1].split('%')[0]);
} else {
width = 100;
}
layout.push({
id: el.getAttribute('data-id'),
width: width,
height: height,
visible: item.isVisible(),
})
}
data.layout = layout;
}
grid.on('layoutEnd', save_layout)
if (window.resizeableGrid) {
window.resizeableGrid.on('resizeend', save_layout)
}
"""
}
class EditableTemplate(VanillaTemplate):
"""
The `EditableTemplate` is a list based template with a header, sidebar, main and modal area.
The template allow interactively dragging, resizing and hiding components on a grid.
The template builds on top of Muuri and interact.js.
Reference: https://panel.holoviz.org/reference/templates/EditableTemplate.html
:Example:
>>> pn.template.EditableTemplate(
... site="Panel", title="EditableTemplate",
... sidebar=[pn.pane.Markdown("## Settings"), some_slider],
... main=[some_python_object]
... ).servable()
"""
editable = param.Boolean(default=True, doc="""
Whether the template layout should be editable.""")
layout = param.Dict(default={}, allow_refs=True, doc="""
The layout definition of the template indexed by the id of
each component in the main area.""")
local_save = param.Boolean(default=True, doc="""
Whether to enable saving to local storage.""")
_css = [
pathlib.Path(__file__).parent.parent / 'vanilla' / "vanilla.css",
pathlib.Path(__file__).parent / 'editable.css'
]
_resources: ClassVar[Dict[str, Dict[str, str]]] = {
"css": {"lato": "https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext"},
"js": {
"interactjs": f"{config.npm_cdn}/interactjs@1.10.19/dist/interact.min.js",
"muuri": f"{config.npm_cdn}/muuri@0.9.5/dist/muuri.min.js",
"web-animation": f"{config.npm_cdn}/web-animations-js@2.3.2/web-animations.min.js"
},
}
_template = pathlib.Path(__file__).parent / "editable.html"
def _update_vars(self):
ids = {id(obj): next(iter(obj._models)) for obj in self.main}
self._render_variables['layout'] = layout = {
ids[iid]: dict(item, id=ids[iid]) for iid, item in self.layout.items()
}
self._render_variables['muuri_layout'] = list(layout.values())
self._render_variables['editable'] = self.editable
self._render_variables['local_save'] = self.local_save
self._render_variables['loading_spinner'] = config.loading_spinner
super()._update_vars()
def _init_doc(
self, doc: Optional[Document] = None, comm: Optional[Comm] = None,
title: Optional[str] = None, notebook: bool = False,
location: bool | Location = True
):
doc = super()._init_doc(doc, comm, title, notebook, location)
doc.js_on_event('document_ready', CustomJS(code="""
window.muuriGrid.getItems().map(item => scroll(item.getElement()));
for (const root of roots) {
root.sizing_mode = 'stretch_both';
if (root.children) {
for (const child of root) {
child.sizing_mode = 'stretch_both'
}
}
}
window.muuriGrid.refreshItems();
window.muuriGrid.layout();
""", args={'roots': [root for root in doc.roots if 'main' in root.tags]}))
return doc
@param.depends('editable', watch=True, on_init=True)
def _add_editor(self) -> None:
if not self.editable:
return
editor = TemplateEditor()
editor.param.watch(self._sync_positions, 'layout')
self._render_items['editor'] = (editor, [])
def _sync_positions(self, event):
ids = {mid: id(obj) for obj in self.main for mid in obj._models}
self.layout.clear()
self.layout.update({ids[item['id']]: item for item in event.new})
self.param.trigger('layout')