-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathcomponents.js
More file actions
526 lines (450 loc) · 18.1 KB
/
Copy pathcomponents.js
File metadata and controls
526 lines (450 loc) · 18.1 KB
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
define('aura/ext/components', function() {
'use strict';
return function(app) {
var ownProp = function(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
};
var core = app.core;
var _ = app.core.util._;
core.Components = core.Components || {};
/**
* Components registry
* @type {Object}
*/
var registeredComponents = {};
/**
* Components Callbacks
*/
var componentsCallbacks = {};
function invokeCallbacks(stage, fnName, context, args) {
var callbacks = componentsCallbacks[stage + ":" + fnName] || [];
var dfds = [];
app.core.util.each(callbacks, function(i, cb) {
if (typeof cb === 'function') {
dfds.push(cb.apply(context, args));
}
});
var ret = app.core.data.when.apply(undefined, dfds).promise();
return ret;
}
function invokeWithCallbacks(fn, context) {
var fnName;
if (typeof fn === 'string') {
fnName = fn;
fn = context[fnName] || function() {};
} else if (typeof fn.name === 'string') {
fnName = fn.name;
fn = fn.fn || function() {};
} else {
throw new Error("Error invoking Component with callbacks: ", context.options.name, ". first argument should be either the name of a function or of the form : { name: 'fnName', fn: function() { ... } } ");
}
var dfd = app.core.data.deferred();
var before, after, args = [].slice.call(arguments, 2);
before = invokeCallbacks("before", fnName, context, args);
var result;
before.then(function() {
var result = fn.apply(context, args);
return result;
}).then(function() {
invokeCallbacks("after", fnName, context, args).then(function() {
dfd.resolve(result);
}, dfd.reject);
}).fail(function(err) {
app.logger.error("Error in Component " + context.options.name + " " + fnName + " callback", err);
dfd.reject(err);
});
return dfd.promise();
}
/**
* The base Component constructor...
* @class Component
* @constructor
* @param {Object} options the options to init the component...
*/
function Component(options) {
var opts = _.clone(options);
/**
* The Components' options Object, passed to its constructor.
* TODO: Add explanation of how options are set from HTML API + which default options are
* set during the Component initialization.
*
* @property {Object} options
*/
this.options = _.defaults(opts || {}, this.options || {});
/**
* Internal, unique reference for a Component instance
*
* @property {String} _ref
*/
this._ref = opts._ref;
/**
* A cached jQuery object for the Components's element.
*
* @property {Object} $el
*/
this.$el = core.dom.find(opts.el);
invokeWithCallbacks('initialize', this, this.options);
return this;
}
/**
* Method called on Components' initialization.
*
* @method initialize
* @param {Object} options options Object passed on Component initialization
*/
Component.prototype.initialize = function() {};
/**
* A helper function to render markup and recursilvely start nested components.
*
* @method html
* @param {String} markup the markup to render in the component's root el
* @return {Component} the Component instance to allow methods chaining...
*/
Component.prototype.html = function(markup) {
var el = this.$el;
el.html(markup);
var self = this;
_.defer(function() {
self.sandbox.start(el, { reset: true });
});
return this;
};
/**
* A helper function to find matching elements within the Component's root element.
*
* @method $find
* @param {Selector | jQuery Object | Element} selector CSS selector or jQuery object.
* @return {jQuery Object}
*/
Component.prototype.$find = function(selector) {
return this.$el.find(selector);
};
/**
*
* @method invokeWithCallbacks
* @param {String} methodName the name of the method to invoke with callbacks
* @return {Promise} a Promise that will resolve to the return value of the original function invoked.
*/
Component.prototype.invokeWithCallbacks = function(methodName) {
invokeWithCallbacks(methodName, this);
};
// Stolen from Backbone 0.9.9 !
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && ownProp(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
core.util.extend(child, parent, staticProps);
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps) { core.util.extend(child.prototype, protoProps); }
child.__super__ = parent.prototype;
return child;
};
Component.extend = extend;
/**
* Component loader.
* @param {String} name The name of the Component to load
* @param {Object} options The options to pass to the new component instance.
* @return {Promise} A Promise that resolves to the loaded component instance.
*/
Component.load = function(name, opts) {
// TODO: Make it more simple / or break it down
// in several functions...
// it's too big !
var dfd = core.data.deferred(),
ref = opts.ref,
component,
ComponentConstructor,
el = opts.el;
opts._ref = core.util._.uniqueId(ref + '+');
var options = _.clone(opts);
app.logger.log("Start loading component:", name);
dfd.fail(function(err) {
app.logger.error("Error loading component:", name, err);
});
// Apply requirejs map / package configuration before the actual loading.
requirejs.config(options.require);
// Here, we require the component's package definition
requirejs([ref], function(componentDefinition) {
if (!componentDefinition) {
return dfd.reject("component " + ref + " Definition is empty !");
}
try {
// Ok, the component has already been loaded once, we should already have it in the registry
if (registeredComponents[ref]) {
ComponentConstructor = registeredComponents[ref];
} else {
if (componentDefinition.type) {
// If `type` is defined, we use a constructor provided by an extension ? ex. Backbone.
ComponentConstructor = core.Components[componentDefinition.type];
} else {
// Otherwise, we use the stock Component constructor.
ComponentConstructor = Component;
}
if (!ComponentConstructor) {
throw new Error("Can't find component of type '" + componentDefinition.type + "', did you forget to include the extension that provides it ?");
}
if (core.util._.isObject(componentDefinition)) {
ComponentConstructor = registeredComponents[ref] = ComponentConstructor.extend(componentDefinition);
}
}
var sandbox = app.sandboxes.create(opts._ref, { el: el });
sandbox.logger.setName("Component '" + name + "'(" + sandbox.logger.name + ')');
// Here we inject the sandbox in the component's prototype...
var ext = { sandbox: sandbox };
// If the Component is just defined as a function, we use it as its `initialize` method.
if (typeof componentDefinition === 'function') {
ext.initialize = componentDefinition;
}
ComponentConstructor = ComponentConstructor.extend(ext);
var newComponent = new ComponentConstructor(options);
// Sandbox owns its el and vice-versa
newComponent.$el.data('__sandbox_ref__', sandbox.ref);
var initialized = core.data.when(newComponent);
initialized.then(function(ret) { dfd.resolve(ret); });
initialized.fail(function(err) { dfd.reject(err); });
return initialized;
} catch(err) {
app.logger.error(err.message);
dfd.reject(err);
}
}, function(err) { dfd.reject(err); });
return dfd.promise();
};
/**
* Parses the component's options from its element's data attributes.
*
* @private
* @param {String|DomNode} el the element
* @param {String} namespace current Component's detected namespace
* @param {String} opts an Object containing the base Component's options to extend.
* @return {Object} An object that contains the Component's options
*/
function parseComponentOptions(el, namespace, opts) {
var options = _.clone(opts || {});
options.el = el;
options.require = {};
var name, data = core.dom.data(el);
// Here we go through all the data attributes of the element to build the options object
core.util.each(data, function(k, v) {
k = k.replace(new RegExp("^" + namespace), "");
k = k.charAt(0).toLowerCase() + k.slice(1);
if (k !== "component" && k !== 'widget') {
options[k] = v;
} else {
name = v;
}
});
return buildComponentOptions(name, options);
}
/**
* Parses the component's options from its element's data attributes.
*
* @private
* @param {String} name the Component's name
* @param {Object} opts an Object containing the base Component's options to extend.
* @return {Object} An object that contains the component's options
*/
function buildComponentOptions(name, options) {
var ref = name.split("@"),
componentName = core.util.decamelize(ref[0]),
componentSource = ref[1] || "default",
requireContext = requirejs.s.contexts._,
componentsPath = app.config.sources[componentSource] || "./aura_components";
// Register the component as a requirejs package...
// TODO: packages are not supported by almond, should we find another way to do this ?
options.name = componentName;
options.ref = '__component__$' + componentName + "@" + componentSource;
options.baseUrl = componentsPath + "/" + componentName;
options.require = options.require || {};
options.require.packages = options.require.packages || [];
options.require.packages.push({ name: options.ref, location: componentsPath + "/" + componentName });
return options;
}
/**!
* Returns a list of components.
* If the first argument is a String, it is considered as a DomNode reference
* We then parse its content to find aura-components inside of it.
*
* @static
* @param {Array|String} components a list of components or a reference to a root dom node
* @return {Array} a list of component with their options
*/
Component.parseList = function(components) {
var list = [];
if (Array.isArray(components)) {
_.map(components, function(w) {
var options = buildComponentOptions(w.name, w.options);
list.push({ name: w.name, options: options });
});
} else if (components && core.dom.find(components)) {
var appNamespace = app.config.namespace;
// Support for legacy data-*-widget
var selector = ["[data-aura-component]", "[data-aura-widget]"];
if (appNamespace) {
selector.push("[data-" + appNamespace + "-component]");
selector.push("[data-" + appNamespace + "-widget]");
}
selector = selector.join(",");
core.dom.find(selector, components || 'body').each(function() {
var ns = "aura";
if (appNamespace && (this.getAttribute('data-' + appNamespace +'-component') || this.getAttribute('data-' + appNamespace +'-widget'))) {
ns = appNamespace;
}
var options = parseComponentOptions(this, ns);
list.push({ name: options.name, options: options });
});
}
return list;
};
/**
* Actual start method for a list of components.
*
* @static
* @param {Array|String} components cf. `Component.parseList`
* @return {Promise} a promise that resolves to a list of started components.
*/
Component.startAll = function(components) {
var componentsList = Component.parseList(components);
var list = [];
core.util.each(componentsList, function(i, w) {
var ret = Component.load(w.name, w.options);
list.push(ret);
});
var loadedComponents = core.data.when.apply(undefined, list);
return loadedComponents.promise();
};
return {
name: 'components',
require: { paths: { text: 'bower_components/requirejs-text/text' } },
initialize: function(app) {
// Components 'classes' registry...
app.core.Components.Base = Component;
/**
* @class Aura
*/
/**
* Registers a function that will be executed before the associated
* Component method is called.
*
* Once registered, every time a component method will be called with the
* `invokeWithCallbacks` method the registered callbacks will execute accordingly.
*
* The callback functions can return a promise if required in order to
* postpone the execution of the called function up to when the all
* registered callbacks results are resolved.
*
* The arguments passed to the callbacks are the same than those which
* with the component will be called. The scope of the callback is
* the component instance itself, as per the component method.
*
* @method components.before
* @param {String} methodName eg. 'initialize', 'remove'
* @param {Function} fn actual function to run
*/
app.components.before = function(methodName, fn) {
var callbackName = "before:" + methodName;
registerComponentCallback(callbackName, fn);
};
/**
* Same as components.before, but executed after the method invocation.
*
* @method components.after
* @param {[type]} methodName eg. 'initialize', 'remove'
* @param {Function} fn actual function to run
*/
app.components.after = function(methodName, fn) {
var callbackName = "after:" + methodName;
registerComponentCallback(callbackName, fn);
};
// Actually registering the callbacks in the registry.
function registerComponentCallback(callbackName, fn) {
componentsCallbacks[callbackName] = componentsCallbacks[callbackName] || [];
componentsCallbacks[callbackName].push(fn);
}
/**
* Register a Component Type (experimental).
* Components type ca be used to encapsulate many custom components behaviours.
* They will be then used while declaring your components as follows:
*
* ```js
* define({
* type: 'myComponentType',
* // component declaration...
* });
* ```
*
* @method components.addType
* @param {String} type a string that will identify the component type.
* @param {Function} def A constructor the this component type
*/
app.components.addType = function(type, def) {
if (app.core.Components[type]) {
throw new Error("Component type " + type + " already defined");
}
app.core.Components[type] = Component.extend(def);
};
/**
* @class Sandbox
*/
/**
* Start method.
* This method takes either an Array of Components to start or or DOM Selector to
* target the element that will be parsed to look for Components to start.
*
* @method start
* @param {Array|DOM Selector} list Array of Components to start or parent node.
* @param {Object} options Available options: `reset` : if true, all current children
* will be stopped before start.
*/
app.sandbox.start = function (list, options) {
var event = ['aura', 'sandbox', 'start'].join(app.config.mediator.delimiter);
app.core.mediator.emit(event, this);
var children = this._children || [];
if (options && options.reset) {
_.invoke(this._children || [], 'stop');
children = [];
}
var self = this;
Component.startAll(list).done(function () {
var components = Array.prototype.slice.call(arguments);
_.each(components, function (w) {
w.sandbox._component = w;
w.sandbox._parent = self;
children.push(w.sandbox);
});
self._children = children;
});
return this;
};
},
/**
* When all of an application's extensions are finally loaded, the 'extensions'
* afterAppStart methods are then called.
*
* @method components.afterAppStart
* @param {Object} an Aura application object
*/
afterAppStart: function(app) {
if (app.config.components !== false && app.startOptions.components !== false) {
var el;
if (Array.isArray(app.startOptions.components)) {
el = core.dom.find('body');
} else {
el = core.dom.find(app.startOptions.components);
}
app.core.appSandbox = app.sandboxes.create(app.ref, { el: el });
app.core.appSandbox.start(app.startOptions.components);
}
}
};
};
});