Commit 2e471183 authored by Stephen Sawchuk's avatar Stephen Sawchuk

troopjs updated to use bower.

parent feb84b19
{
"name": "todomvc-troopjs",
"version": "0.0.0",
"dependencies": {
"todomvc-common": "~0.1.4",
"requirejs": "~2.1.5",
"jquery": "<=1.8.2"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
//Not using strict: uneven strict support in browsers, #392, and causes
//problems with requirejs.exec()/transpiler plugins that may not be strict.
/*jslint regexp: true, nomen: true, sloppy: true */
/*global window, navigator, document, importScripts, setTimeout, opera */
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.5',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
ap = Array.prototype,
apsp = ap.splice,
isBrowser = !!(typeof window !== 'undefined' && navigator && document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value !== 'string') {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
//Allow getting a global that expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite and existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i += 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts,
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
if (getOwn(config.pkgs, baseName)) {
//If the baseName is a package name, then just treat it as one
//name to concat the name with.
normalizedBaseParts = baseParts = [baseName];
} else {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
}
name = normalizedBaseParts.concat(name.split('/'));
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('/');
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName;
}
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
foundStarMap = getOwn(starMap, nameSegment);
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = getOwn(config.paths, id);
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
removeScript(id);
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
context.require([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
nameParts = splitPrefix(name);
prefix = nameParts[0];
name = nameParts[1];
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = getOwn(defined, prefix);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
normalizedName = normalize(name, parentName, applyMap);
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
getModule(depMap).on(name, fn);
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length - 1, 0].concat(globalDefQueue));
globalDefQueue = [];
}
}
handlers = {
'require': function (mod) {
if (mod.require) {
return mod.require;
} else {
return (mod.require = context.makeRequire(mod.map));
}
},
'exports': function (mod) {
mod.usingExports = true;
if (mod.map.isDefine) {
if (mod.exports) {
return mod.exports;
} else {
return (mod.exports = defined[mod.map.id] = {});
}
}
},
'module': function (mod) {
if (mod.module) {
return mod.module;
} else {
return (mod.module = {
id: mod.map.id,
uri: mod.map.url,
config: function () {
return (config.config && getOwn(config.config, mod.map.id)) || {};
},
exports: defined[mod.map.id]
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
delete registry[id];
delete enabledRegistry[id];
}
function breakCycle(mod, traced, processed) {
var id = mod.map.id;
if (mod.error) {
mod.emit('error', mod.error);
} else {
traced[id] = true;
each(mod.depMaps, function (depMap, i) {
var depId = depMap.id,
dep = getOwn(registry, depId);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var map, modId, err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
map = mod.map;
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
this.fetch();
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error.
if (this.events.error) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
if (this.map.isDefine) {
//If setting exports via 'module' is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
cjsModule = this.module;
if (cjsModule &&
cjsModule.exports !== undefined &&
//Make sure it is not already the exports value
cjsModule.exports !== this.exports) {
exports = cjsModule.exports;
} else if (exports === undefined && this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = [this.map.id];
err.requireType = 'define';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
req.onResourceLoad(context, this.map, this.depMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap);
on(normalizedMap,
'defined', bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', this.errback);
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
eachProp(this.pluginMaps, bind(this, function (pluginMap) {
var mod = getOwn(registry, pluginMap.id);
if (mod && !mod.enabled) {
context.enable(pluginMap, this);
}
}));
this.enabling = false;
this.check();
},
on: function (name, cb) {
var cbs = this.events[name];
if (!cbs) {
cbs = this.events[name] = [];
}
cbs.push(cb);
},
emit: function (name, evt) {
each(this.events[name], function (cb) {
cb(evt);
});
if (name === 'error') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
//Save off the paths and packages since they require special processing,
//they are additive.
var pkgs = config.pkgs,
shim = config.shim,
objs = {
paths: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (prop === 'map') {
if (!config.map) {
config.map = {};
}
mixin(config[prop], value, true, true);
} else {
mixin(config[prop], value, true);
}
} else {
config[prop] = value;
}
});
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
location = pkgObj.location;
//Create a brand new object on pkgs, since currentPackages can
//be passed in again, and config.pkgs is the internal transformed
//state for all package configs.
pkgs[pkgObj.name] = {
name: pkgObj.name,
location: location || pkgObj.name,
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//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,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
},
makeShimExports: function (value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
},
makeRequire: function (relMap, options) {
options = options || {};
function localRequire(deps, callback, errback) {
var id, map, requireMod;
if (options.enableBuildCallback && callback && isFunction(callback)) {
callback.__requireJsBuild = true;
}
if (typeof deps === 'string') {
if (isFunction(callback)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
map = makeModuleMap(deps, relMap, false, true);
id = map.id;
if (!hasProp(defined, id)) {
return onError(makeError('notloaded', 'Module name "' +
id +
'" has not been loaded yet for context: ' +
contextName +
(relMap ? '' : '. Use require([])')));
}
return defined[id];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
if (index !== -1 && (!isRelative || index > 1)) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(normalize(moduleNamePlusExt,
relMap && relMap.id, true), ext, true);
},
defined: function (id) {
return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
},
specified: function (id) {
id = makeModuleMap(id, relMap, false, true).id;
return hasProp(defined, id) || hasProp(registry, id);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overriden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var found, args, mod,
shim = getOwn(config.shim, moduleName) || {},
shExports = shim.exports;
takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
//If already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
mod = getOwn(registry, moduleName);
if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
if (hasPathFallback(moduleName)) {
return;
} else {
return onError(makeError('nodefine',
'No define call for ' + moduleName,
null,
[moduleName]));
}
} else {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
parentPath;
//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. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
pkgs = config.pkgs;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
pkg = getOwn(pkgs, parentModule);
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
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;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callack function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
return onError(makeError('scripterror', 'Script error', evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = function (err) {
throw err;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation that a build has been done so that
//only one script needs to be loaded anyway. This may need to be
//reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = dataMain.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
dataMain = mainScript;
}
//Strip off any trailing .js since dataMain is now
//like a module name.
dataMain = dataMain.replace(jsSuffixRegExp, '');
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = [];
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps.length && isFunction(callback)) {
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this));
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
color: inherit;
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #eaeaea url('bg.png');
color: #4d4d4d;
width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
border: 1px solid #ccc;
position: relative;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
#todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
width: 2px;
position: absolute;
top: 0;
left: 40px;
height: 100%;
}
#todoapp input::-webkit-input-placeholder {
font-style: italic;
}
#todoapp input:-moz-placeholder {
font-style: italic;
color: #a9a9a9;
}
#todoapp h1 {
position: absolute;
top: -120px;
width: 100%;
font-size: 70px;
font-weight: bold;
text-align: center;
color: #b3b3b3;
color: rgba(255, 255, 255, 0.3);
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
#header {
padding-top: 15px;
border-radius: inherit;
}
#header:before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
height: 15px;
z-index: 2;
border-bottom: 1px solid #6c615c;
background: #8d7d77;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
#new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
z-index: 2;
box-shadow: none;
}
#main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
}
label[for='toggle-all'] {
display: none;
}
#toggle-all {
position: absolute;
top: -42px;
left: -4px;
width: 40px;
text-align: center;
border: none; /* Mobile Safari */
}
#toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
}
#toggle-all:checked:before {
color: #737373;
}
#todo-list {
margin: 0;
padding: 0;
list-style: none;
}
#todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
}
#todo-list li:last-child {
border-bottom: none;
}
#todo-list li.editing {
border-bottom: none;
padding: 0;
}
#todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
#todo-list li.editing .view {
display: none;
}
#todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
#todo-list li .toggle:after {
content: '✔';
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;
color: #d9d9d9;
text-shadow: 0 -1px 0 #bfbfbf;
}
#todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
}
#todo-list li label {
word-break: break-word;
padding: 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
-webkit-transition: color 0.4s;
-moz-transition: color 0.4s;
-ms-transition: color 0.4s;
-o-transition: color 0.4s;
transition: color 0.4s;
}
#todo-list li.completed label {
color: #a9a9a9;
text-decoration: line-through;
}
#todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 22px;
color: #a88a8a;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
#todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
-moz-transform: scale(1.3);
-ms-transform: scale(1.3);
-o-transform: scale(1.3);
transform: scale(1.3);
}
#todo-list li .destroy:after {
content: '✖';
}
#todo-list li:hover .destroy {
display: block;
}
#todo-list li .edit {
display: none;
}
#todo-list li.editing:last-child {
margin-bottom: -1px;
}
#footer {
color: #777;
padding: 0 15px;
position: absolute;
right: 0;
bottom: -31px;
left: 0;
height: 20px;
z-index: 1;
text-align: center;
}
#footer:before {
content: '';
position: absolute;
right: 0;
bottom: 31px;
left: 0;
height: 50px;
z-index: -1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
0 6px 0 -3px rgba(255, 255, 255, 0.8),
0 7px 1px -3px rgba(0, 0, 0, 0.3),
0 43px 0 -6px rgba(255, 255, 255, 0.8),
0 44px 2px -6px rgba(0, 0, 0, 0.2);
}
#todo-count {
float: left;
text-align: left;
}
#filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
#filters li {
display: inline;
}
#filters li a {
color: #83756f;
margin: 2px;
text-decoration: none;
}
#filters li a.selected {
font-weight: bold;
}
#clear-completed {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
font-size: 11px;
padding: 0 10px;
border-radius: 3px;
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
}
#clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
}
#info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
text-align: center;
}
#info a {
color: inherit;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
#toggle-all,
#todo-list li .toggle {
background: none;
}
#todo-list li .toggle {
height: 40px;
}
#toggle-all {
top: -56px;
left: -15px;
width: 65px;
height: 41px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
.hidden{
display:none;
}
(function () {
'use strict';
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
function getSourcePath() {
// If accessed via addyosmani.github.io/todomvc/, strip the project path.
if (location.hostname.indexOf('github.io') > 0) {
return location.pathname.replace(/todomvc\//, '');
}
return location.pathname;
}
function appendSourceLink() {
var sourceLink = document.createElement('a');
var paragraph = document.createElement('p');
var footer = document.getElementById('info');
var urlBase = 'https://github.com/addyosmani/todomvc/tree/gh-pages';
if (footer) {
sourceLink.href = urlBase + getSourcePath();
sourceLink.appendChild(document.createTextNode('Check out the source'));
paragraph.appendChild(sourceLink);
footer.appendChild(paragraph);
}
}
function redirect() {
if (location.hostname === 'addyosmani.github.io') {
location.href = location.href.replace('addyosmani.github.io/todomvc', 'todomvc.com');
}
}
appendSourceLink();
redirect();
})();
/* base.css overrides */ /* base.css overrides */
#footer, #main {
display: none;
}
.filter-active .completed, .filter-active .completed,
.filter-completed .active { .filter-completed .active {
display: none; display: none;
......
...@@ -4,11 +4,8 @@ ...@@ -4,11 +4,8 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Troop.js • TodoMVC</title> <title>Troop.js • TodoMVC</title>
<link rel="stylesheet" href="../../../assets/base.css"> <link rel="stylesheet" href="components/todomvc-common/base.css">
<link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/app.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head> </head>
<body> <body>
<section id="todoapp"> <section id="todoapp">
...@@ -22,7 +19,9 @@ ...@@ -22,7 +19,9 @@
<ul id="todo-list" data-weave="widget/list"></ul> <ul id="todo-list" data-weave="widget/list"></ul>
</section> </section>
<footer id="footer" data-weave="widget/display"> <footer id="footer" data-weave="widget/display">
<span id="todo-count" data-weave="widget/count"><strong>0</strong> items left</span> <span id="todo-count" data-weave="widget/count">
<strong>0</strong> items left
</span>
<ul id="filters" data-weave="widget/filters"> <ul id="filters" data-weave="widget/filters">
<li> <li>
<a href="#/">All</a> <a href="#/">All</a>
...@@ -42,7 +41,7 @@ ...@@ -42,7 +41,7 @@
<p>Created by <a href="http://github.com/mikaelkaron">Mikael Karon</a></p> <p>Created by <a href="http://github.com/mikaelkaron">Mikael Karon</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer> </footer>
<script src="../../../assets/base.js"></script> <script src="components/todomvc-common/base.js"></script>
<script type="text/javascript" data-main="js/app.js" src="../../../assets/require.min.js"></script> <script data-main="js/app.js" src="components/requirejs/require.js"></script>
</body> </body>
</html> </html>
/*newcap false*/
/*jshint newcap:false*/
require({ require({
'paths': { paths: {
'jquery': '../../../../assets/jquery.min', jquery: '../components/jquery/jquery',
'troopjs-bundle': 'lib/troopjs-bundle.min' 'troopjs-bundle': 'lib/troopjs-bundle'
} }
}, [ 'require', 'jquery', 'troopjs-bundle' ], function Deps(parentRequire, jQuery) { }, [
'require',
'jquery',
'troopjs-bundle'
], function Deps(parentRequire, $) {
'use strict';
// Application and plug-ins // Application and plug-ins
parentRequire([ parentRequire([
...@@ -11,10 +18,11 @@ require({ ...@@ -11,10 +18,11 @@ require({
'troopjs-jquery/weave', 'troopjs-jquery/weave',
'troopjs-jquery/destroy', 'troopjs-jquery/destroy',
'troopjs-jquery/hashchange', 'troopjs-jquery/hashchange',
'troopjs-jquery/action' ], function App(Application) { 'troopjs-jquery/action'
], function App(Application) {
// Hook ready // Hook ready
jQuery(document).ready(function ready($) { $(document).ready(function () {
Application($(this.body), 'app/todos').start(); Application($(this.body), 'app/todos').start();
}); });
}); });
......
/*global define*/
define({ define({
'store': 'todos-troopjs' store: 'todos-troopjs'
}); });
/*!
* TroopJS Bundle - 1.0.7-0-gf886cba
* http://troopjs.com/
* Copyright (c) 2012 Mikael Karon <mikael@karon.se>
* Licensed MIT
*/
/*!
* TroopJS RequireJS template plug-in
*
* parts of code from require-cs 0.4.0+ Copyright (c) 2010-2011, The Dojo Foundation
*
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true, newcap:false, loopfunc:true */
/*global define:true */
define('troopjs-requirejs/template',[],function TemplateModule() {
var FACTORIES = {
"node" : function () {
// Using special require.nodeRequire, something added by r.js.
var fs = require.nodeRequire("fs");
return function fetchText(path, callback) {
callback(fs.readFileSync(path, 'utf8'));
};
},
"browser" : function () {
// Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var progIds = [ "Msxml2.XMLHTTP", "Microsoft.XMLHTTP", "Msxml2.XMLHTTP.4.0"];
var progId;
var XHR;
var i;
if (typeof XMLHttpRequest !== "undefined") {
XHR = XMLHttpRequest;
}
else {
for (i = 0; i < 3; i++) {
progId = progIds[i];
try {
new ActiveXObject(progId);
XHR = function(){
return new ActiveXObject(progId);
};
break;
}
catch (e) {
}
}
if (!XHR){
throw new Error("XHR: XMLHttpRequest not available");
}
}
return function fetchText(url, callback) {
var xhr = new XHR();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
// Do not explicitly handle errors, those should be
// visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
};
},
"rhino" : function () {
var encoding = "utf-8";
var lineSeparator = java.lang.System.getProperty("line.separator");
// Why Java, why is this so awkward?
return function fetchText(path, callback) {
var file = new java.io.File(path);
var input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding));
var stringBuffer = new java.lang.StringBuffer();
var line;
var content = "";
try {
line = input.readLine();
// Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
// http://www.unicode.org/faq/utf_bom.html
// Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
if (line && line.length() && line.charAt(0) === 0xfeff) {
// Eat the BOM, since we've already found the encoding on this file,
// and we plan to concatenating this buffer with others; the BOM should
// only appear at the top of a file.
line = line.substring(1);
}
stringBuffer.append(line);
while ((line = input.readLine()) !== null) {
stringBuffer.append(lineSeparator);
stringBuffer.append(line);
}
// Make sure we return a JavaScript string and not a Java string.
content = String(stringBuffer.toString()); // String
} finally {
input.close();
}
callback(content);
};
},
"borked" : function () {
return function fetchText() {
throw new Error("Environment unsupported.");
};
}
};
var RE_SANITIZE = /^[\n\t\r]+|[\n\t\r]+$/g;
var RE_BLOCK = /<%(=)?([\S\s]*?)%>/g;
var RE_TOKENS = /<%(\d+)%>/gm;
var RE_REPLACE = /(["\n\t\r])/gm;
var RE_CLEAN = /o \+= "";| \+ ""/gm;
var EMPTY = "";
var REPLACE = {
"\"" : "\\\"",
"\n" : "\\n",
"\t" : "\\t",
"\r" : "\\r"
};
/**
* Compiles template
*
* @param body Template body
* @returns {Function}
*/
function compile(body) {
var blocks = [];
var length = 0;
function blocksTokens(original, prefix, block) {
blocks[length] = prefix
? "\" +" + block + "+ \""
: "\";" + block + "o += \"";
return "<%" + String(length++) + "%>";
}
function tokensBlocks(original, token) {
return blocks[token];
}
function replace(original, token) {
return REPLACE[token] || token;
}
return ("function template(data) { var o = \""
// Sanitize body before we start templating
+ body.replace(RE_SANITIZE, "")
// Replace script blocks with tokens
.replace(RE_BLOCK, blocksTokens)
// Replace unwanted tokens
.replace(RE_REPLACE, replace)
// Replace tokens with script blocks
.replace(RE_TOKENS, tokensBlocks)
+ "\"; return o; }")
// Clean
.replace(RE_CLEAN, EMPTY);
}
var buildMap = {};
var fetchText = FACTORIES[ typeof process !== "undefined" && process.versions && !!process.versions.node
? "node"
: (typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined"
? "browser"
: typeof Packages !== "undefined"
? "rhino"
: "borked" ]();
return {
load: function (name, parentRequire, load, config) {
var path = parentRequire.toUrl(name);
fetchText(path, function (text) {
try {
text = "define(function() { return " + compile(text, name, path, config.template) + "; })";
}
catch (err) {
err.message = "In " + path + ", " + err.message;
throw(err);
}
if (config.isBuild) {
buildMap[name] = text;
}
// IE with conditional comments on cannot handle the
// sourceURL trick, so skip it if enabled
/*@if (@_jscript) @else @*/
else {
text += "\n//@ sourceURL='" + path +"'";
}
/*@end@*/
load.fromText(name, text);
// Give result to load. Need to wait until the module
// is fully parse, which will happen after this
// execution.
parentRequire([name], function (value) {
load(value);
});
});
},
write: function (pluginName, name, write) {
if (buildMap.hasOwnProperty(name)) {
write.asModule(pluginName + "!" + name, buildMap[name]);
}
}
};
});
/*!
* TroopJS jQuery hashchange plug-in
*
* Normalized hashchange event, ripped a _lot_ of code from
* https://github.com/millermedeiros/Hasher
*
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true, evil:true */
/*global define:true */
define('troopjs-jquery/hashchange',[ "jquery" ], function HashchangeModule($) {
var INTERVAL = "interval";
var HASHCHANGE = "hashchange";
var ONHASHCHANGE = "on" + HASHCHANGE;
var RE_HASH = /#(.*)$/;
var RE_LOCAL = /\?/;
// hack based on this: http://code.google.com/p/closure-compiler/issues/detail?id=47#c13
var _isIE = /**@preserve@cc_on !@*/0;
function getHash(window) {
// parsed full URL instead of getting location.hash because Firefox
// decode hash value (and all the other browsers don't)
// also because of IE8 bug with hash query in local file
var result = RE_HASH.exec(window.location.href);
return result && result[1]
? decodeURIComponent(result[1])
: "";
}
function Frame(document) {
var self = this;
var element;
self.element = element = document.createElement("iframe");
element.src = "about:blank";
element.style.display = "none";
}
Frame.prototype = {
getElement : function () {
return this.element;
},
getHash : function () {
return this.element.contentWindow.frameHash;
},
update : function (hash) {
var self = this;
var document = self.element.contentWindow.document;
// Quick return if hash has not changed
if (self.getHash() === hash) {
return;
}
// update iframe content to force new history record.
// based on Really Simple History, SWFAddress and YUI.history.
document.open();
document.write("<html><head><title>' + document.title + '</title><script type='text/javascript'>var frameHash='" + hash + "';</script></head><body>&nbsp;</body></html>");
document.close();
}
};
$.event.special[HASHCHANGE] = {
/**
* @param data (Anything) Whatever eventData (optional) was passed in
* when binding the event.
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
* @param eventHandle (Function) The actual function that will be bound
* to the browser’s native event (this is used internally for the
* beforeunload event, you’ll never use it).
*/
setup : function hashChangeSetup(data, namespaces, eventHandle) {
var window = this;
// Quick return if we support onHashChange natively
// FF3.6+, IE8+, Chrome 5+, Safari 5+
if (ONHASHCHANGE in window) {
return false;
}
// Make sure we're always a window
if (!$.isWindow(window)) {
throw new Error("Unable to bind 'hashchange' to a non-window object");
}
var $window = $(window);
var hash = getHash(window);
var location = window.location;
$window.data(INTERVAL, window.setInterval(_isIE
? (function hashChangeIntervalWrapper() {
var document = window.document;
var _isLocal = location.protocol === "file:";
var frame = new Frame(document);
document.body.appendChild(frame.getElement());
frame.update(hash);
return function hashChangeInterval() {
var oldHash = hash;
var newHash;
var windowHash = getHash(window);
var frameHash = frame.getHash();
// Detect changes made pressing browser history buttons.
// Workaround since history.back() and history.forward() doesn't
// update hash value on IE6/7 but updates content of the iframe.
if (frameHash !== hash && frameHash !== windowHash) {
// Fix IE8 while offline
newHash = decodeURIComponent(frameHash);
if (hash !== newHash) {
hash = newHash;
frame.update(hash);
$window.trigger(HASHCHANGE, [ newHash, oldHash ]);
}
// Sync location.hash with frameHash
location.hash = "#" + encodeURI(_isLocal
? frameHash.replace(RE_LOCAL, "%3F")
: frameHash);
}
// detect if hash changed (manually or using setHash)
else if (windowHash !== hash) {
// Fix IE8 while offline
newHash = decodeURIComponent(windowHash);
if (hash !== newHash) {
hash = newHash;
$window.trigger(HASHCHANGE, [ newHash, oldHash ]);
}
}
};
})()
: function hashChangeInterval() {
var oldHash = hash;
var newHash;
var windowHash = getHash(window);
if (windowHash !== hash) {
// Fix IE8 while offline
newHash = decodeURIComponent(windowHash);
if (hash !== newHash) {
hash = newHash;
$window.trigger(HASHCHANGE, [ newHash, oldHash ]);
}
}
}, 25));
},
/**
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
*/
teardown : function hashChangeTeardown(namespaces) {
var window = this;
// Quick return if we support onHashChange natively
if (ONHASHCHANGE in window) {
return false;
}
window.clearInterval($.data(window, INTERVAL));
}
};
});
/*!
* TroopJS Utils getargs module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/getargs',[],function GetArgsModule() {
var PUSH = Array.prototype.push;
var SUBSTRING = String.prototype.substring;
var RE_BOOLEAN = /^(?:false|true)$/i;
var RE_BOOLEAN_TRUE = /^true$/i;
var RE_DIGIT = /^\d+$/;
return function getargs() {
var self = this;
var result = [];
var length;
var from;
var to;
var i;
var c;
var a;
var q = false;
// Iterate over string
for (from = to = i = 0, length = self.length; i < length; i++) {
// Get char
c = self.charAt(i);
switch(c) {
case "\"" :
case "'" :
// If we are currently quoted...
if (q === c) {
// Stop quote
q = false;
// Store result (no need to convert, we know this is a string)
PUSH.call(result, SUBSTRING.call(self, from, to));
}
// Otherwise
else {
// Start quote
q = c;
}
// Update from/to
from = to = i + 1;
break;
case "," :
// Continue if we're quoted
if (q) {
to = i + 1;
break;
}
// If we captured something...
if (from !== to) {
a = SUBSTRING.call(self, from, to);
if (RE_BOOLEAN.test(a)) {
a = RE_BOOLEAN_TRUE.test(a);
}
else if (RE_DIGIT.test(a)) {
a = +a;
}
// Store result
PUSH.call(result, a);
}
// Update from/to
from = to = i + 1;
break;
case " " :
case "\t" :
// Continue if we're quoted
if (q) {
to = i + 1;
break;
}
// Update from/to
if (from === to) {
from = to = i + 1;
}
break;
default :
// Update to
to = i + 1;
}
}
// If we captured something...
if (from !== to) {
a = SUBSTRING.call(self, from, to);
if (RE_BOOLEAN.test(a)) {
a = RE_BOOLEAN_TRUE.test(a);
}
else if (RE_DIGIT.test(a)) {
a = +a;
}
// Store result
PUSH.call(result, a);
}
return result;
};
});
/*!
* TroopJS jQuery action plug-in
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true */
/*global define:true */
define('troopjs-jquery/action',[ "jquery", "troopjs-utils/getargs" ], function ActionModule($, getargs) {
var UNDEFINED;
var FALSE = false;
var NULL = null;
var SLICE = Array.prototype.slice;
var ACTION = "action";
var ORIGINALEVENT = "originalEvent";
var RE_ACTION = /^([\w\d\s_\-\/]+)(?:\.([\w\.]+))?(?:\((.*)\))?$/;
var RE_DOT = /\.+/;
/**
* Namespace iterator
* @param namespace (string) namespace
* @param index (number) index
*/
function namespaceIterator(namespace, index) {
return namespace ? namespace + "." + ACTION : NULL;
}
/**
* Action handler
* @param $event (jQuery.Event) event
*/
function onAction($event) {
// Set $target
var $target = $(this);
// Get argv
var argv = SLICE.call(arguments, 1);
// Extract type
var type = ORIGINALEVENT in $event
? $event[ORIGINALEVENT].type
: ACTION;
// Extract name
var name = $event[ACTION];
// Reset $event.type
$event.type = ACTION + "/" + name + "." + type;
// Trigger 'ACTION/{name}.{type}'
$target.trigger($event, argv);
// No handler, try without namespace, but exclusive
if ($event.result !== FALSE) {
// Reset $event.type
$event.type = ACTION + "/" + name + "!";
// Trigger 'ACTION/{name}'
$target.trigger($event, argv);
// Still no handler, try generic action with namespace
if ($event.result !== FALSE) {
// Reset $event.type
$event.type = ACTION + "." + type;
// Trigger 'ACTION.{type}'
$target.trigger($event, argv);
}
}
}
/**
* Internal handler
*
* @param $event jQuery event
*/
function handler($event) {
// Get closest element that has an action defined
var $target = $($event.target).closest("[data-action]");
// Fail fast if there is no action available
if ($target.length === 0) {
return;
}
// Extract all data in one go
var $data = $target.data();
// Extract matches from 'data-action'
var matches = RE_ACTION.exec($data[ACTION]);
// Return fast if action parameter was f*cked (no matches)
if (matches === NULL) {
return;
}
// Extract action name
var name = matches[1];
// Extract action namespaces
var namespaces = matches[2];
// Extract action args
var args = matches[3];
// If there are action namespaces, make sure we're only triggering action on applicable types
if (namespaces !== UNDEFINED && !RegExp(namespaces.split(RE_DOT).join("|")).test($event.type)) {
return;
}
// Split args by separator (if there were args)
var argv = args !== UNDEFINED
? getargs.call(args)
: [];
// Iterate argv to determine arg type
$.each(argv, function argsIterator(i, value) {
if (value in $data) {
argv[i] = $data[value];
}
});
$target
// Trigger exclusive ACTION event
.trigger($.Event($event, {
type: ACTION + "!",
action: name
}), argv);
// Since we've translated the event, stop propagation
$event.stopPropagation();
}
$.event.special[ACTION] = {
/**
* @param data (Anything) Whatever eventData (optional) was passed in
* when binding the event.
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
* @param eventHandle (Function) The actual function that will be bound
* to the browser’s native event (this is used internally for the
* beforeunload event, you’ll never use it).
*/
setup : function onActionSetup(data, namespaces, eventHandle) {
$(this).bind(ACTION, data, onAction);
},
/**
* Do something each time an event handler is bound to a particular element
* @param handleObj (Object)
*/
add : function onActionAdd(handleObj) {
var events = $.map(handleObj.namespace.split(RE_DOT), namespaceIterator);
if (events.length !== 0) {
$(this).bind(events.join(" "), handler);
}
},
/**
* Do something each time an event handler is unbound from a particular element
* @param handleObj (Object)
*/
remove : function onActionRemove(handleObj) {
var events = $.map(handleObj.namespace.split(RE_DOT), namespaceIterator);
if (events.length !== 0) {
$(this).unbind(events.join(" "), handler);
}
},
/**
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
*/
teardown : function onActionTeardown(namespaces) {
$(this).unbind(ACTION, onAction);
}
};
$.fn[ACTION] = function action(name) {
return $(this).trigger({
type: ACTION + "!",
action: name
}, SLICE.call(arguments, 1));
};
});
/*!
* TroopJS jQuery weave plug-in
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true, loopfunc:true */
/*global define:true */
define('troopjs-jquery/weave',[ "jquery", "troopjs-utils/getargs", "require" ], function WeaveModule($, getargs, parentRequire) {
var UNDEFINED;
var NULL = null;
var ARRAY = Array;
var FUNCTION = Function;
var ARRAY_PROTO = ARRAY.prototype;
var JOIN = ARRAY_PROTO.join;
var PUSH = ARRAY_PROTO.push;
var POP = ARRAY_PROTO.pop;
var $WHEN = $.when;
var THEN = "then";
var WEAVE = "weave";
var UNWEAVE = "unweave";
var WOVEN = "woven";
var WEAVING = "weaving";
var PENDING = "pending";
var DESTROY = "destroy";
var DATA = "data-";
var DATA_WEAVE = DATA + WEAVE;
var DATA_WOVEN = DATA + WOVEN;
var DATA_WEAVING = DATA + WEAVING;
var SELECTOR_WEAVE = "[" + DATA_WEAVE + "]";
var SELECTOR_UNWEAVE = "[" + DATA_WEAVING + "],[" + DATA_WOVEN + "]";
/**
* Generic destroy handler.
* Simply makes sure that unweave has been called
*/
function onDestroy() {
$(this).unweave();
}
$.expr[":"][WEAVE] = $.expr.createPseudo
? $.expr.createPseudo(function (widgets) {
if (widgets !== UNDEFINED) {
widgets = RegExp($.map(getargs.call(widgets), function (widget) {
return "^" + widget + "$";
}).join("|"), "m");
}
return function (element, context, isXml) {
var weave = $(element).attr(DATA_WEAVE);
return weave === UNDEFINED
? false
: widgets === UNDEFINED
? true
: widgets.test(weave.split(/[\s,]+/).join("\n"));
};
})
: function (element, index, match) {
var weave = $(element).attr(DATA_WEAVE);
return weave === UNDEFINED
? false
: match === UNDEFINED
? true
: RegExp($.map(getargs.call(match[3]), function (widget) {
return "^" + widget + "$";
}).join("|"), "m").test(weave.split(/[\s,]+/).join("\n"));
};
$.expr[":"][WOVEN] = $.expr.createPseudo
? $.expr.createPseudo(function (widgets) {
if (widgets !== UNDEFINED) {
widgets = RegExp($.map(getargs.call(widgets), function (widget) {
return "^" + widget + "@\\d+";
}).join("|"), "m");
}
return function (element, context, isXml) {
var woven = $(element).attr(DATA_WOVEN);
return woven === UNDEFINED
? false
: widgets === UNDEFINED
? true
: widgets.test(woven.split(/[\s,]+/).join("\n"));
};
})
: function (element, index, match) {
var woven = $(element).attr(DATA_WOVEN);
return woven === UNDEFINED
? false
: match === UNDEFINED
? true
: RegExp($.map(getargs.call(match[3]), function (widget) {
return "^" + widget + "@\\d+";
}).join("|"), "m").test(woven.split(/[\s,]+/).join("\n"));
};
$.fn[WEAVE] = function weave(/* arg, arg, arg, deferred*/) {
var widgets = [];
var i = 0;
var $elements = $(this);
var arg = arguments;
var argc = arg.length;
// If deferred not a true Deferred, make it so
var deferred = argc > 0 && arg[argc - 1][THEN] instanceof FUNCTION
? POP.call(arg)
: $.Deferred();
$elements
// Reduce to only elements that can be woven
.filter(SELECTOR_WEAVE)
// Iterate
.each(function elementIterator(index, element) {
// Defer weave
$.Deferred(function deferredWeave(dfdWeave) {
var $element = $(element);
var $data = $element.data();
var weave = $data[WEAVE] = $element.attr(DATA_WEAVE) || "";
var woven = $data[WOVEN] || ($data[WOVEN] = []);
var pending = $data[PENDING] || ($data[PENDING] = []);
// Link deferred
dfdWeave.done(function doneWeave() {
$element
// Remove DATA_WEAVING
.removeAttr(DATA_WEAVING)
// Set DATA_WOVEN with full names
.attr(DATA_WOVEN, JOIN.call(arguments, " "));
});
// Wait for all pending deferred
$WHEN.apply($, pending).then(function donePending() {
var re = /[\s,]*([\w_\-\/\.]+)(?:\(([^\)]+)\))?/g;
var mark = i;
var j = 0;
var matches;
// Push dfdWeave on pending to signify we're starting a new task
PUSH.call(pending, dfdWeave);
$element
// Make sure to remove DATA_WEAVE (so we don't try processing this again)
.removeAttr(DATA_WEAVE)
// Set DATA_WEAVING (so that unweave can pick this up)
.attr(DATA_WEAVING, weave)
// Bind destroy event
.bind(DESTROY, onDestroy);
// Iterate woven (while RE_WEAVE matches)
while ((matches = re.exec(weave)) !== NULL) {
// Defer widget
$.Deferred(function deferredWidget(dfdWidget) {
var _j = j++; // store _j before we increment
var k;
var l;
var kMax;
var value;
// Add to widgets
widgets[i++] = dfdWidget;
// Link deferred
dfdWidget.then(function doneWidget(widget) {
woven[_j] = widget;
}, dfdWeave.reject, dfdWeave.notify);
// Get widget name
var name = matches[1];
// Set initial argv
var argv = [ $element, name ];
// Append values from arg to argv
for (k = 0, kMax = arg.length, l = argv.length; k < kMax; k++, l++) {
argv[l] = arg[k];
}
// Get widget args
var args = matches[2];
// Any widget arguments
if (args !== UNDEFINED) {
// Convert args using getargs
args = getargs.call(args);
// Append typed values from args to argv
for (k = 0, kMax = args.length, l = argv.length; k < kMax; k++, l++) {
// Get value
value = args[k];
// Get value from $data or fall back to pure value
argv[l] = value in $data
? $data[value]
: value;
}
}
// Require module
parentRequire([ name ], function required(Widget) {
// Defer start
$.Deferred(function deferredStart(dfdStart) {
// Constructed and initialized instance
var widget = Widget.apply(Widget, argv);
// Link deferred
dfdStart.then(function doneStart() {
dfdWidget.resolve(widget);
}, dfdWidget.reject, dfdWidget.notify);
// Start
widget.start(dfdStart);
});
});
});
}
// Slice out widgets woven for this element
$WHEN.apply($, widgets.slice(mark, i)).then(dfdWeave.resolve, dfdWeave.reject, dfdWeave.notify);
}, dfdWeave.reject, dfdWeave.notify);
});
});
// When all widgets are resolved, resolve original deferred
$WHEN.apply($, widgets).then(deferred.resolve, deferred.reject, deferred.notify);
return $elements;
};
$.fn[UNWEAVE] = function unweave(deferred) {
var widgets = [];
var i = 0;
var $elements = $(this);
// Create default deferred if none was passed
deferred = deferred || $.Deferred();
$elements
// Reduce to only elements that can be unwoven
.filter(SELECTOR_UNWEAVE)
// Iterate
.each(function elementIterator(index, element) {
// Defer unweave
$.Deferred(function deferredUnweave(dfdUnweave) {
var $element = $(element);
var $data = $element.data();
var pending = $data[PENDING] || ($data[PENDING] = []);
var woven = $data[WOVEN] || [];
// Link deferred
dfdUnweave.done(function doneUnweave() {
$element
// Copy weave data to data-weave attribute
.attr(DATA_WEAVE, $data[WEAVE])
// Make sure to clean the destroy event handler
.unbind(DESTROY, onDestroy);
// Remove data fore WEAVE
delete $data[WEAVE];
});
// Wait for all pending deferred
$WHEN.apply($, pending).done(function donePending() {
var mark = i;
var widget;
// Push dfdUnweave on pending to signify we're starting a new task
PUSH.call(pending, dfdUnweave);
// Remove WOVEN data
delete $data[WOVEN];
$element
// Remove DATA_WOVEN attribute
.removeAttr(DATA_WOVEN);
// Somewhat safe(r) iterator over woven
while ((widget = woven.shift()) !== UNDEFINED) {
// Defer widget
$.Deferred(function deferredWidget(dfdWidget) {
// Add to unwoven and pending
widgets[i++] = dfdWidget;
// $.Deferred stop
$.Deferred(function deferredStop(dfdStop) {
// Link deferred
dfdStop.then(function doneStop() {
dfdWidget.resolve(widget);
}, dfdWidget.reject, dfdWidget.notify);
// Stop
widget.stop(dfdStop);
});
});
}
// Slice out widgets unwoven for this element
$WHEN.apply($, widgets.slice(mark, i)).then(dfdUnweave.resolve, dfdUnweave.reject, dfdUnweave.notify);
});
});
});
// When all deferred are resolved, resolve original deferred
$WHEN.apply($, widgets).then(deferred.resolve, deferred.reject, deferred.notify);
return $elements;
};
$.fn[WOVEN] = function woven(/* arg, arg */) {
var result = [];
var widgets = arguments.length > 0
? RegExp($.map(arguments, function (widget) {
return "^" + widget + "$";
}).join("|"), "m")
: UNDEFINED;
$(this).each(function elementIterator(index, element) {
if (!$.hasData(element)) {
return;
}
PUSH.apply(result, widgets === UNDEFINED
? $.data(element, WOVEN)
: $.map($.data(element, WOVEN), function (woven) {
return widgets.test(woven.displayName)
? woven
: UNDEFINED;
}));
});
return result;
};
});
/*!
* TroopJS jQuery dimensions plug-in
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true */
/*global define:true */
define('troopjs-jquery/dimensions',[ "jquery" ], function DimensionsModule($) {
var NULL = null;
var DIMENSIONS = "dimensions";
var RESIZE = "resize." + DIMENSIONS;
var W = "w";
var H = "h";
var _W = "_" + W;
var _H = "_" + H;
/**
* Internal comparator used for reverse sorting arrays
*/
function reverse(a, b) {
return b - a;
}
/**
* Internal onResize handler
* @param $event
*/
function onResize($event) {
var $self = $(this);
var width = $self.width();
var height = $self.height();
// Iterate all dimensions
$.each($.data(self, DIMENSIONS), function dimensionIterator(namespace, dimension) {
var w = dimension[W];
var h = dimension[H];
var _w;
var _h;
var i;
i = w.length;
_w = w[i - 1];
while(w[--i] < width) {
_w = w[i];
}
i = h.length;
_h = h[i - 1];
while(h[--i] < height) {
_h = h[i];
}
// If _w or _h has changed, update and trigger
if (_w !== dimension[_W] || _h !== dimension[_H]) {
dimension[_W] = _w;
dimension[_H] = _h;
$self.trigger(DIMENSIONS + "." + namespace, [ _w, _h ]);
}
});
}
$.event.special[DIMENSIONS] = {
/**
* @param data (Anything) Whatever eventData (optional) was passed in
* when binding the event.
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
* @param eventHandle (Function) The actual function that will be bound
* to the browser’s native event (this is used internally for the
* beforeunload event, you’ll never use it).
*/
setup : function onDimensionsSetup(data, namespaces, eventHandle) {
$(this)
.bind(RESIZE, onResize)
.data(DIMENSIONS, {});
},
/**
* Do something each time an event handler is bound to a particular element
* @param handleObj (Object)
*/
add : function onDimensionsAdd(handleObj) {
var self = this;
var namespace = handleObj.namespace;
var dimension = {};
var w = dimension[W] = [];
var h = dimension[H] = [];
var re = /(w|h)(\d+)/g;
var matches;
while ((matches = re.exec(namespace)) !== NULL) {
dimension[matches[1]].push(parseInt(matches[2], 10));
}
w.sort(reverse);
h.sort(reverse);
$.data(self, DIMENSIONS)[namespace] = dimension;
},
/**
* Do something each time an event handler is unbound from a particular element
* @param handleObj (Object)
*/
remove : function onDimensionsRemove(handleObj) {
delete $.data(this, DIMENSIONS)[handleObj.namespace];
},
/**
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
*/
teardown : function onDimensionsTeardown(namespaces) {
$(this)
.removeData(DIMENSIONS)
.unbind(RESIZE, onResize);
}
};
});
/*!
* TroopJS jQuery destroy plug-in
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true */
/*global define:true */
define('troopjs-jquery/destroy',[ "jquery" ], function DestroyModule($) {
$.event.special.destroy = {
remove : function onDestroyRemove(handleObj) {
var self = this;
handleObj.handler.call(self, $.Event({
"type" : handleObj.type,
"data" : handleObj.data,
"namespace" : handleObj.namespace,
"target" : self
}));
}
};
});
/*!
* TroopJS jQuery resize plug-in
*
* Heavy inspiration from https://github.com/cowboy/jquery-resize.git
*
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true */
/*global define:true */
define('troopjs-jquery/resize',[ "jquery" ], function ResizeModule($) {
var NULL = null;
var RESIZE = "resize";
var W = "w";
var H = "h";
var $ELEMENTS = $([]);
var INTERVAL = NULL;
/**
* Iterator
* @param index
* @param self
*/
function iterator(index, self) {
// Get data
var $data = $.data(self);
// Get reference to $self
var $self = $(self);
// Get previous width and height
var w = $self.width();
var h = $self.height();
// Check if width or height has changed since last check
if (w !== $data[W] || h !== $data[H]) {
$self.trigger(RESIZE, [$data[W] = w, $data[H] = h]);
}
}
/**
* Internal interval
*/
function interval() {
$ELEMENTS.each(iterator);
}
$.event.special[RESIZE] = {
/**
* @param data (Anything) Whatever eventData (optional) was passed in
* when binding the event.
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
* @param eventHandle (Function) The actual function that will be bound
* to the browser’s native event (this is used internally for the
* beforeunload event, you’ll never use it).
*/
setup : function hashChangeSetup(data, namespaces, eventHandle) {
var self = this;
// window has a native resize event, exit fast
if ($.isWindow(self)) {
return false;
}
// Store data
var $data = $.data(self, RESIZE, {});
// Get reference to $self
var $self = $(self);
// Initialize data
$data[W] = $self.width();
$data[H] = $self.height();
// Add to tracked collection
$ELEMENTS = $ELEMENTS.add(self);
// If this is the first element, start interval
if($ELEMENTS.length === 1) {
INTERVAL = setInterval(interval, 100);
}
},
/**
* @param namespaces (Array) An array of namespaces specified when
* binding the event.
*/
teardown : function onDimensionsTeardown(namespaces) {
var self = this;
// window has a native resize event, exit fast
if ($.isWindow(self)) {
return false;
}
// Remove data
$.removeData(self, RESIZE);
// Remove from tracked collection
$ELEMENTS = $ELEMENTS.not(self);
// If this is the last element, stop interval
if($ELEMENTS.length === 0 && INTERVAL !== NULL) {
clearInterval(INTERVAL);
}
}
};
});
/*!
* TroopJS Utils merge module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/merge',[],function MergeModule() {
var ARRAY = Array;
var OBJECT = Object;
return function merge(source) {
var target = this;
var key = null;
var i;
var iMax;
var value;
var constructor;
for (i = 0, iMax = arguments.length; i < iMax; i++) {
source = arguments[i];
for (key in source) {
value = source[key];
constructor = value.constructor;
if (!(key in target)) {
target[key] = value;
}
else if (constructor === ARRAY) {
target[key] = target[key].concat(value);
}
else if (constructor === OBJECT) {
merge.call(target[key], value);
}
else {
target[key] = value;
}
}
}
return target;
};
});
/*!
* TroopJS Utils grep component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/grep',[ "jquery" ], function GrepModule($) {
return $.grep;
});
/*!
* TroopJS Utils tr component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/tr',[],function TrModule() {
var TYPEOF_NUMBER = typeof Number();
return function tr(callback) {
var self = this;
var result = [];
var i;
var length = self.length;
var key;
// Is this an array? Basically, is length a number, is it 0 or is it greater than 0 and that we have index 0 and index length-1
if (typeof length === TYPEOF_NUMBER && length === 0 || length > 0 && 0 in self && length - 1 in self) {
for (i = 0; i < length; i++) {
result.push(callback.call(self, self[i], i));
}
// Otherwise we'll iterate it as an object
} else if (self){
for (key in self) {
result.push(callback.call(self, self[key], key));
}
}
return result;
};
});
/*
* ComposeJS, object composition for JavaScript, featuring
* JavaScript-style prototype inheritance and composition, multiple inheritance,
* mixin and traits-inspired conflict resolution and composition
*/
(function(define){
define('compose',[], function(){
// function for creating instances from a prototype
function Create(){
}
var delegate = Object.create ?
function(proto){
return Object.create(typeof proto == "function" ? proto.prototype : proto || Object.prototype);
} :
function(proto){
Create.prototype = typeof proto == "function" ? proto.prototype : proto;
var instance = new Create();
Create.prototype = null;
return instance;
};
function validArg(arg){
if(!arg){
throw new Error("Compose arguments must be functions or objects");
}
return arg;
}
// this does the work of combining mixins/prototypes
function mixin(instance, args, i){
// use prototype inheritance for first arg
var value, argsLength = args.length;
for(; i < argsLength; i++){
var arg = args[i];
if(typeof arg == "function"){
// the arg is a function, use the prototype for the properties
var prototype = arg.prototype;
for(var key in prototype){
value = prototype[key];
var own = prototype.hasOwnProperty(key);
if(typeof value == "function" && key in instance && value !== instance[key]){
var existing = instance[key];
if(value == required){
// it is a required value, and we have satisfied it
value = existing;
}
else if(!own){
// if it is own property, it is considered an explicit override
// TODO: make faster calls on this, perhaps passing indices and caching
if(isInMethodChain(value, key, getBases([].slice.call(args, 0, i), true))){
// this value is in the existing method's override chain, we can use the existing method
value = existing;
}else if(!isInMethodChain(existing, key, getBases([arg], true))){
// the existing method is not in the current override chain, so we are left with a conflict
console.error("Conflicted method " + key + ", final composer must explicitly override with correct method.");
}
}
}
if(value && value.install && own && !isInMethodChain(existing, key, getBases([arg], true))){
// apply modifier
value.install.call(instance, key);
}else{
instance[key] = value;
}
}
}else{
// it is an object, copy properties, looking for modifiers
for(var key in validArg(arg)){
var value = arg[key];
if(typeof value == "function"){
if(value.install){
// apply modifier
value.install.call(instance, key);
continue;
}
if(key in instance){
if(value == required){
// required requirement met
continue;
}
}
}
// add it to the instance
instance[key] = value;
}
}
}
return instance;
}
// allow for override (by es5 module)
Compose._setMixin = function(newMixin){
mixin = newMixin;
};
function isInMethodChain(method, name, prototypes){
// searches for a method in the given prototype hierarchy
for(var i = 0; i < prototypes.length;i++){
var prototype = prototypes[i];
if(prototype[name] == method){
// found it
return true;
}
}
}
// Decorator branding
function Decorator(install, direct){
function Decorator(){
if(direct){
return direct.apply(this, arguments);
}
throw new Error("Decorator not applied");
}
Decorator.install = install;
return Decorator;
}
Compose.Decorator = Decorator;
// aspect applier
function aspect(handler){
return function(advice){
return Decorator(function install(key){
var baseMethod = this[key];
(advice = this[key] = baseMethod ? handler(this, baseMethod, advice) : advice).install = install;
}, advice);
};
};
// around advice, useful for calling super methods too
Compose.around = aspect(function(target, base, advice){
return advice.call(target, base);
});
Compose.before = aspect(function(target, base, advice){
return function(){
var results = advice.apply(this, arguments);
if(results !== stop){
return base.apply(this, results || arguments);
}
};
});
var stop = Compose.stop = {};
var undefined;
Compose.after = aspect(function(target, base, advice){
return function(){
var results = base.apply(this, arguments);
var adviceResults = advice.apply(this, arguments);
return adviceResults === undefined ? results : adviceResults;
};
});
// rename Decorator for calling super methods
Compose.from = function(trait, fromKey){
if(fromKey){
return (typeof trait == "function" ? trait.prototype : trait)[fromKey];
}
return Decorator(function(key){
if(!(this[key] = (typeof trait == "string" ? this[trait] :
(typeof trait == "function" ? trait.prototype : trait)[fromKey || key]))){
throw new Error("Source method " + fromKey + " was not available to be renamed to " + key);
}
});
};
// Composes an instance
Compose.create = function(base){
// create the instance
var instance = mixin(delegate(base), arguments, 1);
var argsLength = arguments.length;
// for go through the arguments and call the constructors (with no args)
for(var i = 0; i < argsLength; i++){
var arg = arguments[i];
if(typeof arg == "function"){
instance = arg.call(instance) || instance;
}
}
return instance;
}
// The required function, just throws an error if not overriden
function required(){
throw new Error("This method is required and no implementation has been provided");
};
Compose.required = required;
// get the value of |this| for direct function calls for this mode (strict in ES5)
function extend(){
var args = [this];
args.push.apply(args, arguments);
return Compose.apply(0, args);
}
// Compose a constructor
function Compose(base){
var args = arguments;
var prototype = (args.length < 2 && typeof args[0] != "function") ?
args[0] : // if there is just a single argument object, just use that as the prototype
mixin(delegate(validArg(base)), args, 1); // normally create a delegate to start with
function Constructor(){
var instance;
if(this instanceof Constructor){
// called with new operator, can proceed as is
instance = this;
}else{
// we allow for direct calls without a new operator, in this case we need to
// create the instance ourself.
Create.prototype = prototype;
instance = new Create();
}
// call all the constructors with the given arguments
for(var i = 0; i < constructorsLength; i++){
var constructor = constructors[i];
var result = constructor.apply(instance, arguments);
if(typeof result == "object"){
if(result instanceof Constructor){
instance = result;
}else{
for(var j in result){
if(result.hasOwnProperty(j)){
instance[j] = result[j];
}
}
}
}
}
return instance;
}
// create a function that can retrieve the bases (constructors or prototypes)
Constructor._getBases = function(prototype){
return prototype ? prototypes : constructors;
};
// now get the prototypes and the constructors
var constructors = getBases(args),
constructorsLength = constructors.length;
if(typeof args[args.length - 1] == "object"){
args[args.length - 1] = prototype;
}
var prototypes = getBases(args, true);
Constructor.extend = extend;
if(!Compose.secure){
prototype.constructor = Constructor;
}
Constructor.prototype = prototype;
return Constructor;
};
Compose.apply = function(thisObject, args){
// apply to the target
return thisObject ?
mixin(thisObject, args, 0) : // called with a target object, apply the supplied arguments as mixins to the target object
extend.apply.call(Compose, 0, args); // get the Function.prototype apply function, call() it to apply arguments to Compose (the extend doesn't matter, just a handle way to grab apply, since we can't get it off of Compose)
};
Compose.call = function(thisObject){
// call() should correspond with apply behavior
return mixin(thisObject, arguments, 1);
};
function getBases(args, prototype){
// this function registers a set of constructors for a class, eliminating duplicate
// constructors that may result from diamond construction for classes (B->A, C->A, D->B&C, then D() should only call A() once)
var bases = [];
function iterate(args, checkChildren){
outer:
for(var i = 0; i < args.length; i++){
var arg = args[i];
var target = prototype && typeof arg == "function" ?
arg.prototype : arg;
if(prototype || typeof arg == "function"){
var argGetBases = checkChildren && arg._getBases;
if(argGetBases){
iterate(argGetBases(prototype)); // don't need to check children for these, this should be pre-flattened
}else{
for(var j = 0; j < bases.length; j++){
if(target == bases[j]){
continue outer;
}
}
bases.push(target);
}
}
}
}
iterate(args, true);
return bases;
}
// returning the export of the module
return Compose;
});
})(typeof define != "undefined" ?
define: // AMD/RequireJS format if available
function(deps, factory){
if(typeof module !="undefined"){
module.exports = factory(); // CommonJS environment, like NodeJS
// require("./configure");
}else{
Compose = factory(); // raw script, assign to Compose global
}
});
/*!
* TroopJS Utils URI module
*
* parts of code from parseUri 1.2.2 Copyright Steven Levithan <stevenlevithan.com>
*
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true, newcap:false, forin:false, loopfunc:true */
/*global define:true */
define('troopjs-utils/uri',[ "compose" ], function URIModule(Compose) {
var NULL = null;
var ARRAY_PROTO = Array.prototype;
var OBJECT_PROTO = Object.prototype;
var PUSH = ARRAY_PROTO.push;
var SPLIT = String.prototype.split;
var TOSTRING = OBJECT_PROTO.toString;
var TOSTRING_OBJECT = TOSTRING.call(OBJECT_PROTO);
var TOSTRING_ARRAY = TOSTRING.call(ARRAY_PROTO);
var TOSTRING_STRING = TOSTRING.call(String.prototype);
var TOSTRING_FUNCTION = TOSTRING.call(Function.prototype);
var RE_URI = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:([^?#]*)(?:\?([^#]*))?(?:#(.*))?)/;
var PROTOCOL = "protocol";
var AUTHORITY = "authority";
var PATH = "path";
var QUERY = "query";
var ANCHOR = "anchor";
var KEYS = [ "source",
PROTOCOL,
AUTHORITY,
"userInfo",
"user",
"password",
"host",
"port",
PATH,
QUERY,
ANCHOR ];
// Store current Compose.secure setting
var SECURE = Compose.secure;
// Prevent Compose from creating constructor property
Compose.secure = true;
function Query(arg) {
var result = {};
var matches;
var key = NULL;
var value;
var re = /(?:&|^)([^&=]*)=?([^&]*)/g;
result.toString = Query.toString;
if (TOSTRING.call(arg) === TOSTRING_OBJECT) {
for (key in arg) {
result[key] = arg[key];
}
} else {
while ((matches = re.exec(arg)) !== NULL) {
key = matches[1];
if (key in result) {
value = result[key];
if (TOSTRING.call(value) === TOSTRING_ARRAY) {
value[value.length] = matches[2];
}
else {
result[key] = [ value, matches[2] ];
}
}
else {
result[key] = matches[2];
}
}
}
return result;
}
Query.toString = function toString() {
var self = this;
var key = NULL;
var value = NULL;
var values;
var query = [];
var i = 0;
var j;
for (key in self) {
if (TOSTRING.call(self[key]) === TOSTRING_FUNCTION) {
continue;
}
query[i++] = key;
}
query.sort();
while (i--) {
key = query[i];
value = self[key];
if (TOSTRING.call(value) === TOSTRING_ARRAY) {
values = value.slice(0);
values.sort();
j = values.length;
while (j--) {
value = values[j];
values[j] = value === ""
? key
: key + "=" + value;
}
query[i] = values.join("&");
}
else {
query[i] = value === ""
? key
: key + "=" + value;
}
}
return query.join("&");
};
// Extend on the instance of array rather than subclass it
function Path(arg) {
var result = [];
result.toString = Path.toString;
PUSH.apply(result, TOSTRING.call(arg) === TOSTRING_ARRAY
? arg
: SPLIT.call(arg, "/"));
return result;
}
Path.toString = function() {
return this.join("/");
};
var URI = Compose(function URI(str) {
var self = this;
var value;
var matches;
var i;
if ((matches = RE_URI.exec(str)) !== NULL) {
i = matches.length;
while (i--) {
value = matches[i];
if (value) {
self[KEYS[i]] = value;
}
}
}
if (QUERY in self) {
self[QUERY] = Query(self[QUERY]);
}
if (PATH in self) {
self[PATH] = Path(self[PATH]);
}
});
URI.prototype.toString = function () {
var self = this;
var uri = [ PROTOCOL , "://", AUTHORITY, PATH, "?", QUERY, "#", ANCHOR ];
var i;
var key;
if (!(PROTOCOL in self)) {
uri[0] = uri[1] = "";
}
if (!(AUTHORITY in self)) {
uri[2] = "";
}
if (!(PATH in self)) {
uri[3] = "";
}
if (!(QUERY in self)) {
uri[4] = uri[5] = "";
}
if (!(ANCHOR in self)) {
uri[6] = uri[7] = "";
}
i = uri.length;
while (i--) {
key = uri[i];
if (key in self) {
uri[i] = self[key];
}
}
return uri.join("");
};
// Restore Compose.secure setting
Compose.secure = SECURE;
URI.Path = Path;
URI.Query = Query;
return URI;
});
/*!
* TroopJS Utils each component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/each',[ "jquery" ], function EachModule($) {
return $.each;
});
/*!
* TroopJS Utils callbacks component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/callbacks',[ "jquery" ], function CallbacksModule($) {
return $.Callbacks;
});
/*!
* TroopJS Utils unique component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/unique',[],function UniqueModule() {
return function unique(callback) {
var self = this;
var length = self.length;
var result = [];
var value;
var i;
var j;
var k;
add: for (i = j = k = 0; i < length; i++, j = 0) {
value = self[i];
while(j < k) {
if (callback.call(self, value, result[j++]) === true) {
continue add;
}
}
result[k++] = value;
}
return result;
};
});
/*!
* TroopJS Utils when component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/when',[ "jquery" ], function WhenModule($) {
return $.when;
});
/*!
* TroopJS Utils deferred component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-utils/deferred',[ "jquery" ], function DeferredModule($) {
return $.Deferred;
});
/*!
* TroopJS event/emitter module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true */
/*global define:true */
define('troopjs-core/event/emitter',[ "compose" ], function EventEmitterModule(Compose) {
var UNDEFINED;
var TRUE = true;
var FALSE = false;
var FUNCTION = Function;
var MEMORY = "memory";
var CONTEXT = "context";
var CALLBACK = "callback";
var LENGTH = "length";
var HEAD = "head";
var TAIL = "tail";
var NEXT = "next";
var HANDLED = "handled";
var HANDLERS = "handlers";
var ROOT = {};
var COUNT = 0;
return Compose(function EventEmitter() {
this[HANDLERS] = {};
}, {
/**
* Subscribe to a event
*
* @param event Event to subscribe to
* @param context (optional) context to scope callbacks to
* @param memory (optional) do we want the last value applied to callbacks
* @param callback Callback for this event
* @returns self
*/
on : function on(event /*, context, memory, callback, callback, ..*/) {
var self = this;
var arg = arguments;
var length = arg[LENGTH];
var context = arg[1];
var memory = arg[2];
var callback = arg[3];
var handlers = self[HANDLERS];
var handler;
var handled;
var head;
var tail;
var offset;
// No context or memory was supplied
if (context instanceof FUNCTION) {
memory = FALSE;
context = ROOT;
offset = 1;
}
// Only memory was supplied
else if (context === TRUE || context === FALSE) {
memory = context;
context = ROOT;
offset = 2;
}
// Context was supplied, but not memory
else if (memory instanceof FUNCTION) {
memory = FALSE;
offset = 2;
}
// All arguments were supplied
else if (callback instanceof FUNCTION){
offset = 3;
}
// Something is wrong, return fast
else {
return self;
}
// Have handlers
if (event in handlers) {
// Get handlers
handlers = handlers[event];
// Create new handler
handler = {
"callback" : arg[offset++],
"context" : context
};
// Get tail handler
tail = TAIL in handlers
// Have tail, update handlers.tail.next to point to handler
? handlers[TAIL][NEXT] = handler
// Have no tail, update handlers.head to point to handler
: handlers[HEAD] = handler;
// Iterate handlers from offset
while (offset < length) {
// Set tail -> tail.next -> handler
tail = tail[NEXT] = {
"callback" : arg[offset++],
"context" : context
};
}
// Set tail handler
handlers[TAIL] = tail;
// Want memory and have memory
if (memory && MEMORY in handlers) {
// Get memory
memory = handlers[MEMORY];
// Get handled
handled = memory[HANDLED];
// Optimize for arguments
if (memory[LENGTH] > 0 ) {
// Loop through handlers
while(handler) {
// Skip to next handler if this handler has already been handled
if (handler[HANDLED] === handled) {
handler = handler[NEXT];
continue;
}
// Store handled
handler[HANDLED] = handled;
// Apply handler callback
handler[CALLBACK].apply(handler[CONTEXT], memory);
// Update handler
handler = handler[NEXT];
}
}
// Optimize for no arguments
else {
// Loop through handlers
while(handler) {
// Skip to next handler if this handler has already been handled
if (handler[HANDLED] === handled) {
handler = handler[NEXT];
continue;
}
// Store handled
handler[HANDLED] = handled;
// Call handler callback
handler[CALLBACK].call(handler[CONTEXT]);
// Update handler
handler = handler[NEXT];
}
}
}
}
// No handlers
else {
// Create head and tail
head = tail = {
"callback" : arg[offset++],
"context" : context
};
// Iterate handlers from offset
while (offset < length) {
// Set tail -> tail.next -> handler
tail = tail[NEXT] = {
"callback" : arg[offset++],
"context" : context
};
}
// Create event list
handlers[event] = {
"head" : head,
"tail" : tail
};
}
return self;
},
/**
* Unsubscribes from event
*
* @param event Event to unsubscribe from
* @param context (optional) context to scope callbacks to
* @param callback (optional) Callback to unsubscribe, if none
* are provided all callbacks are unsubscribed
* @returns self
*/
off : function off(event /*, context, callback, callback, ..*/) {
var self = this;
var arg = arguments;
var length = arg[LENGTH];
var context = arg[1];
var callback = arg[2];
var handlers = self[HANDLERS];
var handler;
var head;
var previous;
var offset;
// No context or memory was supplied
if (context instanceof FUNCTION) {
callback = context;
context = ROOT;
offset = 1;
}
// All arguments were supplied
else if (callback instanceof FUNCTION){
offset = 2;
}
// Something is wrong, return fast
else {
return self;
}
// Fast fail if we don't have subscribers
if (!(event in handlers)) {
return self;
}
// Get handlers
handlers = handlers[event];
// Get head
head = handlers[HEAD];
// Loop over remaining arguments
while (offset < length) {
// Store callback
callback = arg[offset++];
// Get first handler
handler = previous = head;
// Loop through handlers
do {
// Check if this handler should be unlinked
if (handler[CALLBACK] === callback && handler[CONTEXT] === context) {
// Is this the first handler
if (handler === head) {
// Re-link head and previous, then
// continue
head = previous = handler[NEXT];
continue;
}
// Unlink current handler, then continue
previous[NEXT] = handler[NEXT];
continue;
}
// Update previous pointer
previous = handler;
} while ((handler = handler[NEXT]) !== UNDEFINED);
}
// Update head and tail
if (head && previous) {
handlers[HEAD] = head;
handlers[TAIL] = previous;
}
else {
delete handlers[HEAD];
delete handlers[TAIL];
}
return self;
},
/**
* Emit an event
*
* @param event Event to emit
* @param arg (optional) Argument
* @returns self
*/
emit : function emit(event /*, arg, arg, ..*/) {
var self = this;
var arg = arguments;
var handlers = self[HANDLERS];
var handler;
// Store handled
var handled = arg[HANDLED] = COUNT++;
// Have handlers
if (event in handlers) {
// Get handlers
handlers = handlers[event];
// Remember arguments
handlers[MEMORY] = arg;
// Get first handler
handler = handlers[HEAD];
// Optimize for arguments
if (arg[LENGTH] > 0) {
// Loop through handlers
while(handler) {
// Skip to next handler if this handler has already been handled
if (handler[HANDLED] === handled) {
handler = handler[NEXT];
continue;
}
// Update handled
handler[HANDLED] = handled;
// Apply handler callback
handler[CALLBACK].apply(handler[CONTEXT], arg);
// Update handler
handler = handler[NEXT];
}
}
// Optimize for no arguments
else {
// Loop through handlers
while(handler) {
// Skip to next handler if this handler has already been handled
if (handler[HANDLED] === handled) {
handler = handler[NEXT];
continue;
}
// Update handled
handler[HANDLED] = handled;
// Call handler callback
handler[CALLBACK].call(handler[CONTEXT]);
// Update handler
handler = handler[NEXT];
}
}
}
// No handlers
else if (arg[LENGTH] > 0){
// Create handlers and store with event
handlers[event] = handlers = {};
// Remember arguments
handlers[MEMORY] = arg;
}
return this;
}
});
});
/*!
* TroopJS base component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true */
/*global define:true */
define('troopjs-core/component/base',[ "../event/emitter", "config" ], function ComponentModule(Emitter, config) {
var COUNT = 0;
var INSTANCE_COUNT = "instanceCount";
var Component = Emitter.extend(function Component() {
this[INSTANCE_COUNT] = COUNT++;
}, {
displayName : "core/component",
/**
* Application configuration
*/
config : config
});
/**
* Generates string representation of this object
* @returns Combination displayName and instanceCount
*/
Component.prototype.toString = function () {
var self = this;
return self.displayName + "@" + self[INSTANCE_COUNT];
};
return Component;
});
/*!
* TroopJS pubsub/hub module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true */
/*global define:true */
define('troopjs-core/pubsub/hub',[ "compose", "../component/base" ], function HubModule(Compose, Component) {
var from = Compose.from;
return Compose.create(Component, {
displayName: "core/pubsub/hub",
subscribe : from(Component, "on"),
unsubscribe : from(Component, "off"),
publish : from(Component, "emit")
});
});
/*!
* TroopJS gadget component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, newcap:false, forin:false, loopfunc:true */
/*global define:true */
define('troopjs-core/component/gadget',[ "compose", "./base", "troopjs-utils/deferred", "../pubsub/hub" ], function GadgetModule(Compose, Component, Deferred, hub) {
var UNDEFINED;
var NULL = null;
var FUNCTION = Function;
var RE_HUB = /^hub(?::(\w+))?\/(.+)/;
var RE_SIG = /^sig\/(.+)/;
var PUBLISH = hub.publish;
var SUBSCRIBE = hub.subscribe;
var UNSUBSCRIBE = hub.unsubscribe;
var MEMORY = "memory";
var SUBSCRIPTIONS = "subscriptions";
return Component.extend(function Gadget() {
var self = this;
var bases = self.constructor._getBases(true);
var base;
var callbacks;
var callback;
var i;
var j;
var jMax;
var signals = {};
var signal;
var matches;
var key = null;
// Iterate base chain (while there's a prototype)
for (i = bases.length - 1; i >= 0; i--) {
base = bases[i];
add: for (key in base) {
// Get value
callback = base[key];
// Continue if value is not a function
if (!(callback instanceof FUNCTION)) {
continue;
}
// Match signature in key
matches = RE_SIG.exec(key);
if (matches !== NULL) {
// Get signal
signal = matches[1];
// Have we stored any callbacks for this signal?
if (signal in signals) {
// Get callbacks (for this signal)
callbacks = signals[signal];
// Reset counters
j = jMax = callbacks.length;
// Loop callbacks, continue add if we've already added this callback
while (j--) {
if (callback === callbacks[j]) {
continue add;
}
}
// Add callback to callbacks chain
callbacks[jMax] = callback;
}
else {
// First callback
signals[signal] = [ callback ];
}
}
}
}
// Extend self
Compose.call(self, {
signal : function onSignal(signal, deferred) {
var _self = this;
var _callbacks;
var _j;
var head = deferred;
// Only trigger if we have callbacks for this signal
if (signal in signals) {
// Get callbacks
_callbacks = signals[signal];
// Reset counter
_j = _callbacks.length;
// Build deferred chain from end to 1
while (--_j) {
// Create new deferred
head = Deferred(function (dfd) {
// Store callback and deferred as they will have changed by the time we exec
var _callback = _callbacks[_j];
var _deferred = head;
// Add done handler
dfd.done(function done() {
_callback.call(_self, signal, _deferred);
});
});
}
// Execute first sCallback, use head deferred
_callbacks[0].call(_self, signal, head);
}
else if (deferred) {
deferred.resolve();
}
return _self;
}
});
}, {
displayName : "core/component/gadget",
"sig/initialize" : function initialize(signal, deferred) {
var self = this;
var subscriptions = self[SUBSCRIPTIONS] = [];
var key = NULL;
var value;
var matches;
var topic;
// Loop over each property in gadget
for (key in self) {
// Get value
value = self[key];
// Continue if value is not a function
if (!(value instanceof FUNCTION)) {
continue;
}
// Match signature in key
matches = RE_HUB.exec(key);
if (matches !== NULL) {
// Get topic
topic = matches[2];
// Subscribe
hub.subscribe(topic, self, matches[1] === MEMORY, value);
// Store in subscriptions
subscriptions[subscriptions.length] = [topic, self, value];
// NULL value
self[key] = NULL;
}
}
if (deferred) {
deferred.resolve();
}
return self;
},
"sig/finalize" : function finalize(signal, deferred) {
var self = this;
var subscriptions = self[SUBSCRIPTIONS];
var subscription;
// Loop over subscriptions
while ((subscription = subscriptions.shift()) !== UNDEFINED) {
hub.unsubscribe(subscription[0], subscription[1], subscription[2]);
}
if (deferred) {
deferred.resolve();
}
return self;
},
/**
* Calls hub.publish in self context
* @returns self
*/
publish : function publish() {
var self = this;
PUBLISH.apply(hub, arguments);
return self;
},
/**
* Calls hub.subscribe in self context
* @returns self
*/
subscribe : function subscribe() {
var self = this;
SUBSCRIBE.apply(hub, arguments);
return self;
},
/**
* Calls hub.unsubscribe in self context
* @returns self
*/
unsubscribe : function unsubscribe() {
var self = this;
UNSUBSCRIBE.apply(hub, arguments);
return self;
},
start : function start(deferred) {
var self = this;
deferred = deferred || Deferred();
Deferred(function deferredStart(dfdStart) {
dfdStart.then(deferred.resolve, deferred.reject, deferred.notify);
Deferred(function deferredInitialize(dfdInitialize) {
dfdInitialize.then(function doneInitialize() {
self.signal("start", dfdStart);
}, dfdStart.reject, dfdStart.notify);
self.signal("initialize", dfdInitialize);
});
});
return self;
},
stop : function stop(deferred) {
var self = this;
deferred = deferred || Deferred();
Deferred(function deferredFinalize(dfdFinalize) {
dfdFinalize.then(deferred.resolve, deferred.reject, deferred.notify);
Deferred(function deferredStop(dfdStop) {
dfdStop.then(function doneStop() {
self.signal("finalize", dfdFinalize);
}, dfdFinalize.reject, dfdFinalize.notify);
self.signal("stop", dfdStop);
});
});
return self;
}
});
});
/*!
* TroopJS service component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/component/service',[ "./gadget" ], function ServiceModule(Gadget) {
return Gadget.extend({
displayName : "core/component/service"
});
});
/*!
* TroopJS widget component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, newcap:false */
/*global define:true */
define('troopjs-core/component/widget',[ "./gadget", "jquery", "troopjs-utils/deferred" ], function WidgetModule(Gadget, $, Deferred) {
var UNDEFINED;
var NULL = null;
var FUNCTION = Function;
var ARRAY_PROTO = Array.prototype;
var SHIFT = ARRAY_PROTO.shift;
var UNSHIFT = ARRAY_PROTO.unshift;
var $TRIGGER = $.fn.trigger;
var $ONE = $.fn.one;
var $BIND = $.fn.bind;
var $UNBIND = $.fn.unbind;
var RE = /^dom(?::(\w+))?\/([^\.]+(?:\.(.+))?)/;
var REFRESH = "widget/refresh";
var $ELEMENT = "$element";
var $PROXIES = "$proxies";
var ONE = "one";
var THEN = "then";
var ATTR_WEAVE = "[data-weave]";
var ATTR_WOVEN = "[data-woven]";
/**
* Creates a proxy of the inner method 'handlerProxy' with the 'topic', 'widget' and handler parameters set
* @param topic event topic
* @param widget target widget
* @param handler target handler
* @returns {Function} proxied handler
*/
function eventProxy(topic, widget, handler) {
/**
* Creates a proxy of the outer method 'handler' that first adds 'topic' to the arguments passed
* @returns result of proxied hanlder invocation
*/
return function handlerProxy() {
// Add topic to front of arguments
UNSHIFT.call(arguments, topic);
// Apply with shifted arguments to handler
return handler.apply(widget, arguments);
};
}
/**
* Creates a proxy of the inner method 'render' with the '$fn' parameter set
* @param $fn jQuery method
* @returns {Function} proxied render
*/
function renderProxy($fn) {
/**
* Renders contents into element
* @param contents (Function | String) Template/String to render
* @param data (Object) If contents is a template - template data (optional)
* @param deferred (Deferred) Deferred (optional)
* @returns self
*/
function render(/* contents, data, ..., deferred */) {
var self = this;
var $element = self[$ELEMENT];
var arg = arguments;
// Shift contents from first argument
var contents = SHIFT.call(arg);
// Assume deferred is the last argument
var deferred = arg[arg.length - 1];
// If deferred not a true Deferred, make it so
if (deferred === UNDEFINED || !(deferred[THEN] instanceof FUNCTION)) {
deferred = Deferred();
}
// Defer render (as weaving it may need to load async)
Deferred(function deferredRender(dfdRender) {
// Link deferred
dfdRender.then(function renderDone() {
// Trigger refresh
$element.trigger(REFRESH, arguments);
// Resolve outer deferred
deferred.resolve();
}, deferred.reject, deferred.notify);
// Notify that we're about to render
dfdRender.notify("beforeRender", self);
// Call render with contents (or result of contents if it's a function)
$fn.call($element, contents instanceof FUNCTION ? contents.apply(self, arg) : contents);
// Notify that we're rendered
dfdRender.notify("afterRender", self);
// Weave element
$element.find(ATTR_WEAVE).weave(dfdRender);
});
return self;
}
return render;
}
return Gadget.extend(function Widget($element, displayName) {
var self = this;
self[$ELEMENT] = $element;
if (displayName) {
self.displayName = displayName;
}
}, {
displayName : "core/component/widget",
"sig/initialize" : function initialize(signal, deferred) {
var self = this;
var $element = self[$ELEMENT];
var $proxies = self[$PROXIES] = [];
var key = NULL;
var value;
var matches;
var topic;
// Loop over each property in widget
for (key in self) {
// Get value
value = self[key];
// Continue if value is not a function
if (!(value instanceof FUNCTION)) {
continue;
}
// Match signature in key
matches = RE.exec(key);
if (matches !== NULL) {
// Get topic
topic = matches[2];
// Replace value with a scoped proxy
value = eventProxy(topic, self, value);
// Either ONE or BIND element
(matches[2] === ONE ? $ONE : $BIND).call($element, topic, self, value);
// Store in $proxies
$proxies[$proxies.length] = [topic, value];
// NULL value
self[key] = NULL;
}
}
if (deferred) {
deferred.resolve();
}
return self;
},
"sig/finalize" : function finalize(signal, deferred) {
var self = this;
var $element = self[$ELEMENT];
var $proxies = self[$PROXIES];
var $proxy;
// Loop over subscriptions
while (($proxy = $proxies.shift()) !== UNDEFINED) {
$element.unbind($proxy[0], $proxy[1]);
}
delete self[$ELEMENT];
if (deferred) {
deferred.resolve();
}
return self;
},
/**
* Weaves all children of $element
* @param deferred (Deferred) Deferred (optional)
* @returns self
*/
weave : function weave(deferred) {
var self = this;
self[$ELEMENT].find(ATTR_WEAVE).weave(deferred);
return self;
},
/**
* Unweaves all children of $element _and_ self
* @param deferred (Deferred) Deferred (optional)
* @returns self
*/
unweave : function unweave(deferred) {
var self = this;
self[$ELEMENT].find(ATTR_WOVEN).andSelf().unweave(deferred);
return this;
},
/**
* Binds event from $element, exactly once
* @returns self
*/
one : function one() {
var self = this;
$ONE.apply(self[$ELEMENT], arguments);
return self;
},
/**
* Binds event to $element
* @returns self
*/
bind : function bind() {
var self = this;
$BIND.apply(self[$ELEMENT], arguments);
return self;
},
/**
* Unbinds event from $element
* @returns self
*/
unbind : function unbind() {
var self = this;
$UNBIND.apply(self[$ELEMENT], arguments);
return self;
},
/**
* Triggers event on $element
* @returns self
*/
trigger : function trigger() {
var self = this;
$TRIGGER.apply(self[$ELEMENT], arguments);
return self;
},
/**
* Renders content and inserts it before $element
*/
before : renderProxy($.fn.before),
/**
* Renders content and inserts it after $element
*/
after : renderProxy($.fn.after),
/**
* Renders content and replaces $element contents
*/
html : renderProxy($.fn.html),
/**
* Renders content and replaces $element contents
*/
text : renderProxy($.fn.text),
/**
* Renders content and appends it to $element
*/
append : renderProxy($.fn.append),
/**
* Renders content and prepends it to $element
*/
prepend : renderProxy($.fn.prepend),
/**
* Empties widget
* @param deferred (Deferred) Deferred (optional)
* @returns self
*/
empty : function empty(deferred) {
var self = this;
// Ensure we have deferred
deferred = deferred || Deferred();
// Create deferred for emptying
Deferred(function emptyDeferred(dfdEmpty) {
// Link deferred
dfdEmpty.then(deferred.resolve, deferred.reject, deferred.notify);
// Get element
var $element = self[$ELEMENT];
// Detach contents
var $contents = $element.contents().detach();
// Trigger refresh
$element.trigger(REFRESH, self);
// Use timeout in order to yield
setTimeout(function emptyTimeout() {
// Get DOM elements
var contents = $contents.get();
// Remove elements from DOM
$contents.remove();
// Resolve deferred
dfdEmpty.resolve(contents);
}, 0);
});
return self;
}
});
});
/*!
* TroopJS dimensions/service module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/dimensions/service',[ "../component/service" ], function DimensionsServiceModule(Service) {
var DIMENSIONS = "dimensions";
var $ELEMENT = "$element";
function onDimensions($event, w, h) {
$event.data.publish(DIMENSIONS, w, h);
}
return Service.extend(function DimensionsService($element, dimensions) {
var self = this;
self[$ELEMENT] = $element;
self[DIMENSIONS] = dimensions;
}, {
displayName : "core/dimensions/service",
"sig/initialize" : function initialize(signal, deferred) {
var self = this;
self[$ELEMENT].bind(DIMENSIONS + "." + self[DIMENSIONS], self, onDimensions);
if (deferred) {
deferred.resolve();
}
},
"sig/start" : function start(signal, deferred) {
var self = this;
self[$ELEMENT].trigger("resize." + DIMENSIONS);
if (deferred) {
deferred.resolve();
}
},
"sig/finalize" : function finalize(signal, deferred) {
var self = this;
self[$ELEMENT].unbind(DIMENSIONS + "." + self[DIMENSIONS], onDimensions);
if (deferred) {
deferred.resolve();
}
}
});
});
/*!
* TroopJS store/base module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/store/base',[ "compose", "../component/gadget" ], function StoreModule(Compose, Gadget) {
var STORAGE = "storage";
return Gadget.extend({
storage : Compose.required,
set : function set(key, value, deferred) {
// JSON encoded 'value' then store as 'key'
this[STORAGE].setItem(key, JSON.stringify(value));
// Resolve deferred
if (deferred) {
deferred.resolve(value);
}
},
get : function get(key, deferred) {
// Get value from 'key', parse JSON
var value = JSON.parse(this[STORAGE].getItem(key));
// Resolve deferred
if (deferred) {
deferred.resolve(value);
}
},
remove : function remove(key, deferred) {
// Remove key
this[STORAGE].removeItem(key);
// Resolve deferred
if (deferred) {
deferred.resolve();
}
},
clear : function clear(deferred) {
// Clear
this[STORAGE].clear();
// Resolve deferred
if (deferred) {
deferred.resolve();
}
}
});
});
/*!
* TroopJS store/session module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/store/session',[ "compose", "./base" ], function StoreSessionModule(Compose, Store) {
return Compose.create(Store, {
displayName : "core/store/session",
storage: window.sessionStorage
});
});
/*!
* TroopJS store/local module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/store/local',[ "compose", "./base" ], function StoreLocalModule(Compose, Store) {
return Compose.create(Store, {
displayName : "core/store/local",
storage : window.localStorage
});
});
/*!
* TroopJS route/router module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/route/router',[ "../component/service", "troopjs-utils/uri" ], function RouterModule(Service, URI) {
var HASHCHANGE = "hashchange";
var $ELEMENT = "$element";
var ROUTE = "route";
var RE = /^#/;
function onHashChange($event) {
var self = $event.data;
// Create URI
var uri = URI($event.target.location.hash.replace(RE, ""));
// Convert to string
var route = uri.toString();
// Did anything change?
if (route !== self[ROUTE]) {
// Store new value
self[ROUTE] = route;
// Publish route
self.publish(ROUTE, uri);
}
}
return Service.extend(function RouterService($element) {
this[$ELEMENT] = $element;
}, {
displayName : "core/route/router",
"sig/initialize" : function initialize(signal, deferred) {
var self = this;
self[$ELEMENT].bind(HASHCHANGE, self, onHashChange);
if (deferred) {
deferred.resolve();
}
return self;
},
"sig/start" : function start(signal, deferred) {
var self = this;
self[$ELEMENT].trigger(HASHCHANGE);
if (deferred) {
deferred.resolve();
}
return self;
},
"sig/finalize" : function finalize(signal, deferred) {
var self = this;
self[$ELEMENT].unbind(HASHCHANGE, onHashChange);
if (deferred) {
deferred.resolve();
}
return self;
}
});
});
/*!
* TroopJS widget/placeholder component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true */
/*global define:true */
define('troopjs-core/widget/placeholder',[ "../component/widget", "troopjs-utils/deferred", "require" ], function WidgetPlaceholderModule(Widget, Deferred, parentRequire) {
var FUNCTION = Function;
var POP = Array.prototype.pop;
var HOLDING = "holding";
var DATA_HOLDING = "data-" + HOLDING;
var $ELEMENT = "$element";
var TARGET = "target";
var THEN = "then";
function release(/* arg, arg, arg, deferred*/) {
var self = this;
var arg = arguments;
var argc = arg.length;
// If deferred not a true Deferred, make it so
var deferred = argc > 0 && arg[argc - 1][THEN] instanceof FUNCTION
? POP.call(arg)
: Deferred();
Deferred(function deferredRelease(dfdRelease) {
var i;
var iMax;
var name;
var argv;
// We're already holding something, resolve with cache
if (HOLDING in self) {
dfdRelease
.done(deferred.resolve)
.resolve(self[HOLDING]);
}
else {
// Add done handler to release
dfdRelease.then([ function doneRelease(widget) {
// Set DATA_HOLDING attribute
self[$ELEMENT].attr(DATA_HOLDING, widget);
// Store widget
self[HOLDING] = widget;
}, deferred.resolve ], deferred.reject, deferred.notify);
// Get widget name
name = self[TARGET];
// Set initial argv
argv = [ self[$ELEMENT], name ];
// Append values from arg to argv
for (i = 0, iMax = arg.length; i < iMax; i++) {
argv[i + 2] = arg[i];
}
// Require widget by name
parentRequire([ name ], function required(Widget) {
// Defer require
Deferred(function deferredStart(dfdRequire) {
// Constructed and initialized instance
var widget = Widget
.apply(Widget, argv);
// Link deferred
dfdRequire.then(function doneStart() {
dfdRelease.resolve(widget);
}, dfdRelease.reject, dfdRelease.notify);
// Start
widget.start(dfdRequire);
});
});
}
});
return self;
}
function hold(deferred) {
var self = this;
deferred = deferred || Deferred();
Deferred(function deferredHold(dfdHold) {
var widget;
// Link deferred
dfdHold.then(deferred.resolve, deferred.reject, deferred.notify);
// Check that we are holding
if (HOLDING in self) {
// Get what we're holding
widget = self[HOLDING];
// Cleanup
delete self[HOLDING];
// Remove DATA_HOLDING attribute
self[$ELEMENT].removeAttr(DATA_HOLDING);
// Stop
widget.stop(dfdHold);
}
else {
dfdHold.resolve();
}
});
return self;
}
return Widget.extend(function WidgetPlaceholder($element, name, target) {
this[TARGET] = target;
}, {
displayName : "core/widget/placeholder",
"sig/finalize" : function finalize(signal, deferred) {
this.hold(deferred);
},
release : release,
hold : hold
});
});
/*!
* TroopJS route/placeholder module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/route/placeholder',[ "../widget/placeholder" ], function RoutePlaceholderModule(Placeholder) {
var NULL = null;
var ROUTE = "route";
return Placeholder.extend(function RoutePlaceholderWidget($element, name) {
this[ROUTE] = RegExp($element.data("route"));
}, {
"displayName" : "core/route/placeholder",
"hub:memory/route" : function onRoute(topic, uri) {
var self = this;
var matches = self[ROUTE].exec(uri.path);
if (matches !== NULL) {
self.release.apply(self, matches.slice(1));
}
else {
self.hold();
}
}
});
});
/*!
* TroopJS widget/application component
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/widget/application',[ "../component/widget", "troopjs-utils/deferred" ], function ApplicationModule(Widget, Deferred) {
return Widget.extend({
displayName : "core/widget/application",
"sig/start" : function start(signal, deferred) {
this.weave(deferred);
},
"sig/stop" : function stop(signal, deferred) {
this.unweave(deferred);
}
});
});
/*!
* TroopJS pubsub/topic module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
/*jshint strict:false, smarttabs:true, laxbreak:true */
/*global define:true */
define('troopjs-core/pubsub/topic',[ "../component/base", "troopjs-utils/unique" ], function TopicModule(Component, unique) {
var TOSTRING = Object.prototype.toString;
var TOSTRING_ARRAY = TOSTRING.call(Array.prototype);
function comparator (a, b) {
return a.publisherInstanceCount === b.publisherInstanceCount;
}
var Topic = Component.extend(function Topic(topic, publisher, parent) {
var self = this;
self.topic = topic;
self.publisher = publisher;
self.parent = parent;
self.publisherInstanceCount = publisher.instanceCount;
}, {
displayName : "core/pubsub/topic",
/**
* Traces topic origin to root
* @returns String representation of all topics traced down to root
*/
trace : function trace() {
var current = this;
var constructor = current.constructor;
var parent;
var item;
var stack = "";
var i;
var u;
var iMax;
while (current) {
if (TOSTRING.call(current) === TOSTRING_ARRAY) {
u = unique.call(current, comparator);
for (i = 0, iMax = u.length; i < iMax; i++) {
item = u[i];
u[i] = item.constructor === constructor
? item.trace()
: item.topic;
}
stack += u.join(",");
break;
}
parent = current.parent;
stack += parent
? current.publisher + ":"
: current.publisher;
current = parent;
}
return stack;
}
});
/**
* Generates string representation of this object
* @returns Instance topic
*/
Topic.prototype.toString = function () {
return this.topic;
};
return Topic;
});
/*!
* TroopJS remote/ajax module
* @license TroopJS Copyright 2012, Mikael Karon <mikael@karon.se>
* Released under the MIT license.
*/
define('troopjs-core/remote/ajax',[ "../component/service", "../pubsub/topic", "jquery", "troopjs-utils/merge" ], function AjaxModule(Service, Topic, $, merge) {
return Service.extend({
displayName : "core/remote/ajax",
"hub/ajax" : function request(topic, settings, deferred) {
// Request
$.ajax(merge.call({
"headers": {
"x-request-id": new Date().getTime(),
"x-components": topic instanceof Topic ? topic.trace() : topic
}
}, settings)).then(deferred.resolve, deferred.reject, deferred.notify);
}
});
});
define("template",[],function(){function f(e){function l(e,n,r){return t[f]=n?'" +'+r+'+ "':'";'+r+'o += "',"<%"+String(f++)+"%>"}function c(e,n){return t[n]}function h(e,t){return a[t]||t}var t=[],f=0;return('function template(data) { var o = "'+e.replace(n,"").replace(r,l).replace(s,h).replace(i,c)+'"; return o; }').replace(o,u)}var t={node:function(){var e=require.nodeRequire("fs");return function(n,r){r(e.readFileSync(n,"utf8"))}},browser:function(){var e=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],t,n,r;if(typeof XMLHttpRequest!="undefined")n=XMLHttpRequest;else e:{for(r=0;r<3;r++){t=e[r];try{n=ActiveXObject(t);break e}catch(i){}}throw new Error("XHR: XMLHttpRequest not available")}return function(t,r){var i=new n;i.open("GET",t,!0),i.onreadystatechange=function(e){i.readyState===4&&r(i.responseText)},i.send(null)}},rhino:function(){var e="utf-8",t=java.lang.System.getProperty("line.separator");return function(r,i){var s=new java.io.File(r),o=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(s),e)),u=new java.lang.StringBuffer,a,f="";try{a=o.readLine(),a&&a.length()&&a.charAt(0)===65279&&(a=a.substring(1)),u.append(a);while((a=o.readLine())!==null)u.append(t),u.append(a);f=String(u.toString())}finally{o.close()}i(f)}},borked:function(){return function(){throw new Error("Environment unsupported.")}}},n=/^[\n\t\r]+|[\n\t\r]+$/g,r=/<%(=)?([\S\s]*?)%>/g,i=/<%(\d+)%>/gm,s=/(["\n\t\r])/gm,o=/o \+= "";| \+ ""/gm,u="",a={'"':'\\"',"\n":"\\n"," ":"\\t","\r":"\\r"},l={},c=t[typeof process!="undefined"&&process.versions&&!!process.versions.node?"node":typeof window!="undefined"&&window.navigator&&window.document||typeof importScripts!="undefined"?"browser":typeof Packages!="undefined"?"rhino":"borked"]();return{load:function(e,t,n,r){var i=t.toUrl(e);c(i,function(s){try{s="define(function() { return "+f(s,e,i,r.template)+"; })"}catch(o){throw o.message="In "+i+", "+o.message,o}r.isBuild?l[e]=s:s+="\n//@ sourceURL='"+i+"'",n.fromText(e,s),t([e],function(e){n(e)})})},write:function(e,t,n){l.hasOwnProperty(t)&&n.asModule(e+"!"+t,l[t])}}}),function(e){e("compose",[],function(){function e(){}function n(e){if(!e)throw new Error("Compose arguments must be functions or objects");return e}function r(e,t,r){var s,o=t.length;for(;r<o;r++){var u=t[r];if(typeof u=="function"){var a=u.prototype;for(var l in a){s=a[l];var c=a.hasOwnProperty(l);if(typeof s=="function"&&l in e&&s!==e[l]){var p=e[l];s==f?s=p:c||(i(s,l,h([].slice.call(t,0,r),!0))?s=p:i(p,l,h([u],!0))||console.error("Conflicted method "+l+", final composer must explicitly override with correct method."))}s&&s.install&&c&&!i(p,l,h([u],!0))?s.install.call(e,l):e[l]=s}}else for(var l in n(u)){var s=u[l];if(typeof s=="function"){if(s.install){s.install.call(e,l);continue}if(l in e&&s==f)continue}e[l]=s}}return e}function i(e,t,n){for(var r=0;r<n.length;r++){var i=n[r];if(i[t]==e)return!0}}function s(e,t){function n(){if(t)return t.apply(this,arguments);throw new Error("Decorator not applied")}return n.install=e,n}function o(e){return function(t){return s(function n(r){var i=this[r];(t=this[r]=i?e(this,i,t):t).install=n},t)}}function f(){throw new Error("This method is required and no implementation has been provided")}function l(){var e=[this];return e.push.apply(e,arguments),c.apply(0,e)}function c(i){function u(){var t;this instanceof u?t=this:(e.prototype=o,t=new e);for(var n=0;n<f;n++){var r=a[n],i=r.apply(t,arguments);if(typeof i=="object")if(i instanceof u)t=i;else for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])}return t}var s=arguments,o=s.length<2&&typeof s[0]!="function"?s[0]:r(t(n(i)),s,1);u._getBases=function(e){return e?p:a};var a=h(s),f=a.length;typeof s[s.length-1]=="object"&&(s[s.length-1]=o);var p=h(s,!0);return u.extend=l,c.secure||(o.constructor=u),u.prototype=o,u}function h(e,t){function r(e,i){e:for(var s=0;s<e.length;s++){var o=e[s],u=t&&typeof o=="function"?o.prototype:o;if(t||typeof o=="function"){var a=i&&o._getBases;if(a)r(a(t));else{for(var f=0;f<n.length;f++)if(u==n[f])continue e;n.push(u)}}}}var n=[];return r(e,!0),n}var t=Object.create?function(e){return Object.create(typeof e=="function"?e.prototype:e||Object.prototype)}:function(t){e.prototype=typeof t=="function"?t.prototype:t;var n=new e;return e.prototype=null,n};c._setMixin=function(e){r=e},c.Decorator=s,c.around=o(function(e,t,n){return n.call(e,t)}),c.before=o(function(e,t,n){return function(){var e=n.apply(this,arguments);if(e!==u)return t.apply(this,e||arguments)}});var u=c.stop={},a;return c.after=o(function(e,t,n){return function(){var e=t.apply(this,arguments),r=n.apply(this,arguments);return r===a?e:r}}),c.from=function(e,t){return t?(typeof e=="function"?e.prototype:e)[t]:s(function(n){if(!(this[n]=typeof e=="string"?this[e]:(typeof e=="function"?e.prototype:e)[t||n]))throw new Error("Source method "+t+" was not available to be renamed to "+n)})},c.create=function(e){var n=r(t(e),arguments,1),i=arguments.length;for(var s=0;s<i;s++){var o=arguments[s];typeof o=="function"&&(n=o.call(n)||n)}return n},c.required=f,c.apply=function(e,t){return e?r(e,t,0):l.apply.call(c,0,t)},c.call=function(e){return r(e,arguments,1)},c})}(typeof define!="undefined"?define:function(e,t){typeof module!="undefined"?module.exports=t():Compose=t()}),define("troopjs-core/component/base",["compose","config"],function(t,n){var r=0;return t(function(){this.instanceCount=r++},{displayName:"core/component",config:n,toString:function i(){var e=this;return e.displayName+"@"+e.instanceCount}})}),define("troopjs-core/util/deferred",["jquery"],function(t){return t.Deferred}),define("troopjs-core/util/unique",[],function(){return function(t){var n=this,r=n.length,i=[],s,o,u,a;e:for(o=u=a=0;o<r;o++,u=0){s=n[o];while(u<a)if(t.call(n,s,i[u++])===!0)continue e;i[a++]=s}return i}}),define("troopjs-core/pubsub/topic",["../component/base","../util/unique"],function(t,n){function s(e,t){return e.publisherInstanceCount===t.publisherInstanceCount}var r=Object.prototype.toString,i=r.call(Array.prototype);return t.extend(function(t,n,r){var i=this;i.topic=t,i.publisher=n,i.parent=r,i.publisherInstanceCount=n.instanceCount},{displayName:"core/pubsub/topic",toString:function o(){return this.topic},trace:function(){var t=this,o=t.constructor,u,a,f="",l,c,h;while(t){if(r.call(t)===i){c=n.call(t,s);for(l=0,h=c.length;l<h;l++)a=c[l],c[l]=a.constructor===o?a.trace():a.topic;f+=c.join(",");break}u=t.parent,f+=u?t.publisher+":":t.publisher,t=u}return f}})}),define("troopjs-core/pubsub/hub",["compose","../component/base","./topic"],function(t,n,r){var i=Function,s="memory",o="context",u="callback",a="length",f="head",l="tail",c="next",h="handled",p={},d={},v=0;return t.create({displayName:"core/pubsub/hub",subscribe:function(t){var n=this,r=arguments[a],v=arguments[1],m=arguments[2],g=arguments[3],y,b,w,E,S,x;if(v instanceof i)g=v,m=!1,v=p,y=1;else if(v===!0||v===!1)g=m,m=v,v=p,y=2;else if(m instanceof i)g=m,m=!1,y=2;else{if(!(g instanceof i))return n;y=3}if(t in d){b=d[t],w={callback:arguments[y++],context:v},x=l in b?b[l][c]=w:b[f]=w;while(y<r)x=x[c]={callback:arguments[y++],context:v};b[l]=x;if(m&&s in b){m=b[s],E=m[h];if(m[a]>0)while(w){if(w[h]===E){w=w[c];continue}w[h]=E,w[u].apply(w[o],m),w=w[c]}else while(w){if(w[h]===E){w=w[c];continue}w[h]=E,w[u].call(w[o]),w=w[c]}}}else{S=x={callback:arguments[y++],context:v};while(y<r)x=x[c]={callback:arguments[y++],context:v};d[t]={head:S,tail:x}}return n},unsubscribe:function(t){var n=arguments[a],r=arguments[1],s=arguments[2],h,v,m,g,y=null;if(r instanceof i)s=r,r=p,h=1;else{if(!(s instanceof i))return self;h=2}e:{if(!(t in d))break e;v=d[t],g=v[f];while(h<n){s=arguments[h++],m=y=g;do{if(m[u]===s&&m[o]===r){if(m===g){g=y=m[c];continue}y[c]=m[c];continue}y=m}while(m=m[c])}g&&y?(v[f]=g,v[l]=y):(delete v[f],delete v[l])}return this},publish:function(t){var n,r,i=arguments[h]=v++;if(t in d){n=d[t],n[s]=arguments,r=n[f];if(arguments[a]>0)while(r){if(r[h]===i){r=r[c];continue}r[h]=i,r[u].apply(r[o],arguments),r=r[c]}else while(r){if(r[h]===i){r=r[c];continue}r[h]=i,r[u].call(r[o]),r=r[c]}}else arguments[a]>0&&(d[t]=n={},n[s]=arguments);return this}})}),define("troopjs-core/component/gadget",["compose","./base","../util/deferred","../pubsub/hub"],function(t,n,r,i){var s=null,o=Function,u=/^hub(?::(\w+))?\/(.+)/,a=/^sig\/(.+)/,f=i.publish,l=i.subscribe,c=i.unsubscribe,h="memory",p="subscriptions";return n.extend(function(){var n=this,i=n.constructor._getBases(!0),u,f,l,c,h,p,d={},v,m,g=null;for(c=i.length;c>=0;c--){u=i[c];e:for(g in u){l=u[g];if(!(l instanceof o))continue;m=a.exec(g);if(m!==s){v=m[1];if(v in d){f=d[v],h=p=f.length;while(h--)if(l===f[h])continue e;f[p]=l}else d[v]=[l]}}}t.call(n,{signal:function y(y,e){var t=this,n,i,s=e;if(y in d){n=d[y],i=n.length;while(--i)s=r(function(e){var r=n[i],o=s;e.done(function(){r.call(t,y,o)})});n[0].call(t,y,s)}else e&&e.resolve();return t}})},{displayName:"core/component/gadget","sig/initialize":function(t,n){var r=this,a=r[p]=[],f=s,l,c,d;for(f in r){l=r[f];if(!(l instanceof o))continue;c=u.exec(f),c!==s&&(d=c[2],i.subscribe(d,r,c[1]===h,l),a[a.length]=[d,r,l],r[f]=s)}return n&&n.resolve(),r},"sig/finalize":function(t,n){var r=this,s=r[p],o;while(o=s.shift())i.unsubscribe(o[0],o[1],o[2]);return n&&n.resolve(),r},publish:function(){var t=this;return f.apply(i,arguments),t},subscribe:function(){var t=this;return l.apply(i,arguments),t},unsubscribe:function(){var t=this;return c.apply(i,arguments),t},start:function(t){var n=this;return r(function(i){r(function(t){n.signal("initialize",t)}).done(function(){n.signal("start",i)}).fail(i.reject),t&&i.then(t.resolve,t.reject)}),n},stop:function(t){var n=this;return r(function(i){r(function(t){n.signal("stop",t)}).done(function(){n.signal("finalize",i)}).fail(i.reject),t&&i.then(t.resolve,t.reject)}),n}})}),define("troopjs-core/component/service",["./gadget"],function(t){return t.extend({displayName:"core/component/service"})}),define("troopjs-core/util/merge",[],function(){var t=Array,n=Object;return function r(e){var i=this,s=null,o,u,a,f;for(o=0,u=arguments.length;o<u;o++){e=arguments[o];for(s in e)a=e[s],f=a.constructor,s in i?f===t?i[s]=i[s].concat(a):f===n?r.call(i[s],a):i[s]=a:i[s]=a}return i}}),define("troopjs-core/remote/ajax",["../component/service","../pubsub/topic","jquery","../util/merge"],function(t,n,r,i){return t.extend({displayName:"core/remote/ajax","hub/ajax":function(t,s,o){r.ajax(i.call({headers:{"x-request-id":(new Date).getTime(),"x-components":t instanceof n?t.trace():t}},s)).then(o.resolve,o.reject)}})}),define("troopjs-core/util/uri",["compose"],function(t){var n=null,r=Function,i=Array,s=i.prototype,o=typeof Object.prototype,u=typeof String.prototype,a=/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:([^?#]*)(?:\?([^#]*))?(?:#(.*))?)/,f="protocol",l="authority",c="path",h="query",p="anchor",d=["source",f,l,"userInfo","user","password","host","port",c,h,p],v=t.secure;t.secure=!0;var m=t(function(t){var r=this,s,a=n,f,l=/(?:&|^)([^&=]*)=?([^&]*)/g;switch(typeof t){case o:for(a in t)r[a]=t[a];break;case u:while(s=l.exec(str))a=s[1],a in r?(f=r[a],f instanceof i?f[f.length]=s[2]:r[a]=[f,s[2]]):r[a]=s[2]}},{toString:function b(){var e=this,t=n,s=n,o=[],u=0,a;for(t in e){if(e[t]instanceof r)continue;o[u++]=t}o.sort();while(u--){t=o[u],s=e[t];if(s instanceof i){s=s.slice(0),s.sort(),a=s.length;while(a--)s[a]=t+"="+s[a];o[u]=s.join("&")}else o[u]=t+"="+s}return o.join("&")}}),g=t(s,function(t){if(!t||t.length===0)return;var n=this,r,i=/(?:\/|^)([^\/]*)/g;while(r=i.exec(t))n.push(r[1])},{toString:function w(){return this.join("/")}}),y=t(function(t){var n=this,r=a.exec(t),i=r.length,s;while(i--)s=r[i],s&&(n[d[i]]=s);h in n&&(n[h]=m(n[h])),c in n&&(n[c]=g(n[c]))},{toString:function E(){var e=this,t=[f,"://",l,"/",c,"?",h,"#",p],n,r;f in e||t.splice(0,3),c in e||t.splice(0,2),p in e||t.splice(-2,2),h in e||t.splice(-2,2),n=t.length;while(n--)r=t[n],r in e&&(t[n]=e[r]);return t.join("")}});return t.secure=v,y.Path=g,y.Query=m,y}),define("troopjs-core/route/router",["../component/service","../util/uri"],function(t,n){function u(e){var t=e.data,r=n(e.target.location.hash.replace(o,"")),i=r.toString();i!==t[s]&&(t[s]=i,t.publish(s,r))}var r="hashchange",i="$element",s="route",o=/^#/;return t.extend(function(t){this[i]=t},{displayName:"core/route/router","sig/initialize":function(t,n){var s=this;return s[i].bind(r,s,u),n&&n.resolve(),s},"sig/start":function(t,n){var s=this;return s[i].trigger(r),n&&n.resolve(),s},"sig/finalize":function(t,n){var s=this;return s[i].unbind(r,u),n&&n.resolve(),s}})}),define("troopjs-core/store/base",["compose","../component/gadget"],function(t,n){var r="storage";return n.extend({storage:t.required,set:function(t,n,i){this[r].setItem(t,JSON.stringify(n)),i&&i.resolve(n)},get:function(t,n){var i=JSON.parse(this[r].getItem(t));n&&n.resolve(i)},remove:function(t,n){this[r].removeItem(t),n&&n.resolve()},clear:function(t){this[r].clear(),t&&t.resolve()}})}),define("troopjs-core/store/local",["compose","./base"],function(t,n){return t.create(n,{displayName:"core/store/local",storage:window.localStorage})}),define("troopjs-core/store/session",["compose","./base"],function(t,n){return t.create(n,{displayName:"core/store/session",storage:window.sessionStorage})}),define("troopjs-core/dimensions/service",["../component/service"],function(t){function i(e,t,r){e.data.publish(n,t,r)}var n="dimensions",r="$element";return t.extend(function(t,i){var s=this;s[r]=t,s[n]=i},{displayName:"core/dimensions/service","sig/initialize":function(t,s){var o=this;o[r].bind(n+"."+o[n],o,i),s&&s.resolve()},"sig/start":function(t,i){var s=this;s[r].trigger("resize."+n),i&&i.resolve()},"sig/finalize":function(t,s){var o=this;o[r].unbind(n+"."+o[n],i),s&&s.resolve()}})}),define("troopjs-core/component/widget",["./gadget","jquery","../util/deferred"],function(t,n,r){function x(e,t,n){return function(){return f.call(arguments,e),n.apply(t,arguments)}}function T(e){function t(){var t=this,n=t[g],i=arguments,u=a.call(i),f=i.length,c=f>0&&i[f-1][w]instanceof s?l.call(i):o;return c&&c.notifyWith(this,["beforeRender"]),e.call(n,u instanceof s?u.apply(t,i):u),c&&c.notifyWith(this,["afterRender"]),r(function(t){t.done(function(){n.trigger(m,arguments)}),c&&t.then(c.resolve,c.reject,c.notify),n.find(E).weave(t)}),t}return t}var i=null,s=Function,o=undefined,u=Array.prototype,a=u.shift,f=u.unshift,l=u.pop,c=n.fn.trigger,h=n.fn.one,p=n.fn.bind,d=n.fn.unbind,v=/^dom(?::(\w+))?\/([^\.]+(?:\.(.+))?)/,m="widget/refresh",g="$element",y="$proxies",b="one",w="then",E="[data-weave]",S="[data-woven]";return t.extend(function(t,n){var r=this;r[g]=t,n&&(r.displayName=n)},{displayName:"core/component/widget","sig/initialize":function(t,n){var r=this,o=r[g],u=r[y]=[],a=i,f,l,c;for(a in r){f=r[a];if(!(f instanceof s))continue;l=v.exec(a),l!==i&&(c=l[2],f=x(c,r,f),(l[2]===b?h:p).call(o,c,r,f),u[u.length]=[c,f],r[a]=i)}return n&&n.resolve(),r},"sig/finalize":function(t,n){var r=this,i=r[g],s=r[y],o;while(o=s.shift())i.unbind(o[0],o[1]);return n&&n.resolve(),r},weave:function(t){var n=this;return n[g].find(E).weave(t),n},unweave:function(){var t=this;return t[g].find(S).andSelf().unweave(),this},one:function(){var t=this;return h.apply(t[g],arguments),t},bind:function(){var t=this;return p.apply(t[g],arguments),t},unbind:function(){var t=this;return d.apply(t[g],arguments),t},trigger:function(){var t=this;return c.apply(t[g],arguments),t},before:T(n.fn.before),after:T(n.fn.after),html:T(n.fn.html),text:T(n.fn.text),append:T(n.fn.append),prepend:T(n.fn.prepend),empty:function(t){var n=this;return r(function(r){var i=n[g],s=i.contents().detach();i.trigger(m,n),setTimeout(function(){var t=s.get();s.remove(),r.resolve(t)},0),t&&r.then(t.resolve,t.reject)}),n}})}),define("troopjs-core/widget/placeholder",["../component/widget","../util/deferred"],function(t,n){function p(){var e=this,t=arguments,s=t.length,o=s>0&&t[s-1][h]instanceof i?u.call(t):r;return n(function(i){var s,u,h,p;if(a in e)i.resolve(e[a]);else{i.done(function(n){e[l].attr(f,n),e[a]=n}),h=e[c],p=[e[l],h];for(s=0,u=t.length;s<u;s++)p[s+2]=t[s];require([h],function(t){var r=t.apply(t,p);n(function(t){r.start(t)}).done(function(){i.resolve(r)}).fail(i.reject)})}o&&i.then(o.resolve,o.reject)}),e}function d(e){var t=this;return n(function(i){var s;a in t?(s=t[a],delete t[a],t[l].removeAttr(f),n(function(t){s.stop(t)}).then(i.resolve,i.reject)):i.resolve(),e&&i.then(e.resolve,e.reject)}),t}var r=undefined,i=Function,s=Array,o=s.prototype,u=o.pop,a="holding",f="data-"+a,l="$element",c="target",h="then";return t.extend(function(t,n,r){this[c]=r},{displayName:"core/widget/placeholder",release:p,hold:d,finalize:d})}),define("troopjs-core/route/placeholder",["../widget/placeholder"],function(t){var n=null,r="route";return t.extend(function(t,n){this[r]=RegExp(t.data("route"))},{displayName:"core/route/placeholder","hub:memory/route":function(t,i){var s=this,o=s[r].exec(i.path);o!==n?s.release.apply(s,o.slice(1)):s.hold()}})}),define("troopjs-core/widget/application",["../component/widget","../util/deferred"],function(t,n){return t.extend({displayName:"core/widget/application","sig/start":function(t,n){var r=this;return r.weave(n),r},"sig/stop":function(t,n){var r=this;return r.unweave(n),r}})}),define("troopjs-core/util/each",["jquery"],function(t){return t.each}),define("troopjs-core/util/grep",["jquery"],function(t){return t.grep}),define("troopjs-core/util/tr",[],function(){var t=typeof Number();return function(n){var r=this,i=[],s,o=r.length,u;if(typeof o===t&&o===0||o>0&&0 in r&&o-1 in r)for(s=0;s<o;s++)i.push(n.call(r,r[s],s));else if(r)for(u in r)i.push(n.call(r,r[u],u));return i}}),define("troopjs-core/util/when",["jquery"],function(t){return t.when}),define("troopjs-jquery/action",["jquery"],function(t){function v(e,t){return e?e+"."+o:i}function m(e){var n=t(this),i=s.call(arguments,1),a=u in e?e[u].type:o,f=e[o];e.type=o+"/"+f+"."+a,n.trigger(e,i),e.result!==r&&(e.type=o+"/"+f+"!",n.trigger(e,i),e.result!==r&&(e.type=o+"."+a,n.trigger(e,i)))}function g(e){var r=t(e.target).closest("[data-action]");if(r.length===0)return;var s=r.data(),u=a.exec(s[o]);if(u===i)return;var v=u[1],m=u[2],g=u[3];if(m!==n&&!RegExp(m.split(l).join("|")).test(e.type))return;var y=g!==n?g.split(f):[];t.each(y,function(t,r){r in s?y[t]=s[r]:c.test(r)?y[t]=r.slice(1,-1):h.test(r)?y[t]=Number(r):p.test(r)?y[t]=d.test(r):y[t]=n}),r.trigger(t.Event(e,{type:o+"!",action:v}),y),e.stopPropagation()}var n=undefined,r=!1,i=null,s=Array.prototype.slice,o="action",u="originalEvent",a=/^([\w\d\s_\-\/]+)(?:\.([\w\.]+))?(?:\((.*)\))?$/,f=/\s*,\s*/,l=/\.+/,c=/^(["']).*\1$/,h=/^\d+$/,p=/^(?:false|true)$/i,d=/^true$/i;t.event.special[o]={setup:function(n,r,i){t(this).bind(o,n,m)},add:function(n){var r=t.map(n.namespace.split(l),v);r.length!==0&&t(this).bind(r.join(" "),g)},remove:function(n){var r=t.map(n.namespace.split(l),v);r.length!==0&&t(this).unbind(r.join(" "),g)},teardown:function(n){t(this).unbind(o,m)}},t.fn[o]=function(n){return t(this).trigger({type:o+"!",action:n},s.call(arguments,1))}}),define("troopjs-jquery/destroy",["jquery"],function(t){t.event.special.destroy={remove:function(n){var r=this;n.handler.call(r,t.Event({type:n.type,data:n.data,namespace:n.namespace,target:r}))}}}),define("troopjs-jquery/resize",["jquery"],function(t){function a(e,n){var o=t.data(n),u=t(n),a=u.width(),f=u.height();(a!==o[i]||f!==o[s])&&u.trigger(r,[o[i]=a,o[s]=f])}function f(){o.each(a)}var n=null,r="resize",i="w",s="h",o=t([]),u=n;t.event.special[r]={setup:function(n,a,l){var c=this;if(t.isWindow(c))return!1;var h=t.data(c,r,{}),p=t(c);h[i]=p.width(),h[s]=p.height(),o=o.add(c),o.length===1&&(u=setInterval(f,100))},teardown:function(i){var s=this;if(t.isWindow(s))return!1;t.removeData(s,r),o=o.not(s),o.length===0&&u!==n&&clearInterval(u)}}}),define("troopjs-jquery/dimensions",["jquery"],function(t){function a(e,t){return t-e}function f(e){var r=t(this),a=r.width(),f=r.height();t.each(t.data(self,n),function(t,l){var c=l[i],h=l[s],p,d,v;v=c.length,p=c[v-1];while(c[--v]<a)p=c[v];v=h.length,d=h[v-1];while(h[--v]<f)d=h[v];if(p!==l[o]||d!==l[u])l[o]=p,l[u]=d,r.trigger(n+"."+t,[p,d])})}var n="dimensions",r="resize."+n,i="w",s="h",o="_"+i,u="_"+s;t.event.special[n]={setup:function(i,s,o){t(this).bind(r,f).data(n,{})},add:function(r){var o=this,u=r.namespace,f={},l=f[i]=[],c=f[s]=[],h=/(w|h)(\d+)/g,p;while(p=h.exec(u))f[p[1]].push(parseInt(p[2]));l.sort(a),c.sort(a),t.data(o,n)[u]=f},remove:function(r){delete t.data(this,n)[r.namespace]},teardown:function(i){t(this).removeData(n).unbind(r,f)}}}),define("troopjs-jquery/hashchange",["jquery"],function(t){function a(e){var t=s.exec(e.location.href);return t&&t[1]?decodeURIComponent(t[1]):""}function f(e){var t=this,n;t.element=n=e.createElement("iframe"),n.src="about:blank",n.style.display="none"}var n="interval",r="hashchange",i="on"+r,s=/#(.*)$/,o=/\?/,u=!1;f.prototype={getElement:function(){return this.element},getHash:function(){return this.element.contentWindow.frameHash},update:function(e){var t=this,n=t.element.contentWindow.document;if(t.getHash()===e)return;n.open(),n.write("<html><head><title>' + document.title + '</title><script type='text/javascript'>var frameHash='"+e+"';</script></head><body>&nbsp;</body></html>"),n.close()}},t.event.special[r]={setup:function(s,l,c){var h=this;if(i in h)return!1;if(!t.isWindow(h))throw new Error("Unable to bind 'hashchange' to a non-window object");var p=t(h),d=a(h),v=h.location;p.data(n,h.setInterval(u?function(){var t=h.document,n=v.protocol==="file:",i=new f(t);return t.body.appendChild(i.getElement()),i.update(d),function(){var t=d,s,u=a(h),f=i.getHash();f!==d&&f!==u?(s=decodeURIComponent(f),d!==s&&(d=s,i.update(d),p.trigger(r,[s,t])),v.hash="#"+encodeURI(n?f.replace(o,"%3F"):f)):u!==d&&(s=decodeURIComponent(u),d!==s&&(d=s,p.trigger(r,[s,t])))}}():function(){var t=d,n,i=a(h);i!==d&&(n=decodeURIComponent(i),d!==n&&(d=n,p.trigger(r,[n,t])))},25))},teardown:function(r){var s=this;if(i in s)return!1;s.clearInterval(t.data(s,n))}}}),define("troopjs-jquery/weave",["jquery"],function(t){function x(e){t(this).unweave()}var n=undefined,r=Array,i=Function,s=r.prototype,o=s.join,u=s.pop,a=t.when,f="then",l="weave",c="unweave",h="woven",p="destroy",d="data-"+l,v="data-"+h,m="["+d+"]",g="["+v+"]",y=/\s*,\s*/,b=/^(["']).*\1$/,w=/^\d+$/,E=/^(?:false|true)$/i,S=/^true$/i;t.fn[l]=function(){var r=[],s=0,c=t(this),g=arguments,T=g.length,N=T>0&&g[T-1][f]instanceof i?u.call(g):n;return c.filter(m).each(function(i,u){var f=t(u),c=f.data(),m=f.attr(d)||"",T=/[\s,]*([\w_\-\/]+)(?:\(([^\)]+)\))?/g,C=[],k=s,L=0,A;f.data(l,m).data(h,C).removeAttr(d);while(A=T.exec(m))t.Deferred(function(i){var o=L++,u,a,l,h;r[s++]=i,i.done(function(t){C[o]=t});var d=A[1],v=[f,d];for(u=0,l=g.length,a=v.length;u<l;u++,a++)v[a]=g[u];var m=A[2];if(m!==n){m=m.split(y);for(u=0,l=m.length,a=v.length;u<l;u++,a++)h=m[u],h in c?v[a]=c[h]:b.test(h)?v[a]=h.slice(1,-1):w.test(h)?v[a]=Number(h):E.test(h)?v[a]=S.test(h):v[a]=h}require([d],function(n){var r=n.apply(n,v).bind(p,x);N&&N.notifyWith(r,["wired",r]),t.Deferred(function(t){r.start(t)}).done(function(){i.resolve(r)}).fail(i.reject)})});a.apply(t,r.slice(k,s)).done(function(){f.attr(v,o.call(arguments," "))})}),N&&a.apply(t,r).then(N.resolve,N.reject),c},t.fn[c]=function(n){var r=[],i=0,s=t(this);return s.filter(g).each(function(n,s){var o=t(s),u=o.data(h),a;o.removeData(h).removeAttr(v);while(a=u.shift())t.Deferred(function(t){r[i++]=t,a.stop(t)});o.attr(d,o.data(l)).removeData(l).unbind(p,x)}),n&&a.apply(t,r).then(n.resolve,n.reject),s}});
define( [ 'troopjs-core/widget/application', 'troopjs-core/route/router', 'jquery' ], function ApplicationModule(Application, Router, $) { /*global define*/
/*jshint newcap:false*/
define([
'troopjs-core/widget/application',
'troopjs-core/route/router',
'jquery'
], function ApplicationModule(Application, Router, $) {
'use strict';
function forward(signal, deferred) { function Forward(signal, deferred) {
var services = $.map(this.services, function map(service, index) { var services = $.map(this.services, function map(service) {
return $.Deferred(function deferredSignal(deferSignal) { return $.Deferred(function deferredSignal(deferSignal) {
service.signal(signal, deferSignal); service.signal(signal, deferSignal);
}); });
...@@ -13,11 +20,11 @@ define( [ 'troopjs-core/widget/application', 'troopjs-core/route/router', 'jquer ...@@ -13,11 +20,11 @@ define( [ 'troopjs-core/widget/application', 'troopjs-core/route/router', 'jquer
} }
return Application.extend({ return Application.extend({
'sig/initialize': forward, 'sig/initialize': Forward,
'sig/finalize': forward, 'sig/finalize': Forward,
'sig/start': forward, 'sig/start': Forward,
'sif/stop': forward, 'sif/stop': Forward,
services: [ Router($(window)) ] services: [Router($(window))]
}); });
}); });
define( [ 'troopjs-core/component/widget', 'jquery' ], function ClearModule(Widget, $) { /*global define*/
define([
'troopjs-core/component/widget',
'jquery'
], function ClearModule(Widget, $) {
'use strict';
function filter(item, index) { function filter(item) {
return item === null || !item.completed; return item === null || !item.completed;
} }
...@@ -8,10 +13,10 @@ define( [ 'troopjs-core/component/widget', 'jquery' ], function ClearModule(Widg ...@@ -8,10 +13,10 @@ define( [ 'troopjs-core/component/widget', 'jquery' ], function ClearModule(Widg
'hub:memory/todos/change': function onChange(topic, items) { 'hub:memory/todos/change': function onChange(topic, items) {
var count = $.grep(items, filter, true).length; var count = $.grep(items, filter, true).length;
this.$element.text('Clear completed (' + count + ')')[count > 0 ? 'show' : 'hide'](); this.$element.text('Clear completed (' + count + ')').toggle(count > 0);
}, },
'dom/click': function onClear(topic, $event) { 'dom/click': function onClear() {
this.publish('todos/clear'); this.publish('todos/clear');
} }
}); });
......
define( [ 'troopjs-core/component/widget', 'jquery' ], function CountModule(Widget, $) { /*global define*/
define([
'troopjs-core/component/widget',
'jquery'
], function CountModule(Widget, $) {
'use strict';
function filter(item, index) { function filter(item) {
return item === null || item.completed; return item === null || item.completed;
} }
......
define( [ 'troopjs-core/component/widget' ], function CreateModule(Widget) { /*global define*/
define([
'troopjs-core/component/widget'
], function CreateModule(Widget) {
'use strict';
var ENTER_KEY = 13; var ENTER_KEY = 13;
return Widget.extend({ return Widget.extend({
......
define( [ 'troopjs-core/component/widget', 'jquery' ], function DisplayModule(Widget, $) { /*global define*/
define([
'troopjs-core/component/widget',
'jquery'
], function DisplayModule(Widget, $) {
'use strict';
function filter(item, index) { function filter(item) {
return item === null; return item === null;
} }
return Widget.extend({ return Widget.extend({
'hub:memory/todos/change': function onChange(topic, items) { 'hub:memory/todos/change': function onChange(topic, items) {
this.$element[$.grep(items, filter, true).length > 0 ? 'show' : 'hide'](); var count = $.grep(items, filter, true).length;
this.$element.toggle(count > 0);
} }
}); });
}); });
define( ['jquery'], function EscapeModule($) { /*global define*/
var entityMap = { /*jshint quotmark:false*/
escape: { define([
'&': '&amp;', 'jquery'
'<': '&lt;', ], function EscapeModule($) {
'>': '&gt;', 'use strict';
'"': '&quot;',
"'": '&#x27;', var invert = function (obj) {
'/': '&#x2F;' var result = {};
} var key;
},
invert = function(obj) { for (key in obj) {
var result = {}; if (obj.hasOwnProperty(key)) {
for (var key in obj) { result[obj[key]] = key;
if (obj.hasOwnProperty(key)) {
result[obj[key]] = key;
}
}
return result;
},
nativeKeys = Object.keys,
keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) {
throw new TypeError('Invalid object');
} }
var keys = []; }
for (var key in obj) {
if (obj.hasOwnProperty(key)) { return result;
keys[keys.length] = key; };
}
var fallbackKeys = function (obj) {
var keys = [];
var key;
if (obj !== Object(obj)) {
throw new TypeError('Invalid object');
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
keys[keys.length] = key;
} }
return keys; }
};
exports = {}; return keys;
};
var keys = Object.keys || fallbackKeys;
var entityMap = {};
entityMap.escape = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'/': '&#x2F;'
};
entityMap.unescape = invert(entityMap.escape); entityMap.unescape = invert(entityMap.escape);
...@@ -40,12 +55,15 @@ define( ['jquery'], function EscapeModule($) { ...@@ -40,12 +55,15 @@ define( ['jquery'], function EscapeModule($) {
unescape: new RegExp('(' + keys(entityMap.unescape).join('|') + ')', 'g') unescape: new RegExp('(' + keys(entityMap.unescape).join('|') + ')', 'g')
}; };
$.each(['escape', 'unescape'], function(i, method) { var exports = {};
exports[method] = function(string) {
if (string == null) { $.each(['escape', 'unescape'], function (i, method) {
exports[method] = function (string) {
if (string === null) {
return ''; return '';
} }
return ('' + string).replace(entityRegexes[method], function(match) {
return ('' + string).replace(entityRegexes[method], function (match) {
return entityMap[method][match]; return entityMap[method][match];
}); });
}; };
......
define( [ 'troopjs-core/component/widget', 'jquery' ], function FiltersModule(Widget, $) { /*global define*/
define([
'troopjs-core/component/widget',
'jquery'
], function FiltersModule(Widget, $) {
'use strict';
return Widget.extend({ return Widget.extend({
'hub:memory/route': function onRoute(topic, uri) { 'hub:memory/route': function onRoute(topic, uri) {
......
define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local', 'jquery', 'template!./item.html' ], function ListModule(Escaper, Widget, store, $, template) { /*global define*/
define([
'./escape',
'troopjs-core/component/widget',
'troopjs-core/store/local',
'jquery',
'troopjs-requirejs/template!./item.html'
], function ListModule(Escaper, Widget, store, $, template) {
'use strict';
var ENTER_KEY = 13; var ENTER_KEY = 13;
var ESCAPE_KEY = 27;
var FILTER_ACTIVE = 'filter-active'; var FILTER_ACTIVE = 'filter-active';
var FILTER_COMPLETED = 'filter-completed'; var FILTER_COMPLETED = 'filter-completed';
function filter(item, index) { function filter(item) {
return item === null; return item === null;
} }
return Widget.extend(function ListWidget(element, name) { return Widget.extend(function ListWidget() {
var self = this; var self = this;
// Defer initialization // Defer initialization
...@@ -26,9 +36,9 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -26,9 +36,9 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
$.each(items, function itemIterator(i, item) { $.each(items, function itemIterator(i, item) {
// Append to self // Append to self
self.append(template, { self.append(template, {
'i': i, i: i,
'item': item, item: item,
'itemTitle': Escaper.escape(item.title) itemTitle: Escaper.escape(item.title)
}); });
}); });
}) })
...@@ -51,15 +61,15 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -51,15 +61,15 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
// Create new item, store in items // Create new item, store in items
var item = items[i] = { var item = items[i] = {
'completed': false, completed: false,
'title': title title: title
}; };
// Append new item to self // Append new item to self
self.append(template, { self.append(template, {
'i': i, i: i,
'item': item, item: item,
'itemTitle': Escaper.escape(item.title) itemTitle: Escaper.escape(item.title)
}); });
// Set items and resolve set // Set items and resolve set
...@@ -75,7 +85,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -75,7 +85,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
this.$element.find(':checkbox').prop('checked', value).change(); this.$element.find(':checkbox').prop('checked', value).change();
}, },
'hub/todos/clear': function onClear(topic) { 'hub/todos/clear': function onClear() {
this.$element.find('.completed .destroy').click(); this.$element.find('.completed .destroy').click();
}, },
...@@ -96,7 +106,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -96,7 +106,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
break; break;
default: default:
$element.removeClass([FILTER_ACTIVE, FILTER_COMPLETED].join(' ')); $element.removeClass(FILTER_ACTIVE + ' ' + FILTER_COMPLETED);
} }
}, },
...@@ -191,8 +201,19 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -191,8 +201,19 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
}, },
'dom/action/commit.keyup': function onCommitKeyUp(topic, $event) { 'dom/action/commit.keyup': function onCommitKeyUp(topic, $event) {
if ($event.originalEvent.keyCode === ENTER_KEY) { var $target = $($event.target);
$($event.target).focusout(); var keyCode = $event.originalEvent.keyCode;
if (keyCode === ENTER_KEY) {
$target.focusout();
}
if (keyCode === ESCAPE_KEY) {
$target
.closest('li.editing')
.removeClass('editing');
$target.val(store.get(this.config.store));
} }
}, },
...@@ -207,8 +228,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local ...@@ -207,8 +228,7 @@ define( [ './escape', 'troopjs-core/component/widget', 'troopjs-core/store/local
.removeClass('editing') .removeClass('editing')
.find('.destroy') .find('.destroy')
.click(); .click();
} } else {
else {
// Defer set // Defer set
$.Deferred(function deferredSet(deferSet) { $.Deferred(function deferredSet(deferSet) {
// Disable // Disable
......
define( [ 'troopjs-core/component/widget' ], function MarkModule(Widget) { /*global define*/
define([
'jquery',
'troopjs-core/component/widget'
], function MarkModule($, Widget) {
'use strict';
return Widget.extend({ return Widget.extend({
'hub:memory/todos/change': function onChange(topic, items) { 'hub:memory/todos/change': function onChange(topic, items) {
...@@ -18,21 +23,9 @@ define( [ 'troopjs-core/component/widget' ], function MarkModule(Widget) { ...@@ -18,21 +23,9 @@ define( [ 'troopjs-core/component/widget' ], function MarkModule(Widget) {
total++; total++;
}); });
if (count === 0) { $element
$element .prop('indeterminate', count !== 0 && count !== total)
.prop('indeterminate', false) .prop('checked', count === total);
.prop('checked', false);
}
else if (count === total) {
$element
.prop('indeterminate', false)
.prop('checked', true);
}
else {
$element
.prop('indeterminate', true)
.prop('checked', false);
}
}, },
'dom/change': function onMark(topic, $event) { 'dom/change': function onMark(topic, $event) {
......
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