-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
432 lines (340 loc) · 9.86 KB
/
index.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
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
// AutomationJS
// ------------
// v0.2.0
//
// Copyright (c) 2015 Jollen Chen, WoT.City Inc.
// Distributed under MIT license
//
// http://automationjs.com
/**
* Browserify
*/
var h = require('virtual-dom/h');
var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');
var VNode = require('virtual-dom/vnode/vnode');
var VText = require('virtual-dom/vnode/vtext');
var Backbone = require('backbone');
var _ = require('underscore');
/**
* Setup
*/
var convertHTML = require('html-to-vdom')({
VNode: VNode,
VText: VText
});
/*
* Prototype
*/
Function.prototype.extend = function(parent) {
_.extend(this.prototype, parent.prototype);
};
/*
* Class
*/
var Automation = function(options) {
return this.extend(options);
};
/**
* EventAggregator can be used to decouple various parts
* of an application through event-driven architecture.
*
* Borrowing this code from https://github.com/marionettejs/backbone.wreqr/blob/master/src/wreqr.eventaggregator.js
*/
Automation.EventAggregator = function () {
var EA = function(){};
// Copy the *extend* function used by Backbone's classes
EA.extend = Backbone.Model.extend;
// Copy the basic Backbone.Events on to the event aggregator
_.extend(EA.prototype, Backbone.Events);
return new EA();
};
/**
* Container
*
* The container to store, retrieve child elements.
* Borrowing this code from https://github.com/marionettejs/backbone.babysitter
*/
Automation.ChildElementContainer = function (context) {
// Container Constructor
// ---------------------
var Container = function() {
this._elements = [];
this._models = [];
this._vtrees = [];
this._channel = [];
};
// Container Methods
// -----------------
_.extend(Container.prototype, {
// Add an element to this container. Stores the element
// by `cid` and makes it searchable by the model
// cid (and model itself).
add: function(options){
var element = options.element
, model = options.model
, vtree = options.vtree
, channel = options.channel
, cid = options.cid;
// store the element and index by cid
this._elements[cid] = element;
// store the model and index by cid
this._models[cid] = model;
// store the virtual dom (vtree) and index by cid
this._vtrees[cid] = vtree;
// store the websocket server conntion
this._channel[cid] = channel;
this._updateLength();
return this;
},
// retrieve a element by its `cid` directly
findElementByCid: function(cid){
if (_.isObject(this._elements[cid]))
return this._elements[cid];
return null;
},
findVtreeByCid: function(cid) {
return this._vtrees[cid];
},
findModelByCid: function(cid) {
return this._models[cid];
},
updateVtreeByCid: function(cid, vtree) {
this._vtrees[cid] = vtree;
},
updateElementByCid: function(cid, element) {
this._elements[cid] = element;
},
// Remove a view by cid
remove: function(cid){
// remove the element from the container
delete this._elements[cid];
delete this._models[cid];
delete this._vtrees[cid];
delete this._channel[cid];
// update the length
this._updateLength();
return this;
},
// Fetch data of every element
fetch: function() {
_.each(this._models, function(model) {
var cid = model.get('cid');
model.fetch({
success: function(model, response, options) {
if (_.isFunction(model.parseJSON))
model.parseJSON(response);
}.bind(model)
});
}.bind(this));
},
// Call a method on every element in the container,
// passing parameters to the call method one at a
// time, like `function.call`.
call: function(method){
this.apply(method, _.tail(arguments));
},
// Apply a method on every element in the container,
// passing parameters to the call method one at a
// time, like `function.apply`.
apply: function(method, args){
_.each(this._elements, function(elem){
if (_.isFunction(elem[method])){
elem[method].apply(elem, args || []);
}
});
},
// Update the `.length` attribute on this container
_updateLength: function(){
this.length = _.size(this._elements);
}
});
// Borrowing this code from Backbone.Collection:
// http://backbonejs.org/docs/backbone.html#section-106
//
// Mix in methods from Underscore, for iteration, and other
// collection related features.
var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
'select', 'reject', 'every', 'all', 'some', 'any', 'include',
'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
'last', 'without', 'isEmpty', 'pluck'];
_.each(methods, function(method) {
Container.prototype[method] = function() {
var elements = _.values(this._elements);
var args = [elements].concat(_.toArray(arguments));
return _[method].apply(_, args);
};
});
// return the public API
return new Container();
}
// constructor
Automation.prototype.super = function(options) {
// data binding
this.el = options.el;
this.model = options.model;
this.templateFunc = options.template;
// private properties
this._count = 0;
this._handlers = [];
// constructor
this._container = new Automation.ChildElementContainer();
this._eventAggragator = new Automation.EventAggregator();
// core event handling
this._eventAggragator.on('forceUpdateAll', function() {
// update every model in the container
this._container.fetch();
}.bind(this));
};
// The boundary compositor of shadow DOM.
// It builds the new subtree and patch DOM.
Automation.prototype._composite = function(cid) {
var tree = this._container.findVtreeByCid(cid)
, element = this._container.findElementByCid(cid)
, model = this._container.findModelByCid(cid);
if (element === null)
return;
// create the new tree
var innerHtml = this.templateFunc( model.attributes )
.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'');
var newTree = convertHTML(innerHtml);
// composition
var patches = diff(tree, newTree);
element = patch(element, patches);
// update vtree
this._container.updateVtreeByCid(cid, newTree);
this._container.updateElementByCid(cid, element);
};
Automation.prototype._add = function(options) {
var model = new this.model();
// Data persistence
for(var prop in options) {
if(options.hasOwnProperty(prop))
model.set(prop, options[prop]);
}
// child ID is automatically increased
model.set('cid', this._count);
// bind model change event to boundary compositor
model.bind('change', function(model) {
var cid = model.get('cid');
this._composite(cid);
}.bind(this), model);
// 1. Get view and build the subtree (virtual DOM)
// - remove invalid characters
var innerHtml = this.templateFunc( model.attributes )
.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'');
var tree = convertHTML(innerHtml);
// 2. Create the list item (sub element)
var element = createElement(tree);
// 3: composition boundary
this.el.append(element);
// 4. real-time data push
// check if this model is a websocket
var wsUrl = ''
, wsServer = {};
if (_.isFunction(model.wsUrl))
wsUrl = model.wsUrl();
if (/^ws:\/\//.test(wsUrl) || /^wss:\/\//.test(wsUrl)) {
wsServer = this._createChannel(this._count, wsUrl, {
onopen: function() {
},
onclose: function() {
},
onerror: function() {
}
});
};
// 5. store this element
this._container.add({
vtree: tree,
element: element,
model: model,
cid: this._count,
});
this._count++;
return model;
};
Automation.prototype._createChannel = function(cid, url, cbs) {
// WebSocket object
var ws;
var onopen = function()
{
console.log('ws: onopen');
};
var onclose = function()
{
console.log('ws: onclose');
};
var onerror = function()
{
console.log('ws: onerror');
};
var onmessage = function(message) {
// we have already bind 'cid' at '_createChannel'
var cid = this.cid;
update(cid, JSON.parse(message.data));
};
var update = function(cid, options) {
// get data model by 'cid'
var model = this._container.findModelByCid(cid);
// update model
for(var prop in options) {
if(options.hasOwnProperty(prop))
model.set(prop, options[prop]);
}
if (_.isFunction(model.parseJSON))
model.parseJSON();
// notify View
model.trigger('notify.change');
// composite by 'cid'
this.composite(cid);
}.bind(this);
// Let us open a web socket
ws = new WebSocket(url);
if (typeof(cbs) === 'undefined' || cbs.onopen !== 'function')
cbs.onopen = onopen;
if (typeof(cbs) === 'undefined' || cbs.onclose !== 'function')
cbs.onclose = onclose;
if (typeof(cbs) === 'undefined' || cbs.onerror !== 'function')
cbs.onerror = onerror;
if (typeof(cbs) === 'undefined' || cbs.onmessage !== 'function')
cbs.onmessage = onmessage;
ws.onopen = cbs.onopen;
ws.onclose = cbs.onclose;
ws.onerror = cbs.onerror;
// onmessage should not be overrided
ws.onmessage = onmessage;
// bind 'cid'
ws.cid = cid;
return ws;
};
Automation.prototype.trigger = function(event) {
this._eventAggragator.trigger(event);
};
/**
* class extend
*/
Automation.prototype.extend = function(options) {
// element prototype
var EL = function(options) {
this.super(options);
};
EL.extend(Automation);
EL.prototype.constructor = EL;
EL.prototype.add = function(options) {
// super
var model = this._add(options);
return model;
};
EL.prototype.composite = function(cid) {
// super
this._composite(cid);
};
EL.prototype.createChannel = function(cid, cbs) {
// super
this._createChannel(cid, cbs);
};
return new EL(options);
};
module.exports = Automation;