Commit a5d0ac74 authored by Pascal Hartig's avatar Pascal Hartig

Flight: Update dependencies

parent 2e2ee2b3
...@@ -41,6 +41,12 @@ define( ...@@ -41,6 +41,12 @@ define(
} }
} }
function proxyEventTo(targetEvent) {
return function(e, data) {
$(e.target).trigger(targetEvent, data);
};
}
function withBase() { function withBase() {
// delegate trigger, bind and unbind to an element // delegate trigger, bind and unbind to an element
...@@ -99,6 +105,8 @@ define( ...@@ -99,6 +105,8 @@ define(
originalCb = utils.delegate( originalCb = utils.delegate(
this.resolveDelegateRules(origin) this.resolveDelegateRules(origin)
); );
} else if (typeof origin == 'string') {
originalCb = proxyEventTo(origin);
} else { } else {
originalCb = origin; originalCb = origin;
} }
...@@ -117,16 +125,13 @@ define( ...@@ -117,16 +125,13 @@ define(
callback = originalCb.bind(this); callback = originalCb.bind(this);
callback.target = originalCb; callback.target = originalCb;
callback.context = this;
// if the original callback is already branded by jQuery's guid, copy it to the context-bound version
if (originalCb.guid) {
callback.guid = originalCb.guid;
}
$element.on(type, callback); $element.on(type, callback);
// get jquery's guid from our bound fn, so unbinding will work // store every bound version of the callback
originalCb.guid = callback.guid; originalCb.bound || (originalCb.bound = []);
originalCb.bound.push(callback);
return callback; return callback;
}; };
...@@ -148,6 +153,19 @@ define( ...@@ -148,6 +153,19 @@ define(
type = arguments[0]; type = arguments[0];
} }
if (callback) {
//this callback may be the original function or a bound version
var boundFunctions = callback.target ? callback.target.bound : callback.bound || [];
//set callback to version bound against this instance
boundFunctions && boundFunctions.some(function(fn, i, arr) {
if (fn.context && (this.identity == fn.context.identity)) {
arr.splice(i, 1);
callback = fn;
return true;
}
}, this);
}
return $element.off(type, callback); return $element.off(type, callback);
}; };
...@@ -158,7 +176,7 @@ define( ...@@ -158,7 +176,7 @@ define(
if (!(r in this.attr)) { if (!(r in this.attr)) {
throw new Error('Component "' + this.toString() + '" wants to listen on "' + r + '" but no such attribute was defined.'); throw new Error('Component "' + this.toString() + '" wants to listen on "' + r + '" but no such attribute was defined.');
} }
rules[this.attr[r]] = ruleInfo[r]; rules[this.attr[r]] = (typeof ruleInfo[r] == 'string') ? proxyEventTo(ruleInfo[r]) : ruleInfo[r];
}, this); }, this);
return rules; return rules;
......
...@@ -27,7 +27,11 @@ define( ...@@ -27,7 +27,11 @@ define(
componentInfo && Object.keys(componentInfo.instances).forEach(function(k) { componentInfo && Object.keys(componentInfo.instances).forEach(function(k) {
var info = componentInfo.instances[k]; var info = componentInfo.instances[k];
info.instance.teardown(); // It's possible that a previous teardown caused another component to teardown,
// so we can't assume that the instances object is as it was.
if (info && info.instance) {
info.instance.teardown();
}
}); });
} }
...@@ -65,37 +69,49 @@ define( ...@@ -65,37 +69,49 @@ define(
}.bind(this)); }.bind(this));
} }
function prettyPrintMixins() {
//could be called from constructor or constructor.prototype
var mixedIn = this.mixedIn || this.prototype.mixedIn || [];
return mixedIn.map(function(mixin) {
if (mixin.name == null) {
// function name property not supported by this browser, use regex
var m = mixin.toString().match(functionNameRegEx);
return (m && m[1]) ? m[1] : '';
} else {
return (mixin.name != 'withBase') ? mixin.name : '';
}
}).filter(Boolean).join(', ');
};
// define the constructor for a custom component type // define the constructor for a custom component type
// takes an unlimited number of mixin functions as arguments // takes an unlimited number of mixin functions as arguments
// typical api call with 3 mixins: define(timeline, withTweetCapability, withScrollCapability); // typical api call with 3 mixins: define(timeline, withTweetCapability, withScrollCapability);
function define(/*mixins*/) { function define(/*mixins*/) {
// unpacking arguments by hand benchmarked faster // unpacking arguments by hand benchmarked faster
var l = arguments.length; var l = arguments.length;
// add three for common mixins var mixins = new Array(l);
var mixins = new Array(l + 3);
for (var i = 0; i < l; i++) mixins[i] = arguments[i]; for (var i = 0; i < l; i++) mixins[i] = arguments[i];
var Component = function() {}; var Component = function() {};
Component.toString = Component.prototype.toString = function() { Component.toString = Component.prototype.toString = prettyPrintMixins;
var prettyPrintMixins = mixins.map(function(mixin) {
if (mixin.name == null) {
// function name property not supported by this browser, use regex
var m = mixin.toString().match(functionNameRegEx);
return (m && m[1]) ? m[1] : '';
} else {
return (mixin.name != 'withBase') ? mixin.name : '';
}
}).filter(Boolean).join(', ');
return prettyPrintMixins;
};
if (debug.enabled) { if (debug.enabled) {
Component.describe = Component.prototype.describe = Component.toString(); Component.describe = Component.prototype.describe = Component.toString();
} }
// 'options' is optional hash to be merged with 'defaults' in the component definition // 'options' is optional hash to be merged with 'defaults' in the component definition
Component.attachTo = attachTo; Component.attachTo = attachTo;
// enables extension of existing "base" Components
Component.mixin = function() {
var newComponent = define(); //TODO: fix pretty print
var newPrototype = Object.create(Component.prototype);
newPrototype.mixedIn = [].concat(Component.prototype.mixedIn);
compose.mixin(newPrototype, arguments);
newComponent.prototype = newPrototype;
newComponent.prototype.constructor = newComponent;
return newComponent;
};
Component.teardownAll = teardownAll; Component.teardownAll = teardownAll;
// prepend common mixins to supplied list, then mixin all flavors // prepend common mixins to supplied list, then mixin all flavors
......
...@@ -65,13 +65,13 @@ define( ...@@ -65,13 +65,13 @@ define(
function mixin(base, mixins) { function mixin(base, mixins) {
base.mixedIn = base.hasOwnProperty('mixedIn') ? base.mixedIn : []; base.mixedIn = base.hasOwnProperty('mixedIn') ? base.mixedIn : [];
mixins.forEach(function(mixin) { for (var i=0; i<mixins.length; i++) {
if (base.mixedIn.indexOf(mixin) == -1) { if (base.mixedIn.indexOf(mixins[i]) == -1) {
setPropertyWritability(base, false); setPropertyWritability(base, false);
mixin.call(base); mixins[i].call(base);
base.mixedIn.push(mixin); base.mixedIn.push(mixins[i]);
} }
}); }
setPropertyWritability(base, true); setPropertyWritability(base, true);
} }
......
...@@ -11,9 +11,9 @@ define( ...@@ -11,9 +11,9 @@ define(
function() { function() {
'use strict'; 'use strict';
//****************************************************************************************** // ==========================================
// Search object model // Search object model
//****************************************************************************************** // ==========================================
function traverse(util, searchTerm, options) { function traverse(util, searchTerm, options) {
options = options || {}; options = options || {};
...@@ -53,17 +53,17 @@ define( ...@@ -53,17 +53,17 @@ define(
function byValueCoerced(searchTerm, options) {search('valueCoerced', null, searchTerm, options);} function byValueCoerced(searchTerm, options) {search('valueCoerced', null, searchTerm, options);}
function custom(fn, options) {traverse(fn, null, options);} function custom(fn, options) {traverse(fn, null, options);}
//****************************************************************************************** // ==========================================
// Event logging // Event logging
//****************************************************************************************** // ==========================================
var ALL = 'all'; //no filter var ALL = 'all'; //no filter
//no logging by default //log nothing by default
var defaultEventNamesFilter = []; var logFilter = {
var defaultActionsFilter = []; eventNames: [],
actions: []
var logFilter = retrieveLogFilter(); }
function filterEventLogsByAction(/*actions*/) { function filterEventLogsByAction(/*actions*/) {
var actions = [].slice.call(arguments); var actions = [].slice.call(arguments);
...@@ -94,26 +94,32 @@ define( ...@@ -94,26 +94,32 @@ define(
} }
function saveLogFilter() { function saveLogFilter() {
if (window.localStorage) { try {
localStorage.setItem('logFilter_eventNames', logFilter.eventNames); if (window.localStorage) {
localStorage.setItem('logFilter_actions', logFilter.actions); localStorage.setItem('logFilter_eventNames', logFilter.eventNames);
} localStorage.setItem('logFilter_actions', logFilter.actions);
}
} catch (ignored) {};
} }
function retrieveLogFilter() { function retrieveLogFilter() {
var result = { var eventNames, actions;
eventNames: (window.localStorage && localStorage.getItem('logFilter_eventNames')) || defaultEventNamesFilter, try {
actions: (window.localStorage && localStorage.getItem('logFilter_actions')) || defaultActionsFilter eventNames = (window.localStorage && localStorage.getItem('logFilter_eventNames'));
}; actions = (window.localStorage && localStorage.getItem('logFilter_actions'));
} catch(ignored) {
// reconstitute arrays return;
Object.keys(result).forEach(function(k) { }
var thisProp = result[k]; eventNames && (logFilter.eventNames = eventNames);
actions && (logFilter.actions = actions);
// reconstitute arrays in place
Object.keys(logFilter).forEach(function(k) {
var thisProp = logFilter[k];
if (typeof thisProp == 'string' && thisProp !== ALL) { if (typeof thisProp == 'string' && thisProp !== ALL) {
result[k] = thisProp.split(','); logFilter[k] = thisProp ? thisProp.split(',') : [];
} }
}); });
return result;
} }
return { return {
...@@ -126,6 +132,8 @@ define( ...@@ -126,6 +132,8 @@ define(
console.info('You can configure event logging with DEBUG.events.logAll()/logNone()/logByName()/logByAction()'); console.info('You can configure event logging with DEBUG.events.logAll()/logNone()/logByName()/logByAction()');
} }
retrieveLogFilter();
window.DEBUG = this; window.DEBUG = this;
}, },
......
...@@ -27,47 +27,54 @@ define( ...@@ -27,47 +27,54 @@ define(
} }
function log(action, component, eventArgs) { function log(action, component, eventArgs) {
var name, elem, fn, logFilter, toRegExp, actionLoggable, nameLoggable; if (!window.DEBUG || !window.DEBUG.enabled) return;
var name, eventType, elem, fn, payload, logFilter, toRegExp, actionLoggable, nameLoggable, info;
if (typeof eventArgs[eventArgs.length-1] == 'function') { if (typeof eventArgs[eventArgs.length-1] == 'function') {
fn = eventArgs.pop(); fn = eventArgs.pop();
fn = fn.unbound || fn; // use unbound version if any (better info) fn = fn.unbound || fn; // use unbound version if any (better info)
} }
if (typeof eventArgs[eventArgs.length - 1] == 'object') { if (eventArgs.length == 1) {
eventArgs.pop(); // trigger data arg - not logged right now elem = component.$node[0];
} eventType = eventArgs[0];
} else if ((eventArgs.length == 2) && typeof eventArgs[1] == 'object' && !eventArgs[1].type) {
if (eventArgs.length == 2) { //2 args, first arg is not elem
elem = eventArgs[0];
name = eventArgs[1];
} else {
elem = component.$node[0]; elem = component.$node[0];
name = eventArgs[0]; eventType = eventArgs[0];
if (action == "trigger") {
payload = eventArgs[1];
}
} else {
//2+ args, first arg is elem
elem = eventArgs[0];
eventType = eventArgs[1];
if (action == "trigger") {
payload = eventArgs[2];
}
} }
if (window.DEBUG && window.DEBUG.enabled) { name = typeof eventType == 'object' ? eventType.type : eventType;
logFilter = DEBUG.events.logFilter;
// no regex for you, actions... logFilter = DEBUG.events.logFilter;
actionLoggable = logFilter.actions == 'all' || (logFilter.actions.indexOf(action) > -1);
// event name filter allow wildcards or regex...
toRegExp = function(expr) {
return expr.test ? expr : new RegExp('^' + expr.replace(/\*/g, '.*') + '$');
};
nameLoggable =
logFilter.eventNames == 'all' ||
logFilter.eventNames.some(function(e) {return toRegExp(e).test(name);});
if (actionLoggable && nameLoggable) { // no regex for you, actions...
console.info( actionLoggable = logFilter.actions == 'all' || (logFilter.actions.indexOf(action) > -1);
actionSymbols[action], // event name filter allow wildcards or regex...
action, toRegExp = function(expr) {
'[' + name + ']', return expr.test ? expr : new RegExp('^' + expr.replace(/\*/g, '.*') + '$');
elemToString(elem), };
component.constructor.describe.split(' ').slice(0,3).join(' ') // two mixins only nameLoggable =
); logFilter.eventNames == 'all' ||
} logFilter.eventNames.some(function(e) {return toRegExp(e).test(name);});
if (actionLoggable && nameLoggable) {
info = [actionSymbols[action], action, '[' + name + ']'];
payload && info.push(payload);
info.push(elemToString(elem));
info.push(component.constructor.describe.split(' ').slice(0,3).join(' '));
console.groupCollapsed && action == 'trigger' && console.groupCollapsed(action, name);
console.info.apply(console, info);
} }
} }
...@@ -75,6 +82,11 @@ define( ...@@ -75,6 +82,11 @@ define(
this.before('trigger', function() { this.before('trigger', function() {
log('trigger', this, utils.toArray(arguments)); log('trigger', this, utils.toArray(arguments));
}); });
if (console.groupCollapsed) {
this.after('trigger', function() {
console.groupEnd();
});
}
this.before('on', function() { this.before('on', function() {
log('on', this, utils.toArray(arguments)); log('on', this, utils.toArray(arguments));
}); });
......
...@@ -151,6 +151,12 @@ define( ...@@ -151,6 +151,12 @@ define(
return this.allInstances[instance.identity] || null; return this.allInstances[instance.identity] || null;
}; };
this.getBoundEventNames = function(instance) {
return this.findInstanceInfo(instance).events.map(function(ev) {
return ev.type;
});
};
this.findInstanceInfoByNode = function(node) { this.findInstanceInfoByNode = function(node) {
var result = []; var result = [];
Object.keys(this.allInstances).forEach(function(k) { Object.keys(this.allInstances).forEach(function(k) {
......
...@@ -219,13 +219,41 @@ define( ...@@ -219,13 +219,41 @@ define(
var target = $(e.target), parent; var target = $(e.target), parent;
Object.keys(rules).forEach(function(selector) { Object.keys(rules).forEach(function(selector) {
if ((parent = target.closest(selector)).length) { if (!e.isPropagationStopped() && (parent = target.closest(selector)).length) {
data = data || {}; data = data || {};
data.el = parent[0]; data.el = parent[0];
return rules[selector].apply(this, [e, data]); return rules[selector].apply(this, [e, data]);
} }
}, this); }, this);
}; };
},
// ensures that a function will only be called once.
// usage:
// will only create the application once
// var initialize = utils.once(createApplication)
// initialize();
// initialize();
//
// will only delete a record once
// var myHanlder = function () {
// $.ajax({type: 'DELETE', url: 'someurl.com', data: {id: 1}});
// };
// this.on('click', utils.once(myHandler));
//
once: function(func) {
var ran, result;
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
return result;
};
} }
}; };
......
File mode changed from 100644 to 100755
/** /**
* @license RequireJS text 2.0.10 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * @license RequireJS text 2.0.12 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/requirejs/text for details * see: http://github.com/requirejs/text for details
*/ */
...@@ -23,7 +23,7 @@ define(['module'], function (module) { ...@@ -23,7 +23,7 @@ define(['module'], function (module) {
masterConfig = (module.config && module.config()) || {}; masterConfig = (module.config && module.config()) || {};
text = { text = {
version: '2.0.10', version: '2.0.12',
strip: function (content) { strip: function (content) {
//Strips <?xml ...?> declarations so that external SVG and XML //Strips <?xml ...?> declarations so that external SVG and XML
...@@ -162,12 +162,12 @@ define(['module'], function (module) { ...@@ -162,12 +162,12 @@ define(['module'], function (module) {
// Do not bother with the work if a build and text will // Do not bother with the work if a build and text will
// not be inlined. // not be inlined.
if (config.isBuild && !config.inlineText) { if (config && config.isBuild && !config.inlineText) {
onLoad(); onLoad();
return; return;
} }
masterConfig.isBuild = config.isBuild; masterConfig.isBuild = config && config.isBuild;
var parsed = text.parseName(name), var parsed = text.parseName(name),
nonStripName = parsed.moduleName + nonStripName = parsed.moduleName +
...@@ -257,7 +257,9 @@ define(['module'], function (module) { ...@@ -257,7 +257,9 @@ define(['module'], function (module) {
} }
callback(file); callback(file);
} catch (e) { } catch (e) {
errback(e); if (errback) {
errback(e);
}
} }
}; };
} else if (masterConfig.env === 'xhr' || (!masterConfig.env && } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
...@@ -285,12 +287,14 @@ define(['module'], function (module) { ...@@ -285,12 +287,14 @@ define(['module'], function (module) {
//Do not explicitly handle errors, those should be //Do not explicitly handle errors, those should be
//visible via console output in the browser. //visible via console output in the browser.
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
status = xhr.status; status = xhr.status || 0;
if (status > 399 && status < 600) { if (status > 399 && status < 600) {
//An http 4xx or 5xx error. Signal an error. //An http 4xx or 5xx error. Signal an error.
err = new Error(url + ' HTTP status: ' + status); err = new Error(url + ' HTTP status: ' + status);
err.xhr = xhr; err.xhr = xhr;
errback(err); if (errback) {
errback(err);
}
} else { } else {
callback(xhr.responseText); callback(xhr.responseText);
} }
...@@ -347,7 +351,7 @@ define(['module'], function (module) { ...@@ -347,7 +351,7 @@ define(['module'], function (module) {
typeof Components !== 'undefined' && Components.classes && typeof Components !== 'undefined' && Components.classes &&
Components.interfaces)) { Components.interfaces)) {
//Avert your gaze! //Avert your gaze!
Cc = Components.classes, Cc = Components.classes;
Ci = Components.interfaces; Ci = Components.interfaces;
Components.utils['import']('resource://gre/modules/FileUtils.jsm'); Components.utils['import']('resource://gre/modules/FileUtils.jsm');
xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc); xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);
......
/** vim: et:ts=4:sw=4:sts=4 /** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.9 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * @license RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
...@@ -12,7 +12,7 @@ var requirejs, require, define; ...@@ -12,7 +12,7 @@ var requirejs, require, define;
(function (global) { (function (global) {
var req, s, head, baseElement, dataMain, src, var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath, interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.9', version = '2.1.11',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/, jsSuffixRegExp = /\.js$/,
...@@ -108,7 +108,10 @@ var requirejs, require, define; ...@@ -108,7 +108,10 @@ var requirejs, require, define;
if (source) { if (source) {
eachProp(source, function (value, prop) { eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) { if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value !== 'string') { if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) { if (!target[prop]) {
target[prop] = {}; target[prop] = {};
} }
...@@ -138,7 +141,7 @@ var requirejs, require, define; ...@@ -138,7 +141,7 @@ var requirejs, require, define;
throw err; throw err;
} }
//Allow getting a global that expressed in //Allow getting a global that is expressed in
//dot notation, like 'a.b.c'. //dot notation, like 'a.b.c'.
function getGlobal(value) { function getGlobal(value) {
if (!value) { if (!value) {
...@@ -201,6 +204,7 @@ var requirejs, require, define; ...@@ -201,6 +204,7 @@ var requirejs, require, define;
waitSeconds: 7, waitSeconds: 7,
baseUrl: './', baseUrl: './',
paths: {}, paths: {},
bundles: {},
pkgs: {}, pkgs: {},
shim: {}, shim: {},
config: {} config: {}
...@@ -214,6 +218,7 @@ var requirejs, require, define; ...@@ -214,6 +218,7 @@ var requirejs, require, define;
defQueue = [], defQueue = [],
defined = {}, defined = {},
urlFetched = {}, urlFetched = {},
bundlesMap = {},
requireCounter = 1, requireCounter = 1,
unnormalizedCounter = 1; unnormalizedCounter = 1;
...@@ -227,8 +232,8 @@ var requirejs, require, define; ...@@ -227,8 +232,8 @@ var requirejs, require, define;
* @param {Array} ary the array of path segments. * @param {Array} ary the array of path segments.
*/ */
function trimDots(ary) { function trimDots(ary) {
var i, part; var i, part, length = ary.length;
for (i = 0; ary[i]; i += 1) { for (i = 0; i < length; i++) {
part = ary[i]; part = ary[i];
if (part === '.') { if (part === '.') {
ary.splice(i, 1); ary.splice(i, 1);
...@@ -261,7 +266,7 @@ var requirejs, require, define; ...@@ -261,7 +266,7 @@ var requirejs, require, define;
* @returns {String} normalized name * @returns {String} normalized name
*/ */
function normalize(name, baseName, applyMap) { function normalize(name, baseName, applyMap) {
var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI, foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'), baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts, normalizedBaseParts = baseParts,
...@@ -274,29 +279,26 @@ var requirejs, require, define; ...@@ -274,29 +279,26 @@ var requirejs, require, define;
//otherwise, assume it is a top-level require that will //otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end. //be relative to baseUrl in the end.
if (baseName) { if (baseName) {
if (getOwn(config.pkgs, baseName)) { //Convert baseName to array, and lop off the last part,
//If the baseName is a package name, then just treat it as one //so that . matches that 'directory' and not name of the baseName's
//name to concat the name with. //module. For instance, baseName of 'one/two/three', maps to
normalizedBaseParts = baseParts = [baseName]; //'one/two/three.js', but we want the directory, 'one/two' for
} else { //this normalization.
//Convert baseName to array, and lop off the last part, normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
//so that . matches that 'directory' and not name of the baseName's name = name.split('/');
//module. For instance, baseName of 'one/two/three', maps to lastIndex = name.length - 1;
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization. // If wanting node ID compatibility, strip .js from end
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); // of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
} }
name = normalizedBaseParts.concat(name.split('/')); name = normalizedBaseParts.concat(name);
trimDots(name); trimDots(name);
//Some use of packages may use a . path to reference the
//'main' module name, so normalize for that.
pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
name = name.join('/'); name = name.join('/');
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName;
}
} else if (name.indexOf('./') === 0) { } else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative // No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot. // to baseUrl, pull off the leading dot.
...@@ -308,7 +310,7 @@ var requirejs, require, define; ...@@ -308,7 +310,7 @@ var requirejs, require, define;
if (applyMap && map && (baseParts || starMap)) { if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/'); nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) { outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/'); nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) { if (baseParts) {
...@@ -325,16 +327,12 @@ var requirejs, require, define; ...@@ -325,16 +327,12 @@ var requirejs, require, define;
//Match, update name to the new value. //Match, update name to the new value.
foundMap = mapValue; foundMap = mapValue;
foundI = i; foundI = i;
break; break outerLoop;
} }
} }
} }
} }
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it, //Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching //if there is a shorter segment match later in a matching
//config, then favor over this star map. //config, then favor over this star map.
...@@ -355,7 +353,11 @@ var requirejs, require, define; ...@@ -355,7 +353,11 @@ var requirejs, require, define;
} }
} }
return name; // If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
} }
function removeScript(name) { function removeScript(name) {
...@@ -548,7 +550,7 @@ var requirejs, require, define; ...@@ -548,7 +550,7 @@ var requirejs, require, define;
//local var ref to defQueue, so cannot just reassign the one //local var ref to defQueue, so cannot just reassign the one
//on context. //on context.
apsp.apply(defQueue, apsp.apply(defQueue,
[defQueue.length - 1, 0].concat(globalDefQueue)); [defQueue.length, 0].concat(globalDefQueue));
globalDefQueue = []; globalDefQueue = [];
} }
} }
...@@ -565,7 +567,7 @@ var requirejs, require, define; ...@@ -565,7 +567,7 @@ var requirejs, require, define;
mod.usingExports = true; mod.usingExports = true;
if (mod.map.isDefine) { if (mod.map.isDefine) {
if (mod.exports) { if (mod.exports) {
return mod.exports; return (defined[mod.map.id] = mod.exports);
} else { } else {
return (mod.exports = defined[mod.map.id] = {}); return (mod.exports = defined[mod.map.id] = {});
} }
...@@ -579,15 +581,9 @@ var requirejs, require, define; ...@@ -579,15 +581,9 @@ var requirejs, require, define;
id: mod.map.id, id: mod.map.id,
uri: mod.map.url, uri: mod.map.url,
config: function () { config: function () {
var c, return getOwn(config.config, mod.map.id) || {};
pkg = getOwn(config.pkgs, mod.map.id);
// For packages, only support config targeted
// at the main module.
c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) :
getOwn(config.config, mod.map.id);
return c || {};
}, },
exports: defined[mod.map.id] exports: mod.exports || (mod.exports = {})
}); });
} }
} }
...@@ -628,7 +624,7 @@ var requirejs, require, define; ...@@ -628,7 +624,7 @@ var requirejs, require, define;
} }
function checkLoaded() { function checkLoaded() {
var map, modId, err, usingPathFallback, var err, usingPathFallback,
waitInterval = config.waitSeconds * 1000, waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0. //It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
...@@ -646,8 +642,8 @@ var requirejs, require, define; ...@@ -646,8 +642,8 @@ var requirejs, require, define;
//Figure out the state of all the modules. //Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) { eachProp(enabledRegistry, function (mod) {
map = mod.map; var map = mod.map,
modId = map.id; modId = map.id;
//Skip things that are not enabled or in error state. //Skip things that are not enabled or in error state.
if (!mod.enabled) { if (!mod.enabled) {
...@@ -870,17 +866,14 @@ var requirejs, require, define; ...@@ -870,17 +866,14 @@ var requirejs, require, define;
exports = context.execCb(id, factory, depExports, exports); exports = context.execCb(id, factory, depExports, exports);
} }
if (this.map.isDefine) { // Favor return value over exports. If node/cjs in play,
//If setting exports via 'module' is in play, // then will not have a return value anyway. Favor
//favor that over return value and exports. After that, // module.exports assignment over exports object.
//favor a non-undefined return value over exports use. if (this.map.isDefine && exports === undefined) {
cjsModule = this.module; cjsModule = this.module;
if (cjsModule && if (cjsModule) {
cjsModule.exports !== undefined &&
//Make sure it is not already the exports value
cjsModule.exports !== this.exports) {
exports = cjsModule.exports; exports = cjsModule.exports;
} else if (exports === undefined && this.usingExports) { } else if (this.usingExports) {
//exports already set the defined value. //exports already set the defined value.
exports = this.exports; exports = this.exports;
} }
...@@ -940,6 +933,7 @@ var requirejs, require, define; ...@@ -940,6 +933,7 @@ var requirejs, require, define;
on(pluginMap, 'defined', bind(this, function (plugin) { on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod, var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
name = this.map.name, name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null, parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, { localRequire = context.makeRequire(map.parentMap, {
...@@ -985,6 +979,14 @@ var requirejs, require, define; ...@@ -985,6 +979,14 @@ var requirejs, require, define;
return; return;
} }
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
return;
}
load = bind(this, function (value) { load = bind(this, function (value) {
this.init([], function () { return value; }, null, { this.init([], function () { return value; }, null, {
enabled: true enabled: true
...@@ -1249,31 +1251,38 @@ var requirejs, require, define; ...@@ -1249,31 +1251,38 @@ var requirejs, require, define;
} }
} }
//Save off the paths and packages since they require special processing, //Save off the paths since they require special processing,
//they are additive. //they are additive.
var pkgs = config.pkgs, var shim = config.shim,
shim = config.shim,
objs = { objs = {
paths: true, paths: true,
bundles: true,
config: true, config: true,
map: true map: true
}; };
eachProp(cfg, function (value, prop) { eachProp(cfg, function (value, prop) {
if (objs[prop]) { if (objs[prop]) {
if (prop === 'map') { if (!config[prop]) {
if (!config.map) { config[prop] = {};
config.map = {};
}
mixin(config[prop], value, true, true);
} else {
mixin(config[prop], value, true);
} }
mixin(config[prop], value, true, true);
} else { } else {
config[prop] = value; config[prop] = value;
} }
}); });
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim //Merge shim
if (cfg.shim) { if (cfg.shim) {
eachProp(cfg.shim, function (value, id) { eachProp(cfg.shim, function (value, id) {
...@@ -1294,29 +1303,25 @@ var requirejs, require, define; ...@@ -1294,29 +1303,25 @@ var requirejs, require, define;
//Adjust packages if necessary. //Adjust packages if necessary.
if (cfg.packages) { if (cfg.packages) {
each(cfg.packages, function (pkgObj) { each(cfg.packages, function (pkgObj) {
var location; var location, name;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
name = pkgObj.name;
location = pkgObj.location; location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Create a brand new object on pkgs, since currentPackages can //Save pointer to main module ID for pkg name.
//be passed in again, and config.pkgs is the internal transformed //Remove leading dot in main, so main paths are normalized,
//state for all package configs. //and remove any trailing .js, since different package
pkgs[pkgObj.name] = { //envs have different conventions: some use a module name,
name: pkgObj.name, //some use a file name.
location: location || pkgObj.name, config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
//Remove leading dot in main, so main paths are normalized, .replace(currDirRegExp, '')
//and remove any trailing .js, since different package .replace(jsSuffixRegExp, '');
//envs have different conventions: some use a module name,
//some use a file name.
main: (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '')
};
}); });
//Done with modifications, assing packages back to context config
config.pkgs = pkgs;
} }
//If there are any "waiting to execute" modules in the registry, //If there are any "waiting to execute" modules in the registry,
...@@ -1469,6 +1474,15 @@ var requirejs, require, define; ...@@ -1469,6 +1474,15 @@ var requirejs, require, define;
delete urlFetched[map.url]; delete urlFetched[map.url];
delete undefEvents[id]; delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function(args, i) {
if(args[0] === id) {
defQueue.splice(i, 1);
}
});
if (mod) { if (mod) {
//Hold on to listeners in case the //Hold on to listeners in case the
//module will be attempted to be reloaded //module will be attempted to be reloaded
...@@ -1488,7 +1502,7 @@ var requirejs, require, define; ...@@ -1488,7 +1502,7 @@ var requirejs, require, define;
/** /**
* Called to enable a module if it is still in the registry * Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module, * awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overriden by * is passed in for context, when this method is overridden by
* the optimizer. Not shown here to keep code compact. * the optimizer. Not shown here to keep code compact.
*/ */
enable: function (depMap) { enable: function (depMap) {
...@@ -1562,8 +1576,19 @@ var requirejs, require, define; ...@@ -1562,8 +1576,19 @@ var requirejs, require, define;
* internal API, not a public one. Use toUrl for the public API. * internal API, not a public one. Use toUrl for the public API.
*/ */
nameToUrl: function (moduleName, ext, skipExt) { nameToUrl: function (moduleName, ext, skipExt) {
var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, var paths, syms, i, parentModule, url,
parentPath; parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just //If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
...@@ -1577,7 +1602,6 @@ var requirejs, require, define; ...@@ -1577,7 +1602,6 @@ var requirejs, require, define;
} else { } else {
//A module that needs to be converted to a path. //A module that needs to be converted to a path.
paths = config.paths; paths = config.paths;
pkgs = config.pkgs;
syms = moduleName.split('/'); syms = moduleName.split('/');
//For each module name segment, see if there is a path //For each module name segment, see if there is a path
...@@ -1585,7 +1609,7 @@ var requirejs, require, define; ...@@ -1585,7 +1609,7 @@ var requirejs, require, define;
//and work up from it. //and work up from it.
for (i = syms.length; i > 0; i -= 1) { for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/'); parentModule = syms.slice(0, i).join('/');
pkg = getOwn(pkgs, parentModule);
parentPath = getOwn(paths, parentModule); parentPath = getOwn(paths, parentModule);
if (parentPath) { if (parentPath) {
//If an array, it means there are a few choices, //If an array, it means there are a few choices,
...@@ -1595,16 +1619,6 @@ var requirejs, require, define; ...@@ -1595,16 +1619,6 @@ var requirejs, require, define;
} }
syms.splice(0, i, parentPath); syms.splice(0, i, parentPath);
break; break;
} else if (pkg) {
//If module name is just the package name, then looking
//for the main module.
if (moduleName === pkg.name) {
pkgPath = pkg.location + '/' + pkg.main;
} else {
pkgPath = pkg.location;
}
syms.splice(0, i, pkgPath);
break;
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment