-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathVueRenderer.js
298 lines (268 loc) · 10.5 KB
/
VueRenderer.js
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/* eslint camelcase: ['error', {allow: ['v_model']}] */
import * as base from '@jupyter-widgets/base';
import { vueTemplateRender } from './VueTemplateRenderer'; // eslint-disable-line import/no-cycle
import { VueModel } from './VueModel';
import { VueTemplateModel } from './VueTemplateModel';
import Vue from './VueWithCompiler';
const JupyterPhosphorWidget = base.JupyterPhosphorWidget || base.JupyterLuminoWidget;
export function createObjectForNestedModel(model, parentView) {
let currentView = null;
let destroyed = false;
return {
mounted() {
parentView
.create_child_view(model)
.then(view => {
currentView = view;
// since create view is async, the vue component might be destroyed before the view is created
if(!destroyed) {
if(JupyterPhosphorWidget && (view.pWidget || view.luminoWidget || view.lmWidget)) {
JupyterPhosphorWidget.attach(view.pWidget || view.luminoWidget || view.lmWidget, this.$el);
} else {
console.error("Could not attach widget to DOM using Lumino or Phosphor. Fallback to normal DOM attach", JupyterPhosphorWidget, view.pWidget, view.luminoWidget, view.lmWidget);
this.$el.appendChild(view.el);
}
} else {
currentView.remove();
}
});
},
beforeDestroy() {
if (currentView) {
// In vue 3 we can use the beforeUnmount, which is called before the node is removed from the DOM
// In vue 2, we are already disconnected from the document at this stage, which phosphor does not like.
// In order to avoid an error in phosphor, we add the node to the body before removing it.
// (current.remove triggers a phosphor detach)
// To be sure we do not cause any flickering, we hide the node before moving it.
const widget = currentView.pWidget || currentView.luminoWidget || currentView.lmWidget;
widget.node.style.display = "none";
document.body.appendChild(widget.node)
currentView.remove();
} else {
destroyed = true;
}
},
render(createElement) {
return createElement('div', { style: { height: '100%' } });
},
};
}
// based on https://stackoverflow.com/a/58416333/5397207
function pickSerializable(object, depth=0, max_depth=2) {
// change max_depth to see more levels, for a touch event, 2 is good
if (depth > max_depth)
return 'Object';
const obj = {};
for (let key in object) {
let value = object[key];
if (value instanceof Node)
// specify which properties you want to see from the node
value = {id: value.id};
else if (value instanceof Window)
value = 'Window';
else if (value instanceof Object)
value = pickSerializable(value, depth+1, max_depth);
obj[key] = value;
}
return obj;
}
export function eventToObject(event) {
if (event instanceof Event) {
return pickSerializable(event);
}
return event;
}
export function vueRender(createElement, model, parentView, slotScopes) {
if (model instanceof VueTemplateModel) {
return vueTemplateRender(createElement, model, parentView);
}
if (!(model instanceof VueModel)) {
return createElement(createObjectForNestedModel(model, parentView));
}
const tag = model.getVueTag();
const elem = createElement({
data() {
return {
v_model: model.get('v_model'),
};
},
created() {
addListeners(model, this);
},
render(createElement2) {
const element = createElement2(
tag,
createContent(createElement2, model, this, parentView, slotScopes),
renderChildren(createElement2, model.get('children'), this, parentView, slotScopes),
);
updateCache(this);
return element;
},
}, { ...model.get('slot') && { slot: model.get('slot') } });
/* Impersonate the wrapped component (e.g. v-tabs uses this name to detect v-tab and
* v-tab-item) */
elem.componentOptions.Ctor.options.name = tag;
return elem;
}
function addListeners(model, vueModel) {
const listener = () => {
vueModel.$forceUpdate();
};
const use = key => key === '_events' || (!key.startsWith('_') && !['v_model'].includes(key));
model.keys()
.filter(use)
.forEach(key => model.on(`change:${key}`, listener));
model.on('change:v_model', () => {
if (model.get('v_model') !== vueModel.v_model) {
vueModel.v_model = model.get('v_model'); // eslint-disable-line no-param-reassign
}
});
}
function createAttrsMapping(model) {
const useAsAttr = key => model.get(key) !== null
&& !key.startsWith('_')
&& !['attributes', 'v_slots', 'v_on', 'layout', 'children', 'slot', 'v_model', 'style_', 'class_'].includes(key);
return model.keys()
.filter(useAsAttr)
.reduce((result, key) => {
result[key.replace(/_$/g, '').replace(/_/g, '-')] = model.get(key); // eslint-disable-line no-param-reassign
return result;
}, {});
}
function addEventWithModifiers(eventAndModifiers, content, slotScopes, obj, fn) { // eslint-disable-line no-unused-vars
/* Example Vue.compile output:
* (function anonymous() {
* with (this) {
* return _c('dummy', {
* on: {
* "[event]": function ($event) {
* if (!$event.type.indexOf('key') && _k($event.keyCode, "c", ...)
* return null;
* ...
* return [fn]($event)
* }
* }
* })
* }
* }
* )
*/
const { on } = Vue.compile(`<dummy @${eventAndModifiers}="${content || 'fn' }"></dummy>`)
.render.bind({
_c: (_, data) => data,
_k: Vue.prototype._k,
fn,
...(slotScopes || {}),
})();
return {
...obj,
...on,
};
}
function createEventMapping(model, parentView, slotScopes) {
return Object.entries(model.get('_events') || {})
.reduce((result, [eventAndModifiers, content]) => addEventWithModifiers(
eventAndModifiers,
content,
slotScopes,
result,
(e) => {
model.send({
event: eventAndModifiers,
data: eventToObject(e),
},
model.callbacks(parentView));
},
), {});
}
function createSlots(createElement, model, vueModel, parentView, slotScopes) {
const slots = model.get('v_slots');
if (!slots) {
return undefined;
}
return slots.map(slot => ({
key: slot.name,
...!slot.variable && { proxy: true },
fn(slotScope) {
return renderChildren(createElement,
Array.isArray(slot.children) ? slot.children : [slot.children],
vueModel, parentView, {
...slotScopes,
...slot.variable && { [slot.variable]: slotScope },
});
},
}));
}
function getScope(value, slotScopes) {
const parts = value.split('.');
return parts
.slice(1)
.reduce(
(scope, name) => scope[name],
slotScopes[parts[0]],
);
}
function getScopes(value, slotScopes) {
return typeof value === 'string'
? getScope(value, slotScopes)
: Object.assign({}, ...value.map(v => getScope(v, slotScopes)));
}
function slotUseOn(model, slotScopes) {
const vOnValue = model.get('v_on');
return vOnValue && getScopes(vOnValue, slotScopes);
}
function createContent(createElement, model, vueModel, parentView, slotScopes) {
const htmlEventAttributes = model.get('attributes') && Object.keys(model.get('attributes')).filter(key => key.startsWith('on'));
if (htmlEventAttributes && htmlEventAttributes.length > 0) {
throw new Error(`No HTML event attributes may be used: ${htmlEventAttributes}`);
}
const scopedSlots = createSlots(createElement, model, vueModel, parentView, slotScopes);
return {
on: { ...createEventMapping(model, parentView, slotScopes), ...slotUseOn(model, slotScopes) },
...model.get('style_') && { style: model.get('style_') },
...model.get('class_') && { class: model.get('class_') },
...scopedSlots && { scopedSlots: vueModel._u(scopedSlots) },
attrs: {
...createAttrsMapping(model),
...model.get('attributes') && model.get('attributes'),
},
...model.get('v_model') !== '!!disabled!!' && {
model: {
value: vueModel.v_model,
callback: (v) => {
model.set('v_model', v === undefined ? null : v);
model.save_changes(model.callbacks(parentView));
},
expression: 'v_model',
},
},
};
}
function renderChildren(createElement, children, vueModel, parentView, slotScopes) {
if (!vueModel.childCache) {
vueModel.childCache = {}; // eslint-disable-line no-param-reassign
}
if (!vueModel.childIds) {
vueModel.childIds = []; // eslint-disable-line no-param-reassign
}
const childViewModels = children.map((child) => {
if (typeof (child) === 'string') {
return child;
}
vueModel.childIds.push(child.cid);
if (vueModel.childCache[child.cid]) {
return vueModel.childCache[child.cid];
}
const vm = vueRender(createElement, child, parentView, slotScopes);
vueModel.childCache[child.cid] = vm; // eslint-disable-line no-param-reassign
return vm;
});
return childViewModels;
}
function updateCache(vueModel) {
Object.keys(vueModel.childCache)
.filter(key => !vueModel.childIds.includes(key))
// eslint-disable-next-line no-param-reassign
.forEach(key => delete vueModel.childCache[key]);
vueModel.childIds = []; // eslint-disable-line no-param-reassign
}