-
Notifications
You must be signed in to change notification settings - Fork 2
/
remoting-controller.html
529 lines (450 loc) · 24.9 KB
/
remoting-controller.html
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<link rel="import" href="../polymer/polymer-element.html">
<dom-module id="remoting-controller">
<template>
<slot></slot>
</template>
<script>
(function() {
// Internal methods which are not added to the class
// TODO: This methos are also in use in the AngularJS version ... they should be moved to the core!
/**
* Checks whether an object exists or not.
*
* @param {any} object The object which should be checked
*/
const exists = function (object) {
return typeof object !== 'undefined' && object !== null;
};
/**
* Compares two arrays.
*
* @param {any[]} array1 Array
* @param {any[]} array2 Array
*/
const deepEqual = function (array1, array2) {
if (array1 === array2 || (!exists(array1) && !exists(array2))) {
return true;
}
if (exists(array1) !== exists(array2)) {
return false;
}
const n = array1.length;
if (array2.length !== n) {
return false;
}
for (let i = 0; i < n; i++) {
if (array1[i] !== array2[i]) {
return false;
}
}
return true;
};
/**
* Injects one array into the other at a given index.
*
* @param {any[]} baseArray The array to insert the other array to
* @param {number} startIndex The index at which the array should be added
* @param {any[]} insertArray The array which should be added
*/
const injectArray = function (baseArray, startIndex, insertArray) {
baseArray.splice.apply(baseArray, [startIndex, 0].concat(insertArray));
};
/**
* Caluclates a path for a bean and stores it in a map.
*
* @param {Map} map Map to store the path
* @param {string} path current path
* @param {any} bean current bean
*/
const calculateBeanPath = function(map, path, bean) {
if (!exists(bean)) {
return;
}
map.set(bean, path);
if (Array.isArray(bean)) {
for (let i = 0; i < bean.length; i++) {
const currentName = path + '.' + i;
const value = bean[i];
calculateBeanPath(map, currentName, value);
}
} else if (typeof bean === 'object') {
const keys = Object.keys(bean);
for (let i = 0; i < keys.length; i++) {
const currentName = path + '.' + keys[i];
const key = keys[i];
const value = bean[key];
calculateBeanPath(map, currentName, value);
}
}
}
/**
* Clears the given map and calculates the Polymer paths for a given model into the map.
*
* @param {Map} map Map to store the path
* @param {any} model the model
*/
const calculateBeanPathForModel = function(map, model) {
map.clear();
calculateBeanPath(map, 'model', model);
}
/**
* The `remoting-controller` element creates a connection between Polymer and a controller of the Rico remoting.
*
* ~~~html
* <remoting-controller name="TodoController" model="{{todos}}"></remoting-controller>
* ~~~
*
* The `remoting-controller` sends events after creation and destruction.
* ~~~html
* <remoting-controller name="TodoController" model="{{todos}}" on-postconstruct="myMethod" on-postdestroyed="myOtherMethod"></remoting-controller>
* ~~~
*
* The `remoting-controller` sends events after been added to or removed from the document.
* ~~~html
* <remoting-controller name="TodoController" model="{{todos}}" on-connect="myMethod" on-disconnect="myOtherMethod"></remoting-controller>
* ~~~
*
* The `remoting-controller` can be used as not managed version. For that case you have to invoke the create() and destroy() methods on your own.
* ~~~html
* <remoting-controller name="TodoController" model="{{todos}}" not-managed></remoting-controller>
* ~~~
*
* @customElement
* @polymer
*/
class RemotingController extends Polymer.Element {
constructor() {
super();
this._onBeanUpdate = this._onBeanUpdate.bind(this);
this._onArrayUpdate = this._onArrayUpdate.bind(this);
this._handleControllerCreated = this._handleControllerCreated.bind(this);
this._handleControllerDestroyed = this._handleControllerDestroyed.bind(this);
/** Instance of the remoting controller proxy. */
this._controller = null;
/** State of the initialization. */
this._initialized = false;
/** Interal version of the remoting client context. */
this._internalClientContext = null;
/** Internal list of object with unsubscribe method which must be called when destroying the controller. */
this._unsubscribeFromBeanManager = [];
/** Bean to Polymer Path mapping. */
this._beanToPath = new Map();
}
static get is() {
return "remoting-controller"
}
static get properties() {
return {
/** The name of the controller which is used to identify the remoting controller type. */
name: String,
/** The model of the controller. It will be updated by the Rico remoting layer based on the synchronisation between client and server. */
model: {
type: Object,
notify: true
},
/** This property allows to disable the self-management of the component. If it is set (`true`) the component must be initialized and destroyed by hand with `create()` and `destroy()`! */
notManaged: {
type: Boolean,
value: false
}
}
}
get destroyed(){
return destroyed;
}
/**
* Provides an extended implementation of the standard Custom Elements `connectedCallback`.
*
* This method will be called if this element is added to a document.
*
* If this is a managed component, this method will create the internal Platform Controller if there is already a remoting client context.
* Hint: For a managed component, the `window.clientContext` MUST be created before the `remoting-controller` is added to a document.
*/
connectedCallback() {
RemotingController.LOGGER.debug(this.name, 'Conntected to document.');
super.connectedCallback();
const managed = !this.get('notManaged');
if (managed) {
this._internalClientContext = window.clientContext;
if (exists(this._internalClientContext)) {
this._createController();
} else {
RemotingController.LOGGER.error('Connected managed Remoting Controller component without internal Controller! Client context not found!');
}
}
const event = new CustomEvent('connected', {detail: this, bubbles: true, composed: true});
this.dispatchEvent(event);
}
/**
* Provides an implementation which is called when the element is removed from a document.
*
* If the Remoting Controller is managed, this method will also destroy the internal remoting controller proxy.
*/
disconnectedCallback() {
RemotingController.LOGGER.debug(this.name, 'Disconnected from document.');
super.disconnectedCallback();
const managed = !this.get('notManaged');
if (managed) {
if (exists(this._controller)) {
this._destroyController();
} else {
if (this._initialized) {
RemotingController.LOGGER.error('Disconnected managed Remoting Controller component! No internal Controller found!');
} else {
RemotingController.LOGGER.warn('Disconnected managed Remoting Controller component! Was not initialized yet.');
}
}
}
const event = new CustomEvent('disconnected', {detail: this, bubbles: true, composed: true});
this.dispatchEvent(event);
}
/**
* Creates the internal controller proxy.
*
* @returns {Promise} Promise which will be resolved after the creation of the internal controller proxy
*/
create() {
const self = this;
const notManaged = this.get('notManaged');
return new Promise(function(resolve, reject) {
if (notManaged) {
self._internalClientContext = window.clientContext;
self.addEventListener('postconstruct', function() {
resolve();
});
if (exists(self._internalClientContext)) {
self._createController();
} else {
RemotingController.LOGGER.error(self.name, 'Cannot create managed Remoting Controller Component. Client context not found!');
reject('Cannot create managed Remoting Controller Component. Client context not found!');
}
} else {
RemotingController.LOGGER.error(self.name, 'Cannot invoke create() method for a managed Controller');
reject('Cannot invoke create() method for a managed Controller');
}
});
}
/**
* Destroys the internal controller proxy
*
* @returns {Promise} Promise which will be resolved after the destruction of the internal controller proxy
*/
destroy() {
const self = this;
const notManaged = this.get('notManaged');
return new Promise(function(resolve, reject) {
if (notManaged) {
self.addEventListener('postdestroyed', function() {
resolve();
});
if (exists(self._controller)) {
self._destroyController();
} else {
RemotingController.LOGGER.error(self.name, 'Cannot invoke destroy() method for a managed Controller');
reject('Cannot invoke destroy() method for a managed Controller');
}
} else {
RemotingController.LOGGER.error(self.name, 'Cannot invoke destroy() method for a managed Controller');
reject('Cannot invoke destroy() method for a managed Controller');
}
});
}
/**
* Invokes an action on the server side controller with given name and parameters.
*
* @param {string} name Name of the action. MUST match an action name on the server side
* @param {any[]} params Array of parameters for the action
*
* @returns {Promise} Promise which will be resolved the action was invoked on the server, or will be rejected on error.
*/
invoke(name, params) {
RemotingController.LOGGER.debug(this.name, 'Invoke action called with', name, params);
if (exists(this._controller)) {
return this._controller.invoke(name, params)
} else {
RemotingController.LOGGER.error(this.name, 'No controller found. Cannot invoke action:', name, 'Parameters:', params);
}
}
/**
* Handles model changes received from the Polymer observers.
*
* @param {any} changeRecord The changes made to the model
*/
_modelChanged(changeRecord) {
if (changeRecord) {
const { value, base, path } = changeRecord;
const pathSegments = Polymer.Path.split(path);
let arrayChange = false;
const hasSplices = path.indexOf('.splices', path.length - '.splices'.length) !== -1;
const hasLength = path.indexOf('.length', path.length - '.length'.length) !== -1;
// Check for real array
if (hasSplices || hasLength) {
const currentPath = Polymer.Path.normalize([...pathSegments].splice(0, pathSegments.length-1));
const val = this.get(currentPath);
arrayChange = Array.isArray(val);
}
RemotingController.LOGGER.debug(this.name, 'Model changed', 'Path:', path, 'Value:', value, 'Is Array change:', arrayChange);
if (arrayChange) {
if (value.indexSplices && !hasLength) {
for (let i = 0; i < value.indexSplices.length; i++) {
const position = pathSegments.length-2;
const splice = value.indexSplices[i];
const startIndex = splice.index;
const removedItems = splice.removed;
const addedCount = splice.addedCount;
const propertyName = pathSegments[position];
const currentPath = Polymer.Path.normalize([...pathSegments].splice(0, position));
const bean = this.get(currentPath);
RemotingController.LOGGER.trace(this.name, 'Bean:', bean, 'Removed:', removedItems);
this._internalClientContext.beanManager.notifyArrayChange(bean, propertyName, startIndex, addedCount, removedItems);
}
}
} else {
if (pathSegments.length > 1) {
// subproperty changed
const position = pathSegments.length-1;
const propertyName = pathSegments[position];
const currentPath = Polymer.Path.normalize([...pathSegments].splice(0, position));
const bean = this.get(currentPath);
RemotingController.LOGGER.trace(this.name, 'Bean:', bean, 'Value:', value);
if (bean) {
this._internalClientContext.beanManager.notifyBeanChange(bean, propertyName, value);
}
} else {
// root property changed
const propertyName = pathSegments[0];
const currentPath = Polymer.Path.normalize(pathSegments);
const bean = this.get(currentPath);
RemotingController.LOGGER.trace(this.name, 'Bean:', bean, 'Value:', value);
if (bean) {
this._internalClientContext.beanManager.notifyBeanChange(bean, propertyName, value);
}
}
}
}
}
/**
* Handles bean updates from the Rico remoting layer.
*
* @param {any} bean The bean which was changed
* @param {string} propertyName The name of the property which was changed
* @param {any} newValue The new value of the property
* @param {any} oldValue the old value of the property
*/
_onBeanUpdate(bean, propertyName, newValue, oldValue) {
RemotingController.LOGGER.trace(this.name, 'Updating bean', bean, 'property name:', propertyName, 'new value:', newValue, 'old value:', oldValue, 'initialized', this._initialized);
if (oldValue === newValue) {
RemotingController.LOGGER.trace(this.name, 'Received bean update for property ', propertyName, ' without any change');
return;
}
if (this._initialized) {
const beanPath = this._beanToPath.get(bean);
if (exists(beanPath)) {
const currentPath = Polymer.Path.normalize([beanPath, propertyName]);
this.set(currentPath, newValue);
if ((Array.isArray(newValue) && newValue.length === 0) || newValue == null) {
// Will remove empty arrays or removed beans
calculateBeanPathForModel(this._beanToPath, this.model);
}
} else {
bean[propertyName] = newValue;
}
} else {
bean[propertyName] = newValue;
}
}
/**
* Handles array upadates from the Rico remoting layer (e.g. `ObservableList`).
*/
_onArrayUpdate(bean, propertyName, index, deletedElements, newElements) {
RemotingController.LOGGER.trace(this.name, 'Updating array bean', bean, 'property name:', propertyName, 'index:', index, 'deletedElements:', deletedElements, 'newElements:', newElements);
const array = bean[propertyName];
const oldElements = [bean[propertyName][index]];
if (deepEqual(newElements, oldElements)) {
RemotingController.LOGGER.trace(this.name, 'Will not add equal elements');
return;
}
if (this._initialized) {
const beanPath = this._beanToPath.get(bean);
if (exists(beanPath)) {
const currentPath = Polymer.Path.normalize([beanPath, propertyName]);
const currentValue = this.get(currentPath);
if (currentValue) {
const result = this.splice(currentPath, index, deletedElements, ...newElements);
if (result) {
calculateBeanPathForModel(this._beanToPath, this.model);
}
}
} else {
RemotingController.LOGGER.error(this.name, 'Bean not found in model!', bean, propertyName);
}
} else {
injectArray(array, index, newElements);
}
}
/**
* Handles the destruction of a remoting controller.
*
* This method resets the model.
*/
_handleControllerDestroyed() {
RemotingController.LOGGER.debug(this.name, 'Remoting controller destroyed');
const event = new CustomEvent('postdestroyed', {detail: this, bubbles: true, composed: true});
this.dispatchEvent(event);
}
/**
* Handles the creation of a remoting controller.
*
* @param {object} controllerProxy The `ControllerProxy`
*/
_handleControllerCreated(controllerProxy) {
RemotingController.LOGGER.debug(this.name, 'Remoting controller created', controllerProxy.getId(), controllerProxy);
controllerProxy.onDestroyed(this._handleControllerDestroyed);
this._controller = controllerProxy;
let internalModel = this._controller.getModel();
this.set('model', internalModel);
calculateBeanPathForModel(this._beanToPath, internalModel);
this._initialized = true;
const event = new CustomEvent('postconstruct', {detail: this, bubbles: true, composed: true});
this.dispatchEvent(event);
}
/**
* Creates a controller and registers the listeners for bean updates.
*/
_destroyController() {
RemotingController.LOGGER.debug(this.name, 'Destroy controller');
for (let i = 0; i < this._unsubscribeFromBeanManager.length; i++) {
const handler = this._unsubscribeFromBeanManager[i];
handler.unsubscribe();
}
this.set('model', {});
this._initialized = false;
this._beanToPath.clear();
this._unsubscribeFromBeanManager = [];
this._controller.destroy();
this._controller = null;
}
/**
* Creates a controller and registers the listeners for bean updates.
*/
_createController() {
this._createMethodObserver('_modelChanged(model.*)', false);
RemotingController.LOGGER.info('Creating remoting controller', this.name);
// Register callbacks for the bean manager and store the result for unsubscribe...
const onBeanUpdateHandlerResult = this._internalClientContext.beanManager.onBeanUpdate(this._onBeanUpdate);
this._unsubscribeFromBeanManager.push(onBeanUpdateHandlerResult);
const onArrayUpdatedHandlerResult = this._internalClientContext.beanManager.onArrayUpdate(this._onArrayUpdate);
this._unsubscribeFromBeanManager.push(onArrayUpdatedHandlerResult);
this._internalClientContext.createController(this.name).then(this._handleControllerCreated);
}
}
if (!exists(window.dolphin)) {
throw new Error('No Rico remoting client found in "window" global. Please load Rico remoting first.');
}
/** Default logger for the Controller. */
RemotingController.LOGGER = window.dolphin.LoggerFactory.getLogger('RemotingController');
// Register the element
customElements.define(RemotingController.is, RemotingController);
})();
</script>
</dom-module>