Commit b72a1cb0 authored by George Henderson's avatar George Henderson

Added lavaca example to labs

parent 7d8221c1
......@@ -221,6 +221,9 @@
<li class="routing labs">
<a href="labs/dependency-examples/durandal/" data-source="http://durandaljs.com/" data-content="Single Page Apps Done Right">Durandal</a>
</li>
<li class="routing labs">
<a href="labs/dependency-examples/lavaca_require/" data-source="http://getlavaca.com" data-content="A curated collection of tools for building mobile web applications.">Lavaca + RequireJS</a>
</li>
</ul>
<hr>
<h2>Real-time</h2>
......
{
"name": "todomvc-lavaca_require",
"version": "0.0.0",
"dependencies": {
"todomvc-common": "~0.1.6",
"requirejs": "~2.1.6",
"dustjs-linkedin": "~1.1.1",
"dustjs-linkedin-helpers": "~1.1.1",
"jquery": "~2.0.3",
"mout": "~0.7.1"
}
}
//
// Dust-helpers - Additional functionality for dustjs-linkedin package v1.1.1
//
// Copyright (c) 2012, LinkedIn
// Released under the MIT License.
//
(function(dust){
// Note: all error conditions are logged to console and failed silently
/* make a safe version of console if it is not available
* currently supporting:
* _console.log
* */
var _console = (typeof console !== 'undefined')? console: {
log: function(){
/* a noop*/
}
};
function isSelect(context) {
var value = context.current();
return typeof value === "object" && value.isSelect === true;
}
// Utility method : toString() equivalent for functions
function jsonFilter(key, value) {
if (typeof value === "function") {
return value.toString();
}
return value;
}
// Utility method: to invoke the given filter operation such as eq/gt etc
function filter(chunk, context, bodies, params, filterOp) {
params = params || {};
var body = bodies.block,
actualKey,
expectedValue,
filterOpType = params.filterOpType || '';
// when @eq, @lt etc are used as standalone helpers, key is required and hence check for defined
if ( typeof params.key !== "undefined") {
actualKey = dust.helpers.tap(params.key, chunk, context);
}
else if (isSelect(context)) {
actualKey = context.current().selectKey;
// supports only one of the blocks in the select to be selected
if (context.current().isResolved) {
filterOp = function() { return false; };
}
}
else {
_console.log ("No key specified for filter in:" + filterOpType + " helper ");
return chunk;
}
expectedValue = dust.helpers.tap(params.value, chunk, context);
// coerce both the actualKey and expectedValue to the same type for equality and non-equality compares
if (filterOp(coerce(expectedValue, params.type, context), coerce(actualKey, params.type, context))) {
if (isSelect(context)) {
context.current().isResolved = true;
}
// we want helpers without bodies to fail gracefully so check it first
if(body) {
return chunk.render(body, context);
}
else {
_console.log( "Missing body block in the " + filterOpType + " helper ");
return chunk;
}
}
else if (bodies['else']) {
return chunk.render(bodies['else'], context);
}
return chunk;
}
function coerce (value, type, context) {
if (value) {
switch (type || typeof(value)) {
case 'number': return +value;
case 'string': return String(value);
case 'boolean': {
value = (value === 'false' ? false : value);
return Boolean(value);
}
case 'date': return new Date(value);
case 'context': return context.get(value);
}
}
return value;
}
var helpers = {
// Utility helping to resolve dust references in the given chunk
// uses the Chunk.render method to resolve value
/*
Reference resolution rules:
if value exists in JSON:
"" or '' will evaluate to false, boolean false, null, or undefined will evaluate to false,
numeric 0 evaluates to true, so does, string "0", string "null", string "undefined" and string "false".
Also note that empty array -> [] is evaluated to false and empty object -> {} and non-empty object are evaluated to true
The type of the return value is string ( since we concatenate to support interpolated references
if value does not exist in JSON and the input is a single reference: {x}
dust render emits empty string, and we then return false
if values does not exist in JSON and the input is interpolated references : {x} < {y}
dust render emits < and we return the partial output
*/
"tap": function( input, chunk, context ){
// return given input if there is no dust reference to resolve
var output = input;
// dust compiles a string/reference such as {foo} to function,
if( typeof input === "function"){
// just a plain function (a.k.a anonymous functions) in the context, not a dust `body` function created by the dust compiler
if( input.isFunction === true ){
output = input();
} else {
output = '';
chunk.tap(function(data){
output += data;
return '';
}).render(input, context).untap();
if( output === '' ){
output = false;
}
}
}
return output;
},
"sep": function(chunk, context, bodies) {
var body = bodies.block;
if (context.stack.index === context.stack.of - 1) {
return chunk;
}
if(body) {
return bodies.block(chunk, context);
}
else {
return chunk;
}
},
"idx": function(chunk, context, bodies) {
var body = bodies.block;
if(body) {
return bodies.block(chunk, context.push(context.stack.index));
}
else {
return chunk;
}
},
/**
* contextDump helper
* @param key specifies how much to dump.
* "current" dumps current context. "full" dumps the full context stack.
* @param to specifies where to write dump output.
* Values can be "console" or "output". Default is output.
*/
"contextDump": function(chunk, context, bodies, params) {
var p = params || {},
to = p.to || 'output',
key = p.key || 'current',
dump;
to = dust.helpers.tap(to, chunk, context),
key = dust.helpers.tap(key, chunk, context);
if (key === 'full') {
dump = JSON.stringify(context.stack, jsonFilter, 2);
}
else {
dump = JSON.stringify(context.stack.head, jsonFilter, 2);
}
if (to === 'console') {
_console.log(dump);
return chunk;
}
else {
return chunk.write(dump);
}
},
/**
if helper for complex evaluation complex logic expressions.
Note : #1 if helper fails gracefully when there is no body block nor else block
#2 Undefined values and false values in the JSON need to be handled specially with .length check
for e.g @if cond=" '{a}'.length && '{b}'.length" is advised when there are chances of the a and b been
undefined or false in the context
#3 Use only when the default ? and ^ dust operators and the select fall short in addressing the given logic,
since eval executes in the global scope
#4 All dust references are default escaped as they are resolved, hence eval will block malicious scripts in the context
Be mindful of evaluating a expression that is passed through the unescape filter -> |s
@param cond, either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. cond="2>3"
a dust reference is also enclosed in double quotes, e.g. cond="'{val}'' > 3"
cond argument should evaluate to a valid javascript expression
**/
"if": function( chunk, context, bodies, params ){
var body = bodies.block,
skip = bodies['else'];
if( params && params.cond){
var cond = params.cond;
cond = dust.helpers.tap(cond, chunk, context);
// eval expressions with given dust references
if(eval(cond)){
if(body) {
return chunk.render( bodies.block, context );
}
else {
_console.log( "Missing body block in the if helper!" );
return chunk;
}
}
if(skip){
return chunk.render( bodies['else'], context );
}
}
// no condition
else {
_console.log( "No condition given in the if helper!" );
}
return chunk;
},
/**
* math helper
* @param key is the value to perform math against
* @param method is the math method, is a valid string supported by math helper like mod, add, subtract
* @param operand is the second value needed for operations like mod, add, subtract, etc.
* @param round is a flag to assure that an integer is returned
*/
"math": function ( chunk, context, bodies, params ) {
//key and method are required for further processing
if( params && typeof params.key !== "undefined" && params.method ){
var key = params.key,
method = params.method,
// operand can be null for "abs", ceil and floor
operand = params.operand,
round = params.round,
mathOut = null,
operError = function(){_console.log("operand is required for this math method"); return null;};
key = dust.helpers.tap(key, chunk, context);
operand = dust.helpers.tap(operand, chunk, context);
// TODO: handle and tests for negatives and floats in all math operations
switch(method) {
case "mod":
if(operand === 0 || operand === -0) {
_console.log("operand for divide operation is 0/-0: expect Nan!");
}
mathOut = parseFloat(key) % parseFloat(operand);
break;
case "add":
mathOut = parseFloat(key) + parseFloat(operand);
break;
case "subtract":
mathOut = parseFloat(key) - parseFloat(operand);
break;
case "multiply":
mathOut = parseFloat(key) * parseFloat(operand);
break;
case "divide":
if(operand === 0 || operand === -0) {
_console.log("operand for divide operation is 0/-0: expect Nan/Infinity!");
}
mathOut = parseFloat(key) / parseFloat(operand);
break;
case "ceil":
mathOut = Math.ceil(parseFloat(key));
break;
case "floor":
mathOut = Math.floor(parseFloat(key));
break;
case "round":
mathOut = Math.round(parseFloat(key));
break;
case "abs":
mathOut = Math.abs(parseFloat(key));
break;
default:
_console.log( "method passed is not supported" );
}
if (mathOut !== null){
if (round) {
mathOut = Math.round(mathOut);
}
if (bodies && bodies.block) {
// with bodies act like the select helper with mathOut as the key
// like the select helper bodies['else'] is meaningless and is ignored
return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, selectKey: mathOut }));
} else {
// self closing math helper will return the calculated output
return chunk.write(mathOut);
}
} else {
return chunk;
}
}
// no key parameter and no method
else {
_console.log( "Key is a required parameter for math helper along with method/operand!" );
}
return chunk;
},
/**
select helperworks with one of the eq/gt/gte/lt/lte/default providing the functionality
of branching conditions
@param key, ( required ) either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
**/
"select": function(chunk, context, bodies, params) {
var body = bodies.block;
// key is required for processing, hence check for defined
if( params && typeof params.key !== "undefined"){
// returns given input as output, if the input is not a dust reference, else does a context lookup
var key = dust.helpers.tap(params.key, chunk, context);
// bodies['else'] is meaningless and is ignored
if( body ) {
return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, selectKey: key }));
}
else {
_console.log( "Missing body block in the select helper ");
return chunk;
}
}
// no key
else {
_console.log( "No key given in the select helper!" );
}
return chunk;
},
/**
eq helper compares the given key is same as the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"eq": function(chunk, context, bodies, params) {
if(params) {
params.filterOpType = "eq";
}
return filter(chunk, context, bodies, params, function(expected, actual) { return actual === expected; });
},
/**
ne helper compares the given key is not the same as the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"ne": function(chunk, context, bodies, params) {
if(params) {
params.filterOpType = "ne";
return filter(chunk, context, bodies, params, function(expected, actual) { return actual !== expected; });
}
return chunk;
},
/**
lt helper compares the given key is less than the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"lt": function(chunk, context, bodies, params) {
if(params) {
params.filterOpType = "lt";
return filter(chunk, context, bodies, params, function(expected, actual) { return actual < expected; });
}
},
/**
lte helper compares the given key is less or equal to the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"lte": function(chunk, context, bodies, params) {
if(params) {
params.filterOpType = "lte";
return filter(chunk, context, bodies, params, function(expected, actual) { return actual <= expected; });
}
return chunk;
},
/**
gt helper compares the given key is greater than the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"gt": function(chunk, context, bodies, params) {
// if no params do no go further
if(params) {
params.filterOpType = "gt";
return filter(chunk, context, bodies, params, function(expected, actual) { return actual > expected; });
}
return chunk;
},
/**
gte helper, compares the given key is greater than or equal to the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"gte": function(chunk, context, bodies, params) {
if(params) {
params.filterOpType = "gte";
return filter(chunk, context, bodies, params, function(expected, actual) { return actual >= expected; });
}
return chunk;
},
// to be used in conjunction with the select helper
// TODO: fix the helper to do nothing when used standalone
"default": function(chunk, context, bodies, params) {
// does not require any params
if(params) {
params.filterOpType = "default";
}
return filter(chunk, context, bodies, params, function(expected, actual) { return true; });
},
/**
* size helper prints the size of the given key
* Note : size helper is self closing and does not support bodies
* @param key, the element whose size is returned
*/
"size": function( chunk, context, bodies, params ) {
var key, value=0, nr, k;
params = params || {};
key = params.key;
if (!key || key === true) { //undefined, null, "", 0
value = 0;
}
else if(dust.isArray(key)) { //array
value = key.length;
}
else if (!isNaN(parseFloat(key)) && isFinite(key)) { //numeric values
value = key;
}
else if (typeof key === "object") { //object test
//objects, null and array all have typeof ojbect...
//null and array are already tested so typeof is sufficient http://jsperf.com/isobject-tests
nr = 0;
for(k in key){
if(Object.hasOwnProperty.call(key,k)){
nr++;
}
}
value = nr;
} else {
value = (key + '').length; //any other value (strings etc.)
}
return chunk.write(value);
}
};
dust.helpers = helpers;
})(typeof exports !== 'undefined' ? module.exports = require('dustjs-linkedin') : dust);
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
define(['./prop', '../object/deepMatches'], function(prop, deepMatches) {
/**
* Converts argument into a valid iterator.
* Used internally on most array/object/collection methods that receives a
* callback/iterator providing a shortcut syntax.
*/
function makeIterator(src, thisObj){
switch(typeof src) {
case 'object':
// typeof null == "object"
return (src != null)? function(val, key, target){
return deepMatches(val, src);
} : src;
case 'string':
case 'number':
return prop(src);
case 'function':
if (typeof thisObj === 'undefined') {
return src;
} else {
return function(val, i, arr){
return src.call(thisObj, val, i, arr);
};
}
default:
return src;
}
}
return makeIterator;
});
define(function () {
/**
* Returns a function that gets a property of the passed object
*/
function prop(name){
return function(obj){
return obj[name];
};
}
return prop;
});
define(['./kindOf', './isPlainObject', '../object/mixIn'], function (kindOf, isPlainObject, mixIn) {
/**
* Clone native types.
*/
function clone(val){
switch (kindOf(val)) {
case 'Object':
return cloneObject(val);
case 'Array':
return cloneArray(val);
case 'RegExp':
return cloneRegExp(val);
case 'Date':
return cloneDate(val);
default:
return val;
}
}
function cloneObject(source) {
if (isPlainObject(source)) {
return mixIn({}, source);
} else {
return source;
}
}
function cloneRegExp(r) {
var flags = '';
flags += r.multiline ? 'm' : '';
flags += r.global ? 'g' : '';
flags += r.ignorecase ? 'i' : '';
return new RegExp(r.source, flags);
}
function cloneDate(date) {
return new Date(+date);
}
function cloneArray(arr) {
return arr.slice();
}
return clone;
});
define(['./clone', '../object/forOwn', './kindOf', './isPlainObject'], function (clone, forOwn, kindOf, isPlainObject) {
/**
* Recursively clone native types.
*/
function deepClone(val, instanceClone) {
switch ( kindOf(val) ) {
case 'Object':
return cloneObject(val, instanceClone);
case 'Array':
return cloneArray(val, instanceClone);
default:
return clone(val);
}
}
function cloneObject(source, instanceClone) {
if (isPlainObject(source)) {
var out = {};
forOwn(source, function(val, key) {
this[key] = deepClone(val, instanceClone);
}, out);
return out;
} else if (instanceClone) {
return instanceClone(source);
} else {
return source;
}
}
function cloneArray(arr, instanceClone) {
var out = [],
i = -1,
n = arr.length,
val;
while (++i < n) {
out[i] = deepClone(arr[i], instanceClone);
}
return out;
}
return deepClone;
});
define(['./isKind'], function (isKind) {
/**
*/
var isArray = Array.isArray || function (val) {
return isKind(val, 'Array');
};
return isArray;
});
define(['./kindOf'], function (kindOf) {
/**
* Check if value is from a specific "kind".
*/
function isKind(val, kind){
return kindOf(val) === kind;
}
return isKind;
});
define(['./isKind'], function (isKind) {
/**
*/
function isObject(val) {
return isKind(val, 'Object');
}
return isObject;
});
define(function () {
/**
* Checks if the value is created by the `Object` constructor.
*/
function isPlainObject(value) {
return (!!value
&& typeof value === 'object'
&& value.constructor === Object);
}
return isPlainObject;
});
define(function () {
var _rKind = /^\[object (.*)\]$/,
_toString = Object.prototype.toString,
UNDEF;
/**
* Gets the "kind" of value. (e.g. "String", "Number", etc)
*/
function kindOf(val) {
if (val === null) {
return 'Null';
} else if (val === UNDEF) {
return 'Undefined';
} else {
return _rKind.exec( _toString.call(val) )[1];
}
}
return kindOf;
});
define(['./forOwn', '../lang/isArray'], function(forOwn, isArray) {
function containsMatch(array, pattern) {
var i = -1, length = array.length;
while (++i < length) {
if (deepMatches(array[i], pattern)) {
return true;
}
}
return false;
}
function matchArray(target, pattern) {
var i = -1, patternLength = pattern.length;
while (++i < patternLength) {
if (!containsMatch(target, pattern[i])) {
return false;
}
}
return true;
}
function matchObject(target, pattern) {
var result = true;
forOwn(pattern, function(val, key) {
if (!deepMatches(target[key], val)) {
// Return false to break out of forOwn early
return (result = false);
}
});
return result;
}
/**
* Recursively check if the objects match.
*/
function deepMatches(target, pattern){
if (target && typeof target === 'object') {
if (isArray(target) && isArray(pattern)) {
return matchArray(target, pattern);
} else {
return matchObject(target, pattern);
}
} else {
return target === pattern;
}
}
return deepMatches;
});
define(['./forOwn', '../lang/isPlainObject'], function (forOwn, isPlainObject) {
/**
* Mixes objects into the target object, recursively mixing existing child
* objects.
*/
function deepMixIn(target, objects) {
var i = 0,
n = arguments.length,
obj;
while(++i < n){
obj = arguments[i];
if (obj) {
forOwn(obj, copyProp, target);
}
}
return target;
}
function copyProp(val, key) {
var existing = this[key];
if (isPlainObject(val) && isPlainObject(existing)) {
deepMixIn(existing, val);
} else {
this[key] = val;
}
}
return deepMixIn;
});
define(['./hasOwn', './every', '../lang/isObject'], function(hasOwn, every, isObject) {
function defaultCompare(a, b) {
return a === b;
}
// Makes a function to compare the object values from the specified compare
// operation callback.
function makeCompare(callback) {
return function(value, key) {
return hasOwn(this, key) && callback(value, this[key]);
};
}
function checkProperties(value, key) {
return hasOwn(this, key);
}
/**
* Checks if two objects have the same keys and values.
*/
function equals(a, b, callback) {
callback = callback || defaultCompare;
if (!isObject(a) || !isObject(b)) {
return callback(a, b);
}
return (every(a, makeCompare(callback), b) &&
every(b, checkProperties, a));
}
return equals;
});
define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) {
/**
* Object every
*/
function every(obj, callback, thisObj) {
callback = makeIterator(callback, thisObj);
var result = true;
forOwn(obj, function(val, key) {
// we consider any falsy values as "false" on purpose so shorthand
// syntax can be used to check property existence
if (!callback(val, key, obj)) {
result = false;
return false; // break
}
});
return result;
}
return every;
});
define(function () {
var _hasDontEnumBug,
_dontEnums;
function checkDontEnum(){
_dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
_hasDontEnumBug = true;
for (var key in {'toString': null}) {
_hasDontEnumBug = false;
}
}
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forIn(obj, fn, thisObj){
var key, i = 0;
// no need to check if argument is a real object that way we can use
// it for arrays, functions, date, etc.
//post-pone check till needed
if (_hasDontEnumBug == null) checkDontEnum();
for (key in obj) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
if (_hasDontEnumBug) {
while (key = _dontEnums[i++]) {
// since we aren't using hasOwn check we need to make sure the
// property was overwritten
if (obj[key] !== Object.prototype[key]) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
}
}
}
function exec(fn, obj, key, thisObj){
return fn.call(thisObj, obj[key], key, obj);
}
return forIn;
});
define(['./hasOwn', './forIn'], function (hasOwn, forIn) {
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forOwn(obj, fn, thisObj){
forIn(obj, function(val, key){
if (hasOwn(obj, key)) {
return fn.call(thisObj, obj[key], key, obj);
}
});
}
return forOwn;
});
define(function () {
/**
* Safer Object.hasOwnProperty
*/
function hasOwn(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop);
}
return hasOwn;
});
define(['./hasOwn', '../lang/deepClone', '../lang/isObject'], function (hasOwn, deepClone, isObject) {
/**
* Deep merge objects.
*/
function merge() {
var i = 1,
key, val, obj, target;
// make sure we don't modify source element and it's properties
// objects are passed by reference
target = deepClone( arguments[0] );
while (obj = arguments[i++]) {
for (key in obj) {
if ( ! hasOwn(obj, key) ) {
continue;
}
val = obj[key];
if ( isObject(val) && isObject(target[key]) ){
// inception, deep merge objects
target[key] = merge(target[key], val);
} else {
// make sure arrays, regexp, date, objects are cloned
target[key] = deepClone(val);
}
}
}
return target;
}
return merge;
});
define(['./forOwn'], function(forOwn){
/**
* Combine properties from all the objects into first one.
* - This method affects target object in place, if you want to create a new Object pass an empty object as first param.
* @param {object} target Target Object
* @param {...object} objects Objects to be combined (0...n objects).
* @return {object} Target Object.
*/
function mixIn(target, objects){
var i = 0,
n = arguments.length,
obj;
while(++i < n){
obj = arguments[i];
if (obj != null) {
forOwn(obj, copyProp, target);
}
}
return target;
}
function copyProp(val, key){
this[key] = val;
}
return mixIn;
});
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.8 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.8',
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 && window.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');
}
function defaultOnError(err) {
throw err;
}
//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 {
mod = getModule(depMap);
if (mod.error && name === 'error') {
fn(mod.error);
} else {
mod.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 () {
var c,
pkg = getOwn(config.pkgs, mod.map.id);
// For packages, only support config targeted
// at the main module.
c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) :
getOwn(config.config, mod.map.id);
return c || {};
},
exports: defined[mod.map.id]
});
}
}
};
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. However,
//only do it for define()'d modules. require
//errbacks should not be called for failures in
//their callbacks (#699). However if a global
//onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
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.isDefine ? [this.map.id] : null;
err.requireType = this.map.isDefine ? 'define' : 'require';
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', bind(this, 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 callback 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 for: ' + data.id, 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 = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var 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;
return node;
};
/**
* 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 = req.createNode(config, moduleName, url);
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) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = 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 = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
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 = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//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;
}
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #C5C5C5;
border-bottom: 1px dashed #F7F7F7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
/**body*/.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
/**body*/.learn-bar {
width: auto;
margin: 0 0 0 300px;
}
/**body*/.learn-bar > .learn {
left: 8px;
}
/**body*/.learn-bar #todoapp {
width: 550px;
margin: 130px auto 40px auto;
}
}
(function () {
'use strict';
// Underscore's Template Module
// Courtesy of underscorejs.org
var _ = (function (_) {
_.defaults = function (object) {
if (!object) {
return object;
}
for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
var iterable = arguments[argsIndex];
if (iterable) {
for (var key in iterable) {
if (object[key] == null) {
object[key] = iterable[key];
}
}
}
}
return object;
}
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
return _;
})({});
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 redirect() {
if (location.hostname === 'tastejs.github.io') {
location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
}
}
function findRoot() {
var base;
[/labs/, /\w*-examples/].forEach(function (href) {
var match = location.href.match(href);
if (!base && match) {
base = location.href.indexOf(match);
}
});
return location.href.substr(0, base);
}
function getFile(file, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', findRoot() + file, true);
xhr.send();
xhr.onload = function () {
if (xhr.status === 200 && callback) {
callback(xhr.responseText);
}
};
}
function Learn(learnJSON, config) {
if (!(this instanceof Learn)) {
return new Learn(learnJSON, config);
}
var template, framework;
if (typeof learnJSON !== 'object') {
try {
learnJSON = JSON.parse(learnJSON);
} catch (e) {
return;
}
}
if (config) {
template = config.template;
framework = config.framework;
}
if (!template && learnJSON.templates) {
template = learnJSON.templates.todomvc;
}
if (!framework && document.querySelector('[data-framework]')) {
framework = document.querySelector('[data-framework]').getAttribute('data-framework');
}
if (template && learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework];
this.template = template;
this.append();
}
}
Learn.prototype.append = function () {
var aside = document.createElement('aside');
aside.innerHTML = _.template(this.template, this.frameworkJSON);
aside.className = 'learn';
// Localize demo links
var demoLinks = aside.querySelectorAll('.demo-link');
Array.prototype.forEach.call(demoLinks, function (demoLink) {
demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
});
document.body.className = (document.body.className + ' learn-bar').trim();
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
};
redirect();
getFile('learn.json', Learn);
})();
<!doctype html>
<html lang="en" data-framework="lavaca">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Lavaca • TodoMVC</title>
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
</head>
<body>
<section id="todoapp"></section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="https://github.com/mutualmobile/" data-external>Mutual Mobile</a></p>
<p>Part of <a href="http://todomvc.com" data-external>TodoMVC</a></p>
</footer>
<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/requirejs/require.js"></script>
<script src="js/libs/lavaca.js"></script>
<script src="js/app/boot.js"></script>
</body>
</html>
\ No newline at end of file
define(function (require) {
'use strict';
var History = require('lavaca/net/History');
var Application = require('lavaca/mvc/Application');
var TodosController = require('app/net/TodosController');
var $ = require('$');
require('lavaca/ui/DustTemplate');
// Uncomment this section to use hash-based browser history instead of HTML5 history.
// You should use hash-based history if there's no server-side component supporting your app's routes.
History.overrideStandardsMode();
// Override Lavaca's default view-root selector to match
// the TodoMVC template file better
Application.prototype.viewRootSelector = '#todoapp';
/**
* @class app
* @super Lavaca.mvc.Application
* Global application-specific object
*/
var app = new Application(function () {
// Initialize the routes
this.router.add({
'/': [TodosController, 'home', {filter: 'all'}],
'/active': [TodosController, 'home', {filter: 'active'}],
'/completed': [TodosController, 'home', {filter: 'completed'}]
});
// Patch learn sidebar links so they get ignored by the router
$(document.body).find('aside.learn a').addClass('ignore');
});
return app;
});
\ No newline at end of file
require.config({
baseUrl: 'js',
paths: {
$: '../bower_components/jquery/jquery',
jquery: '../bower_components/jquery/jquery',
mout: '../bower_components/mout/src',
dust: '../bower_components/dustjs-linkedin/dist/dust-full-1.1.1',
'dust-helpers': '../bower_components/dustjs-linkedin-helpers/dist/dust-helpers-1.1.1',
rdust: 'libs/require-dust',
lavaca: 'Lavaca',
Lavaca: 'lavaca'
},
shim: {
$: {
exports: '$'
},
jquery: {
exports: '$'
},
dust: {
exports: 'dust'
},
'dust-helpers': {
deps: ['dust']
},
templates: {
deps: ['dust']
}
}
});
require(['app/app']);
\ No newline at end of file
define(function(require) {
'use strict';
// Constants
var LOCAL_STORAGE_KEY = 'todos-lavaca-require';
var Collection = require('lavaca/mvc/Collection');
/**
* A collection of ToDo items that saves
* and restores its data from localStorage
* @class app.models.TodosCollection
* @super Lavaca.mvc.Collection
*/
var TodosCollection = Collection.extend(function TodosCollection() {
// Call the super class' constructor
Collection.apply(this, arguments);
// Set some computed properties on this model
this.apply({
allComplete: allComplete,
itemsLeft: itemsLeft,
itemsCompleted: itemsCompleted
});
// Restore any data from localStorage
restore.call(this);
// Listen for changes to the models and then
// save them in localStorage
this.on('addItem', store);
this.on('moveItem', store);
this.on('removeItem', store);
this.on('changeItem', store);
}, {
/**
* @method removeCompleted
* Remove models that are complete
*/
removeCompleted: function () {
this.remove({completed: true});
}
});
/* ---- Computed Properties ---- */
// Returns a boolean indicating whether
// all items are complete
function allComplete() {
var allAreComplete = true;
this.each(function (index, model) {
if (!model.get('completed')) {
allAreComplete = false;
return false; // break out of `each` loop
}
});
return allAreComplete;
}
// Returns a count of incomplete items
function itemsLeft() {
return this.filter({completed: false}).length;
}
// Returns a count of complete items
function itemsCompleted() {
return this.filter({completed: true}).length;
}
/* ---- Handle Persistence ---- */
// Called every time the models change.
// Set a timeout that will write the data
// to localStorage. Clear the timeout with
// every call to make sure that data is only
// written once even if multiple changes
// are made in the same run loop
function store() {
clearTimeout(this.storeTimer);
this.storeTimer = setTimeout(function () {
// Safari will throw an exception
// when trying to write to localStorage in
// private browsing mode
try {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.toObject().items));
} catch (e) {}
}.bind(this));
}
// Pull the data from localStorage and
// add it to the collection
function restore() {
var data;
var i;
try {
data = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (data) {
for (i = 0; i < data.length; i++) {
this.add(data[i]);
}
}
} catch (e) {}
}
return new TodosCollection();
});
define(function(require) {
'use strict';
var Controller = require('lavaca/mvc/Controller');
var TodosView = require('app/ui/views/TodosView');
var todosCollection = require('app/models/TodosCollection');
/**
* @class app.net.TodosController
* @super Lavaca.mvc.Controller
* Todos controller
*/
var TodosController = Controller.extend({
home: function (params) {
// Set the `filter` parameter on the collection based
// on the values defined with the routes in app.js
todosCollection.set('filter', params.filter);
// Create an instance of TodosView with `collection` as its model
// and then set a history state which will update the URL
return this
.view(null, TodosView, todosCollection)
.then(this.history({}, document.title, params.url));
}
});
return TodosController;
});
\ No newline at end of file
define(function (require) {
'use strict';
var View = require('lavaca/mvc/View');
var Promise = require('lavaca/util/Promise');
var $ = require('$');
var _UNDEFINED;
/**
* A view for synchronizing a collection of models with sub views
* @class app.ui.views.CollectionView
* @super lavaca.mvc.View
*/
var CollectionView = View.extend(function CollectionView() {
// Call the super class' constructor
View.apply(this, arguments);
this.el.empty();
this.collectionViews = [];
this.mapEvent({
model: {
'addItem': this.onItemEvent.bind(this),
'moveItem': this.onItemEvent.bind(this),
'removeItem': this.onItemEvent.bind(this),
'changeItem': this.onItemEvent.bind(this)
}
});
}, {
/**
* A class name added to the view container
* @property className
* @type String
*/
className: 'collection-view',
/**
* A function that should return a jQuery element
* that will be used as the `el` for a particular
* item in the collection. The function is passed
* two parameters, the model and the index.
* @property itemEl
* @type jQuery
*/
itemEl: function () {
return $('<div/>'); // default to <li>?
},
/**
* The view type used for each item view
* @property TView
* @type lavaca.mvc.View
*/
TView: View,
/**
* Initializes and renders all item views to be shown
* @method render
*/
render: function () {
var models = this.model.filter(this.modelFilter.bind(this));
var fragment = document.createDocumentFragment();
var view;
models.forEach(function (item) {
view = this.addItemView(item);
fragment.appendChild(view.el[0]);
}.bind(this));
this.trigger('rendersuccess', {html: fragment});
return new Promise().resolve();
},
/**
* Creates a new view and inserts it into the DOM at the
* provided index
* @method addItemView
* @param {Object} [model] the model for the view
* @param {Number} [index] the index to insert the view in the DOM
*/
addItemView: function (model, index) {
var count = this.collectionViews.length;
var insertIndex = index === null || index === _UNDEFINED ? count : index;
var view;
if (insertIndex < 0 || insertIndex > count) {
throw 'Invalid item view insertion index';
}
view = new this.TView(this.itemEl(model, index), model, this);
this.childViews.set(view.id, view);
this.collectionViews.splice(insertIndex, 0, view);
this.applyChildViewEvent(view);
if (insertIndex === 0) {
this.el.prepend(view.el[0]);
} else if (insertIndex === count) {
this.el.append(view.el[0]);
} else {
this.el
.children()
.eq(insertIndex - 1)
.after(view.el[0]);
}
return view;
},
/**
* adds listeners for a specific child view
* @method applyChildViewEvent
* @param {Object} [view] the view to add listeners to
*/
applyChildViewEvent: function (view) {
var childViewEventMap = this.childViewEventMap;
var type;
for (type in childViewEventMap) {
if (view instanceof childViewEventMap[type].TView) {
view.on(type, childViewEventMap[type].callback);
}
}
},
/**
* Remove and disposes a view
* @method removeItemView
* @param {Number} [index] the index of the view to remove
*/
removeItemView: function (index) {
var view = this.collectionViews.splice(index, 1)[0];
this.childViews.remove(view.id);
view.el.remove();
view.dispose();
},
/**
* Returns the index of a view
* @method getViewIndexByModel
* @param {Object} [model] the model of the view to find
*/
getViewIndexByModel: function (model) {
var collectionViewIndex = -1;
this.collectionViews.every(function (view, i) {
if (view.model === model) {
collectionViewIndex = i;
return false;
}
return true;
});
return collectionViewIndex;
},
/**
* The filter to run against the collection
* @method modelFilter
* @param {Number} [i] the index
* @param {Object} [model] the model
*/
modelFilter: function () {
return true;
},
/**
* Event handler for all collection events that produces all add, remove, and move actions
* @method modelFilter
* @param {Obejct} [e] the event
*/
onItemEvent: function () {
var models = this.model.filter(this.modelFilter.bind(this));
var i = -1;
var model, view, viewIndex, oldIndex, modelIndex, temp;
// Add new views
while (model = models[++i]) {
viewIndex = this.getViewIndexByModel(model);
if (viewIndex === -1) {
this.addItemView(model, i);
}
}
// Remove Old Views
i = -1;
while (view = this.collectionViews[++i]) {
modelIndex = models.indexOf(view.model);
if (modelIndex === -1) {
this.removeItemView(i);
}
}
// Move any existing views
i = -1;
while (model = models[++i]) {
oldIndex = this.getViewIndexByModel(model);
if (oldIndex !== i) {
this.swapViews(this.collectionViews[i], this.collectionViews[oldIndex]);
temp = this.collectionViews[oldIndex];
this.collectionViews[oldIndex] = this.collectionViews[i];
this.collectionViews[i] = temp;
}
}
},
/**
* Swaps two views in the DOM
* @method swapViews
* @param {Obejct} [viewA] a view
* @param {Obejct} [viewB] another view
*/
swapViews: function (viewA, viewB) {
var a = viewA.el[0];
var b = viewB.el[0];
var aParent = a.parentNode;
var aSibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aParent.insertBefore(b, aSibling);
}
});
return CollectionView;
});
define(function (require) {
'use strict';
// constants
var ENTER_KEY = 13;
var ESC_KEY = 27;
var View = require('lavaca/mvc/View');
require('rdust!templates/todo-item');
/**
* Todos view type
* @class app.ui.views.TodosView
* @super Lavaca.mvc.View
*/
var TodosView = View.extend(function TodosView() {
// Call the super class' constructor
View.apply(this, arguments);
this.mapEvent({
'input.toggle': {
change: toggleComplete.bind(this)
},
'self': {
dblclick: startEditing.bind(this)
},
'input.edit': {
keydown: editTodo.bind(this),
blur: endEditing.bind(this)
},
'button.destroy': {
click: remove.bind(this)
},
model: {
'change': this.onModelChange.bind(this)
}
});
this.render();
}, {
/**
* The name for the template used in the view
* @property template
* @type String
*/
template: 'templates/todo-item',
/**
* A class name added to the view container
* @property className
* @type String
*/
className: 'todo-item',
/**
* Executes when the template renders successfully
* @method onRenderSuccess
*/
onRenderSuccess: function () {
View.prototype.onRenderSuccess.apply(this, arguments);
this.checkIfCompleted();
},
/**
* Redraws template with model
* @method redraw
*/
redraw: function () {
View.prototype.redraw.apply(this, arguments)
.then(this.checkIfCompleted.bind(this));
},
/**
* Adds/Removes a completed class to view element,
* this wouldnt be needed if we restructured some DOM or CSS
* @method checkIfCompleted
*/
checkIfCompleted: function () {
this.$input = this.el.find('.edit'); // cache input element
if (this.model.get('completed')) {
this.el.addClass('completed');
} else {
this.el.removeClass('completed');
}
},
/**
* Redraws template when model changes
* @method onModelChange
*/
onModelChange: function () {
if (this.model) {
this.redraw();
}
}
});
// Set the completion state of a single model
function toggleComplete(e) {
this.model.set('completed', e.currentTarget.checked);
}
// Start editing a Todo
function startEditing() {
this.el.addClass('editing');
this.$input.focus();
this.$input.val(this.model.get('title')); // resetting value fixes text selection on focus
}
// Commit the edit when the ENTER key
// is pressed
function editTodo(e) {
if (e.which === ENTER_KEY) {
endEditing.call(this);
} else if (e.which === ESC_KEY) {
this.$input.val(this.model.get('title'));
endEditing.call(this);
}
}
function endEditing() {
var trimmedValue = this.$input.val().trim();
this.el.removeClass('editing');
if (trimmedValue) {
this.model.set('title', trimmedValue);
} else {
remove.call(this);
}
}
// Remove the Todo when the 'x' is clicked
function remove() {
this.trigger('removeView', {model: this.model});
}
return TodosView;
});
define(function (require) {
'use strict';
var CollectionView = require('app/ui/views/CollectionView');
var TodoItemView = require('app/ui/views/TodoItemView');
var $ = require('$');
/**
* Todos view type
* @class app.ui.views.TodosCollectionView
* @super app/ui/views/CollectionView
*/
var TodosCollectionView = CollectionView.extend(function TodosCollectionView() {
CollectionView.apply(this, arguments);
this.mapChildViewEvent('removeView', this.onRemoveView.bind(this), this.TView);
this.render();
}, {
/**
* A class name added to the view container
* @property className
* @type String
*/
className: 'todos-collection-view',
/**
* A function that should return a jQuery element
* that will be used as the `el` for a particular
* item in the collection. The function is passed
* two parameters, the model and the index.
* @property itemEl
* @type jQuery
*/
itemEl: function () {
return $('<li/>');
},
/**
* The view type used for each item view
* @property itemEl
* @type lavaca.mvc.View
*/
TView: TodoItemView,
/**
* Executes when the template renders successfully
* @method onRenderSuccess
*
* @param {Event} e The render event. This object should have a string property named "html"
* that contains the template's rendered HTML output.
*/
onRenderSuccess: function (e) {
this.el.html(e.html);
this.bindMappedEvents();
this.applyEvents();
this.createWidgets();
this.el.data('view', this);
this.el.attr('data-view-id', this.id);
this.hasRendered = true;
},
/**
* The filter to run against the collection
* @method modelFilter
* @param {Number} [i] the index
* @param {Object} [model] the model
*/
modelFilter: function (i, model) {
var filter = this.model.get('filter');
var shouldBeComplete = filter === 'completed';
if (filter === 'all' || model.get('completed') === shouldBeComplete) {
return true;
}
},
/**
* Removes a view when removeView event it triggered
* @method swapViews
* @param {Obejct} [viewA] a view
* @param {Obejct} [viewB] another view
*/
onRemoveView: function (e) {
this.model.remove(e.model);
}
});
return TodosCollectionView;
});
\ No newline at end of file
define(function (require) {
'use strict';
// constants
var ENTER_KEY = 13;
var PageView = require('lavaca/mvc/PageView');
var TodosCollectionView = require('app/ui/views/TodosCollectionView');
require('rdust!templates/todos');
/**
* Todos view type
* @class app.ui.views.TodosView
* @super Lavaca.mvc.PageView
*/
var TodosView = PageView.extend(function TodosView() {
// Call the super class' constructor
PageView.apply(this, arguments);
// Map collection view to #todo-list
this.mapChildView('#todo-list', TodosCollectionView, this.model);
// Map DOM and model events to event handler
// functions declared below
this.mapEvent({
'#new-todo': {
keypress: addTodo.bind(this)
},
'input#toggle-all': {
change: toggleAll.bind(this)
},
'button#clear-completed': {
click: removeCompleted.bind(this)
},
model: {
'addItem': modelChange.bind(this),
'moveItem': modelChange.bind(this),
'removeItem': modelChange.bind(this),
'changeItem': modelChange.bind(this)
}
});
this.countIsZero = !this.model.count();
}, {
/**
* @field {String} template
* @default 'example'
* The name of the template used by the view
*/
template: 'templates/todos',
/**
* @field {String} className
* @default 'example'
* A class name added to the view container
*/
className: 'todos'
});
/* ---- Event Handlers ---- */
// Whenever the model changes, set a timeout
// that will re-render the view's template
// and update the DOM. Clear the timeout with
// every call to make sure that the redraw
// only happens once even if multiple changes
// are made in the same run loop
function modelChange() {
clearTimeout(this.redrawTimeout);
this.redrawTimeout = setTimeout(function () {
var count = this.model.count();
if (count === 0) {
this.countIsZero = true;
this.redraw();
} else if (this.countIsZero && count) {
this.countIsZero = false;
this.redraw();
} else {
this.redraw('#footer, #toggle-all');
}
}.bind(this));
}
// Create a new Todo when the ENTER
// key is pressed
function addTodo(e) {
var input = e.currentTarget;
var val;
if (e.which === ENTER_KEY) {
val = input.value.trim();
if (val) {
this.model.add({
id: Date.now(),
title: val,
completed: false
});
input.value = '';
}
e.preventDefault();
}
}
// Set the completion state of all models
function toggleAll(e) {
this.model.each(function (index, model) {
model.set('completed', e.currentTarget.checked);
});
}
// Remove all completed Todos
function removeCompleted() {
this.model.removeCompleted();
}
return TodosView;
});
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* AMD implementation for dust.js
* This is based on require-cs code.
* see: http://github.com/jrburke/require-cs for details
*/
/*jslint */
/*global define, window, XMLHttpRequest, importScripts, Packages, java,
ActiveXObject, process, require */
define(function() {
'use strict';
var fs, getXhr,
progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
fetchText = function () {
throw new Error('Environment unsupported.');
},
buildMap = {},
isBrowser = (typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined",
isNode = typeof process !== "undefined" && process.versions && !!process.versions.node;
if (typeof process !== "undefined" &&
process.versions &&
!!process.versions.node) {
//Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs');
fetchText = function (path, callback) {
callback(fs.readFileSync(path, 'utf8'));
};
} else if ((typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined") {
// Browser action
getXhr = function () {
//Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var xhr, i, progId;
if (typeof XMLHttpRequest !== "undefined") {
return new XMLHttpRequest();
} else {
for (i = 0; i < 3; i++) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
} catch (e) {}
if (xhr) {
progIds = [progId]; // so faster next time
break;
}
}
}
if (!xhr) {
throw new Error("getXhr(): XMLHttpRequest not available");
}
return xhr;
};
fetchText = function (url, callback) {
var xhr = getXhr();
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);
};
// end browser.js adapters
} else if (typeof Packages !== 'undefined') {
//Why Java, why is this so awkward?
fetchText = function (path, callback) {
var encoding = "utf-8",
file = new java.io.File(path),
lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
stringBuffer, line,
content = '';
try {
stringBuffer = new java.lang.StringBuffer();
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);
};
}
return {
write: function (pluginName, name, write) {
if (buildMap.hasOwnProperty(name)) {
var text = buildMap[name];
write.asModule(pluginName + "!" + name, text);
}
},
load: function (name, parentRequire, load, config) {
var self = this;
if (isBrowser) {
require(['dust'], function(dust) { self.process(dust, name, parentRequire, load, config); });
} else if(isNode) {
self.process(require.nodeRequire('dustjs-linkedin'), name, parentRequire, load, config);
}
},
process: function(dust, name, parentRequire, load, config) {
var path = parentRequire.toUrl(name + '.html');
fetchText(path, function (text) {
//Do dust transform.
try {
text = "define(['dust'],function(dust){"+dust.compile(text, name)+" return {render: function(context, callback) {return dust.render('"+name+"', context, callback)}}})";
}
catch (err) {
err.message = "In " + path + ", " + err.message;
throw(err);
}
//Hold on to the transformed text if a build.
if (config.isBuild) {
buildMap[name] = text;
}
//IE with conditional comments on cannot handle the
//sourceURL trick, so skip it if enabled.
/*@if (@_jscript) @else @*/
if (!config.isBuild) {
text += "\r\n//@ sourceURL=" + path;
}
/*@end@*/
load.fromText('rdust!' + name, text);
});
}
};
});
<div class="view" data-id="{id}">
<input class="toggle" type="checkbox" {?completed}checked{/completed}>
<label>{title}</label>
<button class="destroy"></button>
</div>
<input class="edit" value="{title}">
\ No newline at end of file
<header id="header">
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
</header>
{?items}
<section id="main">
<input id="toggle-all" type="checkbox" {?allComplete}checked{/allComplete}>
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list" {@eq key=filter value="active"}class="active"{/eq}{@eq key=filter value="completed"}class="completed"{/eq}></ul>
</section>
<footer id="footer">
<span id="todo-count"><strong>{itemsLeft}</strong> item{@ne key=itemsLeft value="1" type="number"}s{/ne} left</span>
<ul id="filters">
<li>
<a {@eq key=filter value="all"}class="selected"{/eq} href="/">All</a>
</li>
<li>
<a {@eq key=filter value="active"}class="selected"{/eq} href="/active">Active</a>
</li>
<li>
<a {@eq key=filter value="completed"}class="selected"{/eq} href="/completed">Completed</a>
</li>
</ul>
{@gt key=itemsCompleted value="0"}<button id="clear-completed">Clear completed ({itemsCompleted})</button>{/gt}
</footer>
{/items}
\ No newline at end of file
......@@ -1245,6 +1245,40 @@
}]
}]
},
"lavaca": {
"name": "Lavaca",
"description": "A curated collection of tools for building mobile web applications.",
"homepage": "getlavaca.com",
"examples": [{
"name": "Dependency Example",
"url": "labs/dependency-examples/lavaca_require"
}],
"link_groups": [{
"heading": "Official Resources",
"links": [{
"name": "Guide",
"url": "http://getlavaca.com/#/guide"
}, {
"name": "API Reference",
"url": "http://getlavaca.com/#/apidoc"
}, {
"name": "Live examples",
"url": "http://getlavaca.com/#/examples"
}]
}, {
"heading": "Articles and Guides",
"links": [{
"name": "Why Lavaca is the only sane HTML5 mobile development framework out there",
"url": "http://povolotski.me/2013/09/20/lavaca-intro/"
}]
}, {
"heading": "Community",
"links": [{
"name": "Lavaca on Twitter",
"url": "http://twitter.com/getlavaca"
}]
}]
},
"maria": {
"name": "Maria",
"description": "The MVC framework for JavaScript applications. The real MVC. The Smalltalk MVC. The Gang of Four MVC.",
......
......@@ -79,6 +79,7 @@ We also have a number of in-progress applications in Labs:
- [Aria Templates](http://ariatemplates.com/)
- [Enyo + Backbone.js](http://enyojs.com/)
- [SAPUI5](http://scn.sap.com/community/developer-center/front-end)
- [Lavaca](http://getlavaca.com) + [RequireJS](http://requirejs.org) (using AMD)
## Live demos
......
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