forked from montagejs/montage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
montage.js
565 lines (499 loc) · 21.3 KB
/
montage.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
/* <copyright>
Copyright (c) 2012, Motorola Mobility LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Motorola Mobility LLC nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */
/*global BUNDLE */
if (typeof window !== "undefined") {
document._montageTiming = {}
document._montageTiming.loadStartTime = Date.now();
// Give a threshold before we decide we need to show the bootstrapper progress
// Applications that use our loader will interact with this timeout
// and class name to coordinate a nice loading experience. Applications that do not will
// just go about business as usual and draw their content as soon as possible.
window.addEventListener("DOMContentLoaded", function() {
var bootstrappingDelay = 1000;
document._montageStartBootstrappingTimeout = setTimeout(function() {
document._montageStartBootstrappingTimeout = null;
var root = document.documentElement;
if(!!root.classList) {
root.classList.add("montage-app-bootstrapping");
} else {
root.className = root.className + " montage-app-bootstrapping";
}
document._montageTiming.bootstrappingStartTime = Date.now();
}, bootstrappingDelay);
});
}
(function (definition) {
if (typeof require !== "undefined") {
// CommonJS / NodeJS
definition(require, exports, module);
} else {
// <script>
definition({}, {}, {});
}
})(function (require, exports, module) {
// The global context object
var global = new Function("return this")();
/**
* Initializes Montage and creates the application singleton if
* necessary.
*/
exports.initMontage = function () {
var platform = exports.getPlatform();
// Platform dependent
platform.bootstrap(function (Require, Promise, URL, Clock) {
var params = platform.getParams();
var config = platform.getConfig();
var montageLocation = URL.resolve(Require.getLocation(), params.montageLocation);
// setup the reel loader
config.makeLoader = function (config) {
return exports.ReelLoader(
config,
Require.makeLoader(config)
);
};
// setup serialization compiler
config.makeCompiler = function (config) {
return exports.SerializationCompiler(
config,
exports.TemplateCompiler(
config,
Require.makeCompiler(config)
)
);
};
var location = URL.resolve(config.location, params["package"] || ".");
var applicationHash = params.applicationHash;
if (typeof BUNDLE === "object") {
var bundleDefinitions = {};
var getDefinition = function (name) {
return bundleDefinitions[name] =
bundleDefinitions[name] ||
Promise.Promise.defer();
};
global.bundleLoaded = function (name) {
getDefinition(name).resolve();
};
var preloading = Promise.Promise.defer();
config.preloaded = preloading.promise;
// preload bundles sequentially
var preloaded = Promise.Promise.resolve();
BUNDLE.forEach(function (bundleLocations) {
preloaded = preloaded.then(function () {
return Promise.Promise.all(bundleLocations.map(function (bundleLocation) {
browser.load(bundleLocation);
return getDefinition(bundleLocation).promise;
}));
});
});
// then release the module loader to run normally
preloading.resolve(preloaded.then(function () {
delete BUNDLE;
delete bundleLoaded;
}));
}
Require.loadPackage({
location: montageLocation,
hash: params.montageHash
}, config)
.then(function (montageRequire) {
montageRequire.inject("core/promise", Promise);
montageRequire.inject("core/next-tick", Clock);
montageRequire.inject("core/mini-url", URL);
// install the linter, which loads on the first error
config.lint = function (module) {
montageRequire.async("core/jshint")
.then(function (JSHINT) {
if (!JSHINT.JSHINT(module.text)) {
console.warn("JSHint Error: "+module.location);
JSHINT.JSHINT.errors.forEach(function(error) {
if (error) {
console.warn("Problem at line "+error.line+" character "+error.character+": "+error.reason);
if (error.evidence) {
console.warn(" " + error.evidence);
}
}
});
}
});
};
if ("autoPackage" in params) {
montageRequire.injectPackageDescription(location, {
dependencies: {
montage: "*"
}
});
}
// handle explicit package.json location
if (location.slice(location.length - 5) === ".json") {
var packageDescriptionLocation = location;
location = URL.resolve(location, ".");
montageRequire.injectPackageDescriptionLocation(
location,
packageDescriptionLocation
);
}
return montageRequire.loadPackage({
location: location,
hash: applicationHash
})
.then(function (applicationRequire) {
global.require = applicationRequire;
global.montageRequire = montageRequire;
platform.initMontage(montageRequire, applicationRequire, params);
})
})
.end();
});
};
/**
Adds "_montage_metadata" property to all objects and function attached to
the exports object.
@see Compiler middleware in require/require.js
@param config
@param compiler
*/
var reverseReelExpression = /((.*)\.reel)\/\2$/;
var reverseReelFunction = function ($0, $1) { return $1 };
exports.SerializationCompiler = function(config, compile) {
return function(module) {
compile(module);
if (!module.factory)
return;
var defaultFactory = module.factory;
module.factory = function(require, exports, module) {
defaultFactory.call(this, require, exports, module);
for (var name in exports) {
var object = exports[name];
// avoid attempting to initialize a non-object
if (!(object instanceof Object)) {
// avoid attempting to reinitialize an aliased property
} else if (object.hasOwnProperty("_montage_metadata") && !object._montage_metadata.isInstance) {
object._montage_metadata.aliases.push(name);
object._montage_metadata.objectName = name;
} else if (!Object.isSealed(object)) {
var id = module.id.replace(
reverseReelExpression,
reverseReelFunction
);
Object.defineProperty(
object,
"_montage_metadata",
{
value: {
require: require,
module: id,
moduleId: id, // deprecated
property: name,
objectName: name, // deprecated
aliases: [name],
isInstance: false
}
}
);
}
}
};
return module;
};
};
/**
* Allows reel directories to load the contained eponymous JavaScript
* module.
* @see Loader middleware in require/require.js
* @param config
* @param loader the next loader in the chain
*/
var reelExpression = /([^\/]+)\.reel$/;
exports.ReelLoader = function (config, load) {
return function (id, module) {
var match = reelExpression.exec(id);
if (match) {
module.redirect = id + "/" + match[1];
return module;
} else {
return load(id, module);
}
};
};
/**
Allows the reel's html file to be loaded via require.
@see Compiler middleware in require/require.js
@param config
@param compiler
*/
exports.TemplateCompiler = function(config, compile) {
return function(module) {
if (!module.location)
return;
var match = module.location.match(/(.*\/)?(?=[^\/]+\.html(?:\.load\.js)?$)/);
if (match) {
module.dependencies = module.dependencies || [];
module.exports = {
directory: match[1],
content: module.text
};
// XXX deprecated
Object.defineProperty(module.exports, "root", {
get: function () {
if (typeof console === "object") {
console.warn("'root' property is deprecated on template modules. Use 'directory' instead of root[1]");
}
return match;
}
});
return module;
} else {
compile(module);
}
};
};
// Bootstrapping for multiple-platforms
exports.getPlatform = function () {
if (typeof window !== "undefined" && window && window.document) {
return browser;
} else if (typeof process !== "undefined") {
return require("./node.js");
} else {
throw new Error("Platform not supported.");
}
};
var urlModuleFactory = function (require, exports) {
var baseElement = document.querySelector("base");
var existingBaseElement = baseElement;
if (!existingBaseElement) {
baseElement = document.createElement("base");
baseElement.href = "";
}
var head = document.querySelector("head");
var relativeElement = document.createElement("a");
exports.resolve = function (base, relative) {
if (!existingBaseElement) {
head.appendChild(baseElement);
}
base = String(base);
if (!/^[\w\-]+:/.test(base)) { // isAbsolute(base)
throw new Error("Can't resolve from a relative location: " + JSON.stringify(base) + " " + JSON.stringify(relative));
}
var restore = baseElement.href;
baseElement.href = base;
relativeElement.href = relative;
var resolved = relativeElement.href;
baseElement.href = restore;
if (!existingBaseElement) {
head.removeChild(baseElement);
}
return resolved;
};
};
var browser = {
load: function (location) {
var script = document.createElement("script");
script.src = location;
script.onload = function () {
// remove clutter
script.parentNode.removeChild(script);
};
document.getElementsByTagName("head")[0].appendChild(script);
},
getConfig: function() {
return {
location: "" + window.location
};
},
getParams: function() {
var i, j,
match,
script,
montage,
attr,
name;
if (!this._params) {
this._params = {};
// Find the <script> that loads us, so we can divine our
// parameters from its attributes.
var scripts = document.getElementsByTagName("script");
for (i = 0; i < scripts.length; i++) {
script = scripts[i];
montage = false;
if (script.src && (match = script.src.match(/^(.*)montage.js(?:[\?\.]|$)/i))) {
this._params.montageLocation = match[1];
montage = true;
}
if (script.hasAttribute("data-montage")) {
this._params.montageLocation = script.getAttribute("data-montage");
montage = true;
}
if (montage) {
if (script.dataset) {
for (name in script.dataset) {
this._params[name] = script.dataset[name];
}
} else if (script.attributes) {
for (j = 0; j < script.attributes.length; j++) {
attr = script.attributes[j];
match = attr.name.match(/^data-(.*)$/);
if (match) {
this._params[match[1]] = attr.value;
}
}
}
// Permits multiple montage.js <scripts>; by
// removing as they are discovered, next one
// finds itself.
script.parentNode.removeChild(script);
break;
}
}
}
return this._params;
},
bootstrap: function (callback) {
var base, Require, DOM, Promise, URL, Clock;
var params = this.getParams();
// observe dom loading and load scripts in parallel
// observe dom loaded
function domLoad() {
document.removeEventListener("DOMContentLoaded", domLoad, true);
DOM = true;
callbackIfReady();
}
// this permits montage.js to be injected after domready
if (document.readyState === "complete") {
domLoad();
} else {
document.addEventListener("DOMContentLoaded", domLoad, true);
}
// determine which scripts to load
var pending = [
"require/require",
"require/browser",
"core/promise",
"core/next-tick"
];
// load in parallel, but only if we’re not using a preloaded cache.
// otherwise, these scripts will be inlined after already
if (typeof BUNDLE === "undefined") {
pending.forEach(function(name) {
browser.load(params.montageLocation + name + ".js");
});
}
// register module definitions for deferred,
// serial execution
var definitions = {};
global.bootstrap = function (id, factory) {
definitions[id] = factory;
var at = pending.indexOf(id);
if (at !== -1) {
pending.splice(at, 1);
}
if (pending.length === 0) {
allModulesLoaded();
}
};
global.bootstrap("core/mini-url", urlModuleFactory);
// miniature module system
var bootModules = {};
function bootRequire(id) {
if (!bootModules[id] && definitions[id]) {
var exports = bootModules[id] = {};
definitions[id](bootRequire, exports);
}
return bootModules[id];
}
// execute bootstrap scripts
function allModulesLoaded() {
Clock = bootRequire("core/next-tick");
Promise = bootRequire("core/promise");
URL = bootRequire("core/mini-url");
Require = bootRequire("require/require");
delete global.bootstrap;
callbackIfReady();
}
function callbackIfReady() {
if (DOM && Require) {
callback(Require, Promise, URL, Clock);
}
}
},
initMontage: function (montageRequire, applicationRequire, params) {
var dependencies = [
"core/event/event-manager",
"core/deserializer"
];
if (typeof window !== "undefined") {
dependencies.push("core/event/binding");
}
var Promise = montageRequire("core/promise").Promise;
return Promise.all(dependencies.map(montageRequire.deepLoad))
.then(function () {
dependencies.forEach(montageRequire);
var EventManager = montageRequire("core/event/event-manager").EventManager;
var Deserializer = montageRequire("core/deserializer").Deserializer;
var defaultEventManager, application;
// Load the event-manager
defaultEventManager = EventManager.create().initWithWindow(window);
// montageWillLoad is mostly for testing purposes
if (typeof global.montageWillLoad === "function") {
global.montageWillLoad();
}
// Load the application
var appProto = applicationRequire.packageDescription.applicationPrototype,
applicationDescription, appModulePromise;
if (appProto) {
applicationDescription = Deserializer.parseForModuleAndName(appProto);
appModulePromise = applicationRequire.async(applicationDescription.module);
} else {
appModulePromise = montageRequire.async("ui/application");
}
return appModulePromise.then(function(exports) {
application = exports[(applicationDescription ? applicationDescription.name : "Application")].create();
window.document.application = application;
defaultEventManager.application = application;
application.eventManager = defaultEventManager;
application._load(applicationRequire, function() {
if (params.module) {
// If a module was specified in the config then we initialize it now
applicationRequire.async(params.module)
.end();
}
});
})
})
.end();
}
};
if (typeof window !== "undefined") {
if (global.__MONTAGE_LOADED__) {
console.warn("Montage already loaded!");
} else {
global.__MONTAGE_LOADED__ = true;
exports.initMontage();
}
} else {
// may cause additional exports to be injected:
exports.getPlatform();
}
});