-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcore.js
687 lines (608 loc) · 18.6 KB
/
core.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @namespace core
* @author Sergiusz Struminski <[email protected]>
* @author Pawel Sierszen <[email protected]>
*/
(function core(global) {
'use strict';
/**
* Public object.
* @type {object}
*/
var publicAPI = {},
/**
* Document element.
* @type {object}
*/
document = global.document,
/**
* Head element.
* @type {HTMLHeadElement}
*/
head = document.getElementsByTagName('head')[0],
/**
* Internal object cache
* @type {object}
*/
modules = {},
/**
* Internal config
* @type {object}
*/
cfg = {
/**
* Default path to modules.
* @type {string}
*/
defaultPath: './js/',
/**
* Path to core modules.
* @type {string}
*/
basePath: null,
/**
* Path to application modules.
* @type {string}
*/
modulePath: null
};
/**
* Generic Module class.
* @private
*/
function Module(name) {
// Module name.
this.name = name;
return;
}
/**
* Returns correct path for modules.
* @private
* @param {string} data Current path.
* @return {string} New path.
*/
function getPath(data) {
var index = data.lastIndexOf('/'),
path = data.substr(0, index + 1);
return path || './';
}
/**
* Have all requires been sorted already?
* @private
* @param {string[]} requires Requires.
* @param {string[]} sorted Sorted requires.
* @return {boolean} result.
*/
function areSorted(requires, sorted) {
var i = 0,
depsLen = requires.length,
result = true;
for (i = 0; i < depsLen; i += 1) {
// Has mod been sorted already?
result = result && (sorted.indexOf(requires[i]) !== -1);
}
return result;
}
/**
* Sort modules by requires (dependents last),
* returning sorted list of module names.
* @private
* @param {object} modules Modules.
*/
function sort(modules) {
var name = null,
// Modules to be sorted.
pending = [],
// Modules already sorted.
sorted = [],
// Remember length of pending list for each module.
visited = {},
currModule = null;
for (name in modules) {
if (modules.hasOwnProperty(name)) {
if (modules[name].instance) {
// Already linked.
sorted.push(name);
} else {
// Sort for linking.
pending.push(name);
}
}
}
// Repeat while there are modules pending.
while (pending.length > 0) {
// Consider the next pending module
currModule = pending.shift();
// If we've been here and have not made any progress, we are looping
// (no support for cyclic module requires).
if (visited[currModule] && visited[currModule] <= pending.length) {
throw new Error('No support for circular module dependency.');
}
visited[currModule] = pending.length;
// Consider the current module's import requires.
if (areSorted(modules[currModule].requires, sorted)) {
// Requires done, module done.
sorted.push(currModule);
} else {
// Some requires still pending.
pending.push(currModule);
}
}
return sorted;
}
/**
* Merge the contents of two objects into the first object.
* @private
* @param {Object} target Target object (child).
* @param {Object} source Source object (parent).
* @return {Object} Target object.
*/
function extend(target, source) {
var prop = null;
for (prop in source) {
if (source.hasOwnProperty(prop)) {
Object.defineProperty(
target,
prop,
{
value: source[prop]
}
);
}
}
return target;
}
/**
* Create the object using Def as a constructor.
* In this case the object inherits the prototype from Def.
* @private
* @param {function} Def Constructing function.
* @param {object[]} args Parameters for the constructing function.
* @return {object} Constructed object.
*/
function construct(Def, args) {
var argsLen = args.length;
// Switch/case is used for performance reasons.
switch (argsLen) {
case 0:
return new Def();
case 1:
return new Def(args[0]);
case 2:
return new Def(args[0], args[1]);
case 3:
return new Def(args[0], args[1], args[2]);
case 4:
return new Def(args[0], args[1], args[2], args[3]);
case 5:
return new Def(args[0], args[1], args[2], args[3], args[4]);
default:
// Too many parameters, use a short form instead
return Def.apply(Object.create(Def.prototype), args);
}
}
/**
* Creates an object using the passed constructor and parameters.
* @private
* @param {function} Def Constructing function.
* @param {object[]} args Parameters for the constructing function.
* @return {object} Object of Def type.
*/
function instantiate(Def, args) {
var obj = null, proto = null;
obj = construct(Def, args);
// Constructors don't have to return anything, but we need at least
// an empty object.
if (!obj) {
obj = {};
}
/**
* If the module returns a plain object, we need to fix this.
* Create an object with a valid prototype
* and extend it by copying properties from the original object.
* The previous prototype, if any, is ignored.
* Only modules created with Object function will be extended.
* It is for ignore global objects like "window" or "tizen".
*/
proto = Object.getPrototypeOf(obj);
if (proto !== null && !Object.prototype.isPrototypeOf(proto)) {
obj = extend(
Object.create(Def.prototype),
obj
);
}
return obj;
}
/**
* Returns required module instance.
* Parameters are passed to the constructor.
* @private
* @param {string} moduleName Module name.
* @param {object} reqModule Required module object.
* @return {object} Module instance.
*/
function requireInstance(moduleName, reqModule) {
var instance = reqModule.instance;
if (reqModule.name === 'core/event') {
// Make new object inherited from core/event module
// for adding additional properties (per caller module).
instance = Object.create(reqModule.instance);
// Module name used to fire events.
instance.evName = moduleName.replace(/\//g, '.');
}
return instance;
}
/**
* Creates a require function which takes
* modules from the req object in the closure.
* @param {object} req All requires as object.
* @return {function} Require function.
*/
function createRequire(req) {
return function require(name) {
return req[name];
};
}
/**
* Creates parameters (from required modules).
* Parameteres are passed to the constructor.
* @private
* @param {object} module Module object.
* @return {object[]} params.
*/
function createParams(module) {
var def = module.def,
requires = module.requires,
params = [],
req = {},
instance = null,
i = 0;
if (def.length === 1 && requires.length > 1) {
// Collect requires as object.
for (i = requires.length - 1; i >= 0; i -= 1) {
instance = requireInstance(module.name, modules[requires[i]]);
// Full name keys for array-like indexing.
req[requires[i]] = instance;
}
// The only param is a 'require' function used for retrieving
// instances of the required modules.
params.push(createRequire(req));
} else if (def.length === requires.length) {
// Collect requires as modules.
for (i = requires.length - 1; i >= 0; i -= 1) {
params[i] = requireInstance(module.name, modules[requires[i]]);
}
} else if (def.length !== 0) {
// Invalid number of params.
// Definition module params length is greater than zero
// and different than requires params length.
throw new Error(
'Invalid number of params in ' + def.name +
'- expected ' + requires.length + ' but is ' + def.length
);
}
return params;
}
/* build:app */
/**
* Initialize Debug module.
* @private
*/
function initDebug() {
if (typeof global.debug === 'object') {
global.debug.init(modules);
}
}
/* endbuild:app */
/**
* Links and runs modules in the order in which they were loaded.
* @private
*/
function link() {
var i = 0,
sorted = [],
sortedLen = 0,
name = '',
module = null;
// Sort modules in requires order.
sorted = sort(modules);
sortedLen = sorted.length;
// Create instances of modules in requires order.
for (i = 0; i < sortedLen; i += 1) {
name = sorted[i];
module = modules[name];
if (module.instance === undefined) {
module.initialized = false;
// Each module should inherit from a generic Module object.
module.def.prototype = new Module(name);
// Execute module code, pass requires, record exports.
modules[name].instance = instantiate(
module.def,
createParams(module)
);
}
}
// Initialize modules in requires order.
// It must be in different loop (see above)
// because we need every instance ready.
for (i = 0; i < sortedLen; i += 1) {
name = sorted[i];
module = modules[name];
if (module.instance !== undefined && !module.initialized) {
if (typeof modules[name].instance.init === 'function') {
modules[name].instance.init();
module.initialized = true;
}
}
}
/* build:app */
initDebug();
/* endbuild:app */
}
/**
* Returns instance of module.
* @global
*
* @example
* // Define `foo` module which require `bar` module:
* define({
* name: 'foo',
* requires: ['bar'],
* def: function def(bar) {}
* });
*
* // Define `bar` module which needs some `foo` functionalities:
* // You can't define a circular dependency
* // (foo needs bar and bar needs foo)
* define({
* name: 'bar',
* requires: ['foo'],
* def: function def(foo) {}
* });
*
* // In that case use:
* define({
* name: 'bar',
* def: function def() {
* var foo;
* function init() {
* foo = require('foo');
* }
* return {
* init: init
* }
* }
* });
*
* @throws {Error} Module must be defined.
* @throws {Error} Module must be an instance.
*
* @param {string} moduleName Module name.
* @return {object} Module instance.
*/
function require(moduleName) {
var module = modules[moduleName];
if (module === undefined) {
throw new Error('Module ' + moduleName + ' must be defined.');
}
if (module.instance === undefined) {
throw new Error('The instance of ' + moduleName +
' doesn\'t exist yet.');
}
return module.instance;
}
/**
* Loads a script.
* @private
* @param {string} src Script src.
*/
function loadScript(src) {
var script = null;
script = document.createElement('script');
script.setAttribute('src', src);
script.addEventListener('error', function error() {
throw new Error(
'Failed to load "' + src + '" script'
);
});
head.appendChild(script);
}
/**
* Loads a module.
* @private
* @param {string} moduleName Module name.
*/
function load(moduleName) {
var modulePath = '';
if (modules[moduleName] !== undefined) {
return false;
}
modules[moduleName] = {};
if (moduleName.indexOf('core') === 0) {
modulePath = cfg.basePath || cfg.defaultPath;
} else {
modulePath = cfg.modulePath || cfg.defaultPath;
}
loadScript(modulePath + moduleName + '.js');
return true;
}
/**
* Check whether this was the last module to be loaded
* in a given dependency group.
* If yes, start linking and running modules.
* @private
*/
function loaded() {
var m = null,
pending = [];
for (m in modules) {
if (modules.hasOwnProperty(m) && modules[m].name === undefined) {
pending.push(m);
}
}
if (pending.length === 0) {
link();
}
}
/**
* The function that handles definitions of modules.
* @global
*
* @example
* // Define `foo` module:
* define(
* 'foo',
* def: function def() {}
* );
*
* @example
* // Define `bar` module:
* define(
* 'bar',
* function def() {}
* );
*
* @example
* // Define `foo` module which require `bar` module:
* define(
* 'foo',
* ['bar'],
* function def(bar) {}
* );
*
* @example
* // Define `foo` module which require `bar1` and `bar2` module:
* define(
* 'foo',
* ['bar1', 'bar2'],
* function def(bar1, bar2) {}
* );
*
* @example
* // Define `foo` module which require `bar1` and `bar2` module:
* define(
* 'foo',
* ['bar1', 'bar2'],
* function def(require) {
* var bar1 = require('bar1'),
* bar2 = require('bar2');
* }
* );
*
* @example
* // Define `foo` module which require `path/bar1` and `path/bar2` module:
* define(
* 'foo',
* ['path/bar1', 'path/bar2'],
* function def(require) {
* var bar1 = require('path/bar1'),
* bar2 = require('path/bar2');
* }
* );
*
* @example
* // Define `foo` module which is automatically initialized
* // during definition:
* define(
* 'foo',
* function def() {
* // module definition
* function init() {
* // init action
* }
*
* // return the module value with init function
* return {
* init: init
* };
* }
* );
*
* @throws {Error} Module must have name and definititon.
* @throws {Error} Module is already defined.
*
* @param {string} name Module name.
* @param {string[]} [requires] Module requires.
* @param {function} def Module definititon.
*/
function define(name, requires, def) {
var i = 0,
j = 0,
module = null;
// Handle optional requires.
if (typeof requires === 'function') {
def = requires;
requires = [];
}
module = {
name: name,
requires: requires || [],
def: def
};
if (name === undefined || def === undefined) {
throw new Error(
'Module must have name and definition'
);
}
if (modules[name] !== undefined &&
modules[name].name !== undefined) {
throw new Error(
'Module "' + name + '" is already defined'
);
}
modules[name] = module;
// Load required modules.
for (i = 0, j = module.requires.length; i < j; i += 1) {
load(module.requires[i]);
}
// Check for loaded modules.
loaded();
return true;
}
/**
* Looks for a data-main attribute in script elements.
* Data-main attribute tells core to load main application script.
* @private
* @return {boolean}
*/
function main() {
var i = 0,
len = 0,
scripts = document.getElementsByTagName('script'),
script = null,
dataMain = null;
for (i = 0, len = scripts.length; i < len; i += 1) {
script = scripts[i];
dataMain = script.getAttribute('data-main');
if (dataMain) {
cfg.modulePath = getPath(dataMain);
cfg.basePath = getPath(script.getAttribute('src'));
loadScript(dataMain);
return true;
}
}
return true;
}
define.amd = {};
publicAPI = {
require: require,
define: define
};
extend(global, publicAPI);
main();
}(this));