Commit 7d6dd975 authored by Stephen Sawchuk's avatar Stephen Sawchuk

olives upgraded to bower.

parent 23d7c727
{
"name": "todomvc-olives",
"version": "0.0.0",
"dependencies": {
"olives": "~1.4.0",
"emily": "~1.3.5",
"requirejs": "~2.1.5",
"todomvc-common": "~0.1.2"
}
}
/**
* @license Emily <VERSION> http://flams.github.com/emily
*
* The MIT License (MIT)
*
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
*/
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Tools',[],
/**
* @class
* Tools is a collection of tools
*/
function Tools(){
return {
/**
* For applications that don't run in a browser, window is not the global object.
* This function returns the global object wherever the application runs.
* @returns {Object} the global object
*/
getGlobal: function getGlobal() {
var func = function() {
return this;
};
return func.call(null);
},
/**
* Mixes an object into another
* @param {Object} source object to get values from
* @param {Object} destination object to mix values into
* @param {Boolean} optional, set to true to prevent overriding
* @returns {Object} the destination object
*/
mixin: function mixin(source, destination, dontOverride) {
this.loop(source, function (value, idx) {
if (!destination[idx] || !dontOverride) {
destination[idx] = source[idx];
}
});
return destination;
},
/**
* Count the number of properties in an object
* It doesn't look up in the prototype chain
* @param {Object} object the object to count
* @returns {Number}
*/
count: function count(object) {
var nbItems = 0;
this.loop(object, function () {
nbItems++;
});
return nbItems;
},
/**
* Compares the properties of two objects and returns true if they're the same
* It's doesn't do it recursively
* @param {Object} first object
* @param {Object} second object
* @returns {Boolean} true if the two objets have the same properties
*/
compareObjects: function compareObjects(object1, object2) {
var getOwnProperties = function (object) {
return Object.getOwnPropertyNames(object).sort().join("");
};
return getOwnProperties(object1) == getOwnProperties(object2);
},
/**
* Compares two numbers and tells if the first one is bigger (1), smaller (-1) or equal (0)
* @param {Number} number1 the first number
* @param {Number} number2 the second number
* @returns 1 if number1>number2, -1 if number2>number1, 0 if equal
*/
compareNumbers: function compareNumbers(number1, number2) {
if (number1>number2) {
return 1;
} else if (number1<number2) {
return -1;
} else {
return 0;
}
},
/**
* Transform array-like objects to array, such as nodeLists or arguments
* @param {Array-like object}
* @returns {Array}
*/
toArray: function toArray(array) {
return [].slice.call(array);
},
/**
* Small adapter for looping over objects and arrays
* Warning: it's not meant to be used with nodeList
* To use with nodeList, convert to array first
* @param {Array/Object} iterated the array or object to loop through
* @param {Function} callback the function to execute for each iteration
* @param {Object} scope the scope in which to execute the callback
* @returns {Boolean} true if executed
*/
loop: function loop(iterated, callback, scope) {
var i,
length;
if (iterated instanceof Object && callback instanceof Function) {
if (iterated instanceof Array) {
for (i=0; i<iterated.length; i++) {
callback.call(scope, iterated[i], i, iterated);
}
} else {
for (i in iterated) {
if (iterated.hasOwnProperty(i)) {
callback.call(scope, iterated[i], i, iterated);
}
}
}
return true;
} else {
return false;
}
},
/**
* Make a diff between two objects
* @param {Array/Object} before is the object as it was before
* @param {Array/Object} after is what it is now
* @example:
* With objects:
*
* before = {a:1, b:2, c:3, d:4, f:6}
* after = {a:1, b:20, d: 4, e: 5}
* will return :
* {
* unchanged: ["a", "d"],
* updated: ["b"],
* deleted: ["f"],
* added: ["e"]
* }
*
* It also works with Arrays:
*
* before = [10, 20, 30]
* after = [15, 20]
* will return :
* {
* unchanged: [1],
* updated: [0],
* deleted: [2],
* added: []
* }
*
* @returns object
*/
objectsDiffs : function objectsDiffs(before, after) {
if (before instanceof Object && after instanceof Object) {
var unchanged = [],
updated = [],
deleted = [],
added = [];
// Look through the after object
this.loop(after, function (value, idx) {
// To get the added
if (typeof before[idx] == "undefined") {
added.push(idx);
// The updated
} else if (value !== before[idx]) {
updated.push(idx);
// And the unchanged
} else if (value === before[idx]) {
unchanged.push(idx);
}
});
// Loop through the before object
this.loop(before, function (value, idx) {
// To get the deleted
if (typeof after[idx] == "undefined") {
deleted.push(idx);
}
});
return {
updated: updated,
unchanged: unchanged,
added: added,
deleted: deleted
};
} else {
return false;
}
},
/**
* Transforms Arrays and Objects into valid JSON
* @param {Object/Array} object the object to JSONify
* @returns the JSONified object or false if failed
*/
jsonify: function jsonify(object) {
if (object instanceof Object) {
return JSON.parse(JSON.stringify(object));
} else {
return false;
}
},
/**
* Clone an Array or an Object
* @param {Array/Object} object the object to clone
* @returns {Array/Object} the cloned object
*/
clone: function clone(object) {
if (object instanceof Array) {
return object.slice(0);
} else if (typeof object == "object" && object !== null && !(object instanceof RegExp)) {
return this.mixin(object, {});
} else {
return false;
}
},
/**
*
*
*
*
* Refactoring needed for the following
*
*
*
*
*
*/
/**
* Get the property of an object nested in one or more objects
* given an object such as a.b.c.d = 5, getNestedProperty(a, "b.c.d") will return 5.
* @param {Object} object the object to get the property from
* @param {String} property the path to the property as a string
* @returns the object or the the property value if found
*/
getNestedProperty: function getNestedProperty(object, property) {
if (object && object instanceof Object) {
if (typeof property == "string" && property != "") {
var split = property.split(".");
return split.reduce(function (obj, prop) {
return obj && obj[prop];
}, object);
} else if (typeof property == "number") {
return object[property];
} else {
return object;
}
} else {
return object;
}
},
/**
* Set the property of an object nested in one or more objects
* If the property doesn't exist, it gets created.
* @param {Object} object
* @param {String} property
* @param value the value to set
* @returns object if no assignment was made or the value if the assignment was made
*/
setNestedProperty: function setNestedProperty(object, property, value) {
if (object && object instanceof Object) {
if (typeof property == "string" && property != "") {
var split = property.split(".");
return split.reduce(function (obj, prop, idx) {
obj[prop] = obj[prop] || {};
if (split.length == (idx + 1)) {
obj[prop] = value;
}
return obj[prop];
}, object);
} else if (typeof property == "number") {
object[property] = value;
return object[property];
} else {
return object;
}
} else {
return object;
}
}
};
});
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Observable',["Tools"],
/**
* @class
* Observable is an implementation of the Observer design pattern,
* which is also known as publish/subscribe.
*
* This service creates an Observable on which you can add subscribers.
*/
function Observable(Tools) {
/**
* Defines the Observable
* @private
* @returns {_Observable}
*/
return function ObservableConstructor() {
/**
* The list of topics
* @private
*/
var _topics = {};
/**
* Add an observer
* @param {String} topic the topic to observe
* @param {Function} callback the callback to execute
* @param {Object} scope the scope in which to execute the callback
* @returns handle
*/
this.watch = function watch(topic, callback, scope) {
if (typeof callback == "function") {
var observers = _topics[topic] = _topics[topic] || [],
observer = [callback, scope];
observers.push(observer);
return [topic,observers.indexOf(observer)];
} else {
return false;
}
};
/**
* Remove an observer
* @param {Handle} handle returned by the watch method
* @returns {Boolean} true if there were subscribers
*/
this.unwatch = function unwatch(handle) {
var topic = handle[0], idx = handle[1];
if (_topics[topic] && _topics[topic][idx]) {
// delete value so the indexes don't move
delete _topics[topic][idx];
// If the topic is only set with falsy values, delete it;
if (!_topics[topic].some(function (value) {
return !!value;
})) {
delete _topics[topic];
}
return true;
} else {
return false;
}
};
/**
* Notifies observers that a topic has a new message
* @param {String} topic the name of the topic to publish to
* @param subject
* @returns {Boolean} true if there was subscribers
*/
this.notify = function notify(topic) {
var observers = _topics[topic],
args = Tools.toArray(arguments).slice(1);
if (observers) {
Tools.loop(observers, function (value) {
try {
value && value[0].apply(value[1] || null, args);
} catch (err) { }
});
return true;
} else {
return false;
}
},
/**
* Check if topic has the described observer
* @param {Handle}
* @returns {Boolean} true if exists
*/
this.hasObserver = function hasObserver(handle) {
return !!( handle && _topics[handle[0]] && _topics[handle[0]][handle[1]]);
};
/**
* Check if a topic has observers
* @param {String} topic the name of the topic
* @returns {Boolean} true if topic is listened
*/
this.hasTopic = function hasTopic(topic) {
return !!_topics[topic];
};
/**
* Unwatch all or unwatch all from topic
* @param {String} topic optional unwatch all from topic
* @returns {Boolean} true if ok
*/
this.unwatchAll = function unwatchAll(topic) {
if (_topics[topic]) {
delete _topics[topic];
} else {
_topics = {};
}
return true;
};
};
});
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('StateMachine',["Tools"],
/**
* @class
* Create a stateMachine
*/
function StateMachine(Tools) {
/**
* @param initState {String} the initial state
* @param diagram {Object} the diagram that describes the state machine
* @example
*
* diagram = {
* "State1" : [
* [ message1, action, nextState], // Same as the state's add function
* [ message2, action2, nextState]
* ],
*
* "State2" :
* [ message3, action3, scope3, nextState]
* ... and so on ....
*
* }
*
* @return the stateMachine object
*/
function StateMachineConstructor($initState, $diagram) {
/**
* The list of states
* @private
*/
var _states = {},
/**
* The current state
* @private
*/
_currentState = "";
/**
* Set the initialization state
* @param {String} name the name of the init state
* @returns {Boolean}
*/
this.init = function init(name) {
if (_states[name]) {
_currentState = name;
return true;
} else {
return false;
}
};
/**
* Add a new state
* @private
* @param {String} name the name of the state
* @returns {State} a new state
*/
this.add = function add(name) {
if (!_states[name]) {
return _states[name] = new Transition();
} else {
return _states[name];
}
};
/**
* Get an existing state
* @private
* @param {String} name the name of the state
* @returns {State} the state
*/
this.get = function get(name) {
return _states[name];
};
/**
* Get the current state
* @returns {String}
*/
this.getCurrent = function getCurrent() {
return _currentState;
};
/**
* Tell if the state machine has the given state
* @param {String} state the name of the state
* @returns {Boolean} true if it has the given state
*/
this.has = function has(state) {
return _states.hasOwnProperty(state);
};
/**
* Advances the state machine to a given state
* @param {String} state the name of the state to advance the state machine to
* @returns {Boolean} true if it has the given state
*/
this.advance = function advance(state) {
if (this.has(state)) {
_currentState = state;
return true;
} else {
return false;
}
};
/**
* Pass an event to the state machine
* @param {String} name the name of the event
* @returns {Boolean} true if the event exists in the current state
*/
this.event = function event(name) {
var nextState;
nextState = _states[_currentState].event.apply(_states[_currentState].event, Tools.toArray(arguments));
// False means that there's no such event
// But undefined means that the state doesn't change
if (nextState === false) {
return false;
} else {
// There could be no next state, so the current one remains
if (nextState) {
// Call the exit action if any
_states[_currentState].event("exit");
_currentState = nextState;
// Call the new state's entry action if any
_states[_currentState].event("entry");
}
return true;
}
};
/**
* Initializes the StateMachine with the given diagram
*/
Tools.loop($diagram, function (transition, state) {
var myState = this.add(state);
transition.forEach(function (params){
myState.add.apply(null, params);
});
}, this);
/**
* Sets its initial state
*/
this.init($initState);
}
/**
* Each state has associated transitions
* @constructor
*/
function Transition() {
/**
* The list of transitions associated to a state
* @private
*/
var _transitions = {};
/**
* Add a new transition
* @private
* @param {String} event the event that will trigger the transition
* @param {Function} action the function that is executed
* @param {Object} scope [optional] the scope in which to execute the action
* @param {String} next [optional] the name of the state to transit to.
* @returns {Boolean} true if success, false if the transition already exists
*/
this.add = function add(event, action, scope, next) {
var arr = [];
if (_transitions[event]) {
return false;
}
if (typeof event == "string"
&& typeof action == "function") {
arr[0] = action;
if (typeof scope == "object") {
arr[1] = scope;
}
if (typeof scope == "string") {
arr[2] = scope;
}
if (typeof next == "string") {
arr[2] = next;
}
_transitions[event] = arr;
return true;
}
return false;
};
/**
* Check if a transition can be triggered with given event
* @private
* @param {String} event the name of the event
* @returns {Boolean} true if exists
*/
this.has = function has(event) {
return !!_transitions[event];
};
/**
* Get a transition from it's event
* @private
* @param {String} event the name of the event
* @return the transition
*/
this.get = function get(event) {
return _transitions[event] || false;
};
/**
* Execute the action associated to the given event
* @param {String} event the name of the event
* @param {params} params to pass to the action
* @private
* @returns false if error, the next state or undefined if success (that sounds weird)
*/
this.event = function event(event) {
var _transition = _transitions[event];
if (_transition) {
_transition[0].apply(_transition[1], Tools.toArray(arguments).slice(1));
return _transition[2];
} else {
return false;
}
};
};
return StateMachineConstructor;
});
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Promise',["Observable", "StateMachine"],
/**
* @class
* Create a promise/A+
*/
function Promise(Observable, StateMachine) {
return function PromiseConstructor() {
/**
* The fulfilled value
* @private
*/
var _value = null,
/**
* The rejection reason
* @private
*/
_reason = null,
/**
* The funky observable
* @private
*/
_observable = new Observable,
/**
* The state machine States & transitions
* @private
*/
_states = {
// The promise is pending
"Pending": [
// It can only be fulfilled when pending
["fulfill", function onFulfill(value) {
_value = value;
_observable.notify("fulfill", value);
// Then it transits to the fulfilled state
}, "Fulfilled"],
// it can only be rejected when pending
["reject", function onReject(reason) {
_reason = reason;
_observable.notify("reject", reason);
// Then it transits to the rejected state
}, "Rejected"],
// When pending, add the resolver to an observable
["toFulfill", function toFulfill(resolver) {
_observable.watch("fulfill", resolver);
}],
// When pending, add the resolver to an observable
["toReject", function toReject(resolver) {
_observable.watch("reject", resolver);
}]],
// When fulfilled,
"Fulfilled": [
// We directly call the resolver with the value
["toFulfill", function toFulfill(resolver) {
setTimeout(function () {
resolver(_value);
}, 0);
}]],
// When rejected
"Rejected": [
// We directly call the resolver with the reason
["toReject", function toReject(resolver) {
setTimeout(function () {
resolver(_reason);
}, 0);
}]]
},
/**
* The stateMachine
* @private
*/
_stateMachine = new StateMachine("Pending", _states);
/**
* Fulfilled the promise.
* A promise can be fulfilld only once.
* @param the fulfillment value
* @returns the promise
*/
this.fulfill = function fulfill(value) {
_stateMachine.event("fulfill", value);
return this;
};
/**
* Reject the promise.
* A promise can be rejected only once.
* @param the rejection value
* @returns true if the rejection function was called
*/
this.reject = function reject(reason) {
_stateMachine.event("reject", reason);
return this;
};
/**
* The callbacks to call after fulfillment or rejection
* @param {Function} fulfillmentCallback the first parameter is a success function, it can be followed by a scope
* @param {Function} the second, or third parameter is the rejection callback, it can also be followed by a scope
* @examples:
*
* then(fulfillment)
* then(fulfillment, scope, rejection, scope)
* then(fulfillment, rejection)
* then(fulfillment, rejection, scope)
* then(null, rejection, scope)
* @returns {Promise} the new promise
*/
this.then = function then() {
var promise = new PromiseConstructor;
// If a fulfillment callback is given
if (arguments[0] instanceof Function) {
// If the second argument is also a function, then no scope is given
if (arguments[1] instanceof Function) {
_stateMachine.event("toFulfill", this.makeResolver(promise, arguments[0]));
} else {
// If the second argument is not a function, it's the scope
_stateMachine.event("toFulfill", this.makeResolver(promise, arguments[0], arguments[1]));
}
} else {
// If no fulfillment callback given, give a default one
_stateMachine.event("toFulfill", this.makeResolver(promise, function () {
promise.fulfill(_value);
}));
}
// if the second arguments is a callback, it's the rejection one, and the next argument is the scope
if (arguments[1] instanceof Function) {
_stateMachine.event("toReject", this.makeResolver(promise, arguments[1], arguments[2]));
}
// if the third arguments is a callback, it's the rejection one, and the next arguments is the sopce
if (arguments[2] instanceof Function) {
_stateMachine.event("toReject", this.makeResolver(promise, arguments[2], arguments[3]));
}
// If no rejection callback is given, give a default one
if (!(arguments[1] instanceof Function) &&
!(arguments[2] instanceof Function)) {
_stateMachine.event("toReject", this.makeResolver(promise, function () {
promise.reject(_reason);
}));
}
return promise;
};
/**
* Synchronize this promise with a thenable
* @returns {Boolean} false if the given sync is not a thenable
*/
this.sync = function sync(syncWith) {
if (syncWith instanceof Object && syncWith.then) {
var onFulfilled = function onFulfilled(value) {
this.fulfill(value);
},
onRejected = function onRejected(reason) {
this.reject(reason);
};
syncWith.then(onFulfilled.bind(this),
onRejected.bind(this));
return true;
} else {
return false;
}
};
/**
* Make a resolver
* for debugging only
* @private
* @returns {Function} a closure
*/
this.makeResolver = function makeResolver(promise, func, scope) {
return function resolver(value) {
var returnedPromise;
try {
returnedPromise = func.call(scope, value);
if (!promise.sync(returnedPromise)) {
promise.fulfill(returnedPromise);
}
} catch (err) {
promise.reject(err);
}
}
};
/**
* Returns the reason
* for debugging only
* @private
*/
this.getReason = function getReason() {
return _reason;
};
/**
* Returns the reason
* for debugging only
* @private
*/
this.getValue = function getValue() {
return _value;
};
/**
* Get the promise's observable
* for debugging only
* @private
* @returns {Observable}
*/
this.getObservable = function getObservable() {
return _observable;
};
/**
* Get the promise's stateMachine
* for debugging only
* @private
* @returns {StateMachine}
*/
this.getStateMachine = function getStateMachine() {
return _stateMachine;
};
/**
* Get the statesMachine's states
* for debugging only
* @private
* @returns {Object}
*/
this.getStates = function getStates() {
return _states;
};
}
});
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Store',["Observable", "Tools"],
/**
* @class
* Store creates an observable structure based on a key/values object
* or on an array
*/
function Store(Observable, Tools) {
/**
* Defines the Store
* @param {Array/Object} the data to initialize the store with
* @returns
*/
return function StoreConstructor($data) {
/**
* Where the data is stored
* @private
*/
var _data = Tools.clone($data) || {},
/**
* The observable for publishing changes on the store iself
* @private
*/
_storeObservable = new Observable(),
/**
* The observable for publishing changes on a value
* @private
*/
_valueObservable = new Observable(),
/**
* Gets the difference between two objects and notifies them
* @private
* @param {Object} previousData
*/
_notifyDiffs = function _notifyDiffs(previousData) {
var diffs = Tools.objectsDiffs(previousData, _data);
["updated",
"deleted",
"added"].forEach(function (value) {
diffs[value].forEach(function (dataIndex) {
_storeObservable.notify(value, dataIndex, _data[dataIndex]);
_valueObservable.notify(dataIndex, _data[dataIndex], value);
});
});
};
/**
* Get the number of items in the store
* @returns {Number} the number of items in the store
*/
this.getNbItems = function() {
return _data instanceof Array ? _data.length : Tools.count(_data);
};
/**
* Count is an alias for getNbItems
* @returns {Number} the number of items in the store
*/
this.count = this.getNbItems;
/**
* Get a value from its index
* @param {String} name the name of the index
* @returns the value
*/
this.get = function get(name) {
return _data[name];
};
/**
* Checks if the store has a given value
* @param {String} name the name of the index
* @returns {Boolean} true if the value exists
*/
this.has = function has(name) {
return _data.hasOwnProperty(name);
};
/**
* Set a new value and overrides an existing one
* @param {String} name the name of the index
* @param value the value to assign
* @returns true if value is set
*/
this.set = function set(name, value) {
var hasPrevious,
previousValue,
action;
if (typeof name != "undefined") {
hasPrevious = this.has(name);
previousValue = this.get(name);
_data[name] = value;
action = hasPrevious ? "updated" : "added";
_storeObservable.notify(action, name, _data[name], previousValue);
_valueObservable.notify(name, _data[name], action, previousValue);
return true;
} else {
return false;
}
};
/**
* Update the property of an item.
* @param {String} name the name of the index
* @param {String} property the property to modify.
* @param value the value to assign
* @returns false if the Store has no name index
*/
this.update = function update(name, property, value) {
var item;
if (this.has(name)) {
item = this.get(name);
Tools.setNestedProperty(item, property, value);
_storeObservable.notify("updated", property, value);
_valueObservable.notify(name, item, "updated");
return true;
} else {
return false;
}
};
/**
* Delete value from its index
* @param {String} name the name of the index from which to delete the value
* @returns true if successfully deleted.
*/
this.del = function del(name) {
if (this.has(name)) {
if (!this.alter("splice", name, 1)) {
delete _data[name];
_storeObservable.notify("deleted", name);
_valueObservable.notify(name, _data[name], "deleted");
}
return true;
} else {
return false;
}
};
/**
* Delete multiple indexes. Prefer this one over multiple del calls.
* @param {Array}
* @returns false if param is not an array.
*/
this.delAll = function delAll(indexes) {
if (indexes instanceof Array) {
// Indexes must be removed from the greatest to the lowest
// To avoid trying to remove indexes that don't exist.
// i.e: given [0, 1, 2], remove 1, then 2, 2 doesn't exist anymore
indexes.sort(Tools.compareNumbers)
.reverse()
.forEach(this.del, this);
return true;
} else {
return false;
}
};
/**
* Alter the data be calling one of it's method
* When the modifications are done, it notifies on changes.
* @param {String} func the name of the method
* @returns the result of the method call
*/
this.alter = function alter(func) {
var apply,
previousData;
if (_data[func]) {
previousData = Tools.clone(_data);
apply = _data[func].apply(_data, Array.prototype.slice.call(arguments, 1));
_notifyDiffs(previousData);
return apply;
} else {
return false;
}
};
/**
* proxy is an alias for alter
*/
this.proxy = this.alter;
/**
* Watch the store's modifications
* @param {String} added/updated/deleted
* @param {Function} func the function to execute
* @param {Object} scope the scope in which to execute the function
* @returns {Handle} the subscribe's handler to use to stop watching
*/
this.watch = function watch(name, func, scope) {
return _storeObservable.watch(name, func, scope);
};
/**
* Unwatch the store modifications
* @param {Handle} handle the handler returned by the watch function
* @returns
*/
this.unwatch = function unwatch(handle) {
return _storeObservable.unwatch(handle);
};
/**
* Get the observable used for watching store's modifications
* Should be used only for debugging
* @returns {Observable} the Observable
*/
this.getStoreObservable = function getStoreObservable() {
return _storeObservable;
};
/**
* Watch a value's modifications
* @param {String} name the name of the value to watch for
* @param {Function} func the function to execute
* @param {Object} scope the scope in which to execute the function
* @returns handler to pass to unwatchValue
*/
this.watchValue = function watchValue(name, func, scope) {
return _valueObservable.watch(name, func, scope);
};
/**
* Unwatch the value's modifications
* @param {Handler} handler the handler returned by the watchValue function
* @private
* @returns true if unwatched
*/
this.unwatchValue = function unwatchValue(handler) {
return _valueObservable.unwatch(handler);
};
/**
* Get the observable used for watching value's modifications
* Should be used only for debugging
* @private
* @returns {Observable} the Observable
*/
this.getValueObservable = function getValueObservable() {
return _valueObservable;
};
/**
* Loop through the data
* @param {Function} func the function to execute on each data
* @param {Object} scope the scope in wich to run the callback
*/
this.loop = function loop(func, scope) {
Tools.loop(_data, func, scope);
};
/**
* Reset all data and get notifications on changes
* @param {Arra/Object} data the new data
* @returns {Boolean}
*/
this.reset = function reset(data) {
if (data instanceof Object) {
var previousData = Tools.clone(_data);
_data = Tools.clone(data) || {};
_notifyDiffs(previousData);
return true;
} else {
return false;
}
};
/**
* Returns a JSON version of the data
* Use dump if you want all the data as a plain js object
* @returns {String} the JSON
*/
this.toJSON = function toJSON() {
return JSON.stringify(_data);
};
/**
* Returns the store's data
* @returns {Object} the data
*/
this.dump = function dump() {
return _data;
};
};
});
/**
* Emily
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Transport',[],
/**
* @class
* Transport hides and centralizes the logic behind requests.
* It can issue requests to request handlers, which in turn can issue requests
* to anything your node.js server has access to (HTTP, FileSystem, SIP...)
*/
function Transport() {
/**
* Create a Transport
* @param {Emily Store} [optionanl] $reqHandlers an object containing the request handlers
* @returns
*/
return function TransportConstructor($reqHandlers) {
/**
* The request handlers
* @private
*/
var _reqHandlers = null;
/**
* Set the requests handlers object
* @param {Emily Store} reqHandlers an object containing the requests handlers
* @returns
*/
this.setReqHandlers = function setReqHandlers(reqHandlers) {
if (reqHandlers instanceof Object) {
_reqHandlers = reqHandlers;
return true;
} else {
return false;
}
};
/**
* Get the requests handlers
* @returns{ Emily Store} reqHandlers the object containing the requests handlers
*/
this.getReqHandlers = function getReqHandlers() {
return _reqHandlers;
};
/**
* Issue a request to a request handler
* @param {String} reqHandler the name of the request handler to issue the request to
* @param {Object} data the data, or payload, to send to the request handler
* @param {Function} callback the function to execute with the result
* @param {Object} scope the scope in which to execute the callback
* @returns
*/
this.request = function request(reqHandler, data, callback, scope) {
if (_reqHandlers.has(reqHandler)
&& typeof data != "undefined") {
_reqHandlers.get(reqHandler)(data, function () {
callback && callback.apply(scope, arguments);
});
return true;
} else {
return false;
}
};
/**
* Issue a request to a reqHandler but keep listening for the response as it can be sent in several chunks
* or remain open as long as the abort funciton is not called
* @param {String} reqHandler the name of the request handler to issue the request to
* @param {Object} data the data, or payload, to send to the request handler
* @param {Function} callback the function to execute with the result
* @param {Object} scope the scope in which to execute the callback
* @returns {Function} the abort function to call to stop listening
*/
this.listen = function listen(reqHandler, data, callback, scope) {
if (_reqHandlers.has(reqHandler)
&& typeof data != "undefined"
&& typeof callback == "function") {
var func = function () {
callback.apply(scope, arguments);
},
abort;
abort = _reqHandlers.get(reqHandler)(data, func, func);
return function () {
if (typeof abort == "function") {
abort();
} else if (typeof abort == "object" && typeof abort.func == "function") {
abort.func.call(abort.scope);
}
};
} else {
return false;
}
};
this.setReqHandlers($reqHandlers);
};
});
/**
* @license Olives <VERSION> http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('DomUtils',["Tools"], function (Tools) {
return {
/**
* Returns a NodeList including the given dom node,
* its childNodes and its siblingNodes
* @param {HTMLElement|SVGElement} dom the dom node to start with
* @param {String} query an optional CSS selector to narrow down the query
* @returns the list of nodes
*/
getNodes: function getNodes(dom, query) {
if (this.isAcceptedType(dom)) {
if (!dom.parentNode) {
document.createDocumentFragment().appendChild(dom);
}
return dom.parentNode.querySelectorAll(query || "*");
} else {
return false;
}
},
/**
* Get a domNode's dataset attribute. If dataset doesn't exist (IE)
* then the domNode is looped through to collect them.
* @param {HTMLElement|SVGElement} dom
* @returns {Object} dataset
*/
getDataset: function getDataset(dom) {
var i=0,
l,
dataset={},
split,
join;
if (this.isAcceptedType(dom)) {
if (dom.hasOwnProperty("dataset")) {
return dom.dataset;
} else {
for (l=dom.attributes.length;i<l;i++) {
split = dom.attributes[i].name.split("-");
if (split.shift() == "data") {
dataset[join = split.join("-")] = dom.getAttribute("data-"+join);
}
}
return dataset;
}
} else {
return false;
}
},
/**
* Olives can manipulate HTMLElement and SVGElements
* This function tells if an element is one of them
* @param {Element} type
* @returns true if HTMLElement or SVGElement
*/
isAcceptedType: function isAcceptedType(type) {
if (type instanceof HTMLElement ||
type instanceof SVGElement) {
return true;
} else {
return false;
}
},
/**
* Assign a new value to an Element's property. Works with HTMLElement and SVGElement.
* @param {HTMLElement|SVGElement} node the node which property should be changed
* @param {String} property the name of the property
* @param {any} value the value to set
* @returns true if assigned
*/
setAttribute: function setAttribute(node, property, value) {
if (node instanceof HTMLElement) {
node[property] = value;
return true;
} else if (node instanceof SVGElement){
node.setAttribute(property, value);
return true;
} else {
return false;
}
},
/**
* Determine if an element matches a certain CSS selector.
* @param {Element} the parent node
* @param {String} CSS selector
* @param {Element} the node to check out
* @param true if matches
*/
matches : function matches(parent, selector, node){
return Tools.toArray(this.getNodes(parent, selector)).indexOf(node) > -1;
}
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('Bind.plugin',["Store", "Observable", "Tools", "DomUtils"],
/**
* @class
* This plugin links dom nodes to a model
* @requires Store, Observable
*/
function BindPlugin(Store, Observable, Tools, DomUtils) {
return function BindPluginConstructor($model, $bindings) {
/**
* The model to watch
* @private
*/
var _model = null,
/**
* The list of custom bindings
* @private
*/
_bindings = {},
/**
* The list of itemRenderers
* each foreach has its itemRenderer
* @private
*/
_itemRenderers = {};
/**
* The observers handlers
* for debugging only
* @private
*/
this.observers = {};
/**
* Define the model to watch for
* @param {Store} model the model to watch for changes
* @returns {Boolean} true if the model was set
*/
this.setModel = function setModel(model) {
if (model instanceof Store) {
// Set the model
_model = model;
return true;
} else {
return false;
}
};
/**
* Get the store that is watched for
* for debugging only
* @private
* @returns the Store
*/
this.getModel = function getModel() {
return _model;
};
/**
* The item renderer defines a dom node that can be duplicated
* It is made available for debugging purpose, don't use it
* @private
*/
this.ItemRenderer = function ItemRenderer($plugins, $rootNode) {
/**
* The node that will be cloned
* @private
*/
var _node = null,
/**
* The object that contains plugins.name and plugins.apply
* @private
*/
_plugins = null,
/**
* The _rootNode where to append the created items
* @private
*/
_rootNode = null,
/**
* The lower boundary
* @private
*/
_start = null,
/**
* The number of item to display
* @private
*/
_nb = null;
/**
* Set the duplicated node
* @private
*/
this.setRenderer = function setRenderer(node) {
_node = node;
return true;
};
/**
* Returns the node that is going to be used for rendering
* @private
* @returns the node that is duplicated
*/
this.getRenderer = function getRenderer() {
return _node;
};
/**
* Sets the rootNode and gets the node to copy
* @private
* @param {HTMLElement|SVGElement} rootNode
* @returns
*/
this.setRootNode = function setRootNode(rootNode) {
var renderer;
if (DomUtils.isAcceptedType(rootNode)) {
_rootNode = rootNode;
renderer = _rootNode.querySelector("*");
this.setRenderer(renderer);
renderer && _rootNode.removeChild(renderer);
return true;
} else {
return false;
}
};
/**
* Gets the rootNode
* @private
* @returns _rootNode
*/
this.getRootNode = function getRootNode() {
return _rootNode;
};
/**
* Set the plugins objet that contains the name and the apply function
* @private
* @param plugins
* @returns true
*/
this.setPlugins = function setPlugins(plugins) {
_plugins = plugins;
return true;
};
/**
* Get the plugins object
* @private
* @returns the plugins object
*/
this.getPlugins = function getPlugins() {
return _plugins;
};
/**
* The nodes created from the items are stored here
* @private
*/
this.items = new Store([]);
/**
* Set the start limit
* @private
* @param {Number} start the value to start rendering the items from
* @returns the value
*/
this.setStart = function setStart(start) {
return _start = parseInt(start, 10);
};
/**
* Get the start value
* @private
* @returns the start value
*/
this.getStart = function getStart() {
return _start;
};
/**
* Set the number of item to display
* @private
* @param {Number/String} nb the number of item to display or "*" for all
* @returns the value
*/
this.setNb = function setNb(nb) {
return _nb = nb == "*" ? nb : parseInt(nb, 10);
};
/**
* Get the number of item to display
* @private
* @returns the value
*/
this.getNb = function getNb() {
return _nb;
};
/**
* Adds a new item and adds it in the items list
* @private
* @param {Number} id the id of the item
* @returns
*/
this.addItem = function addItem(id) {
var node,
next;
if (typeof id == "number" && !this.items.get(id)) {
node = this.create(id);
if (node) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
next = this.getNextItem(id);
next ? _rootNode.insertBefore(node, next) : _rootNode.appendChild(node);
return true;
} else {
return false;
}
} else {
return false;
}
};
/**
* Get the next item in the item store given an id.
* @private
* @param {Number} id the id to start from
* @returns
*/
this.getNextItem = function getNextItem(id) {
return this.items.alter("slice", id+1).filter(function (value) {
if (DomUtils.isAcceptedType(value)) {
return true;
}
})[0];
};
/**
* Remove an item from the dom and the items list
* @private
* @param {Number} id the id of the item to remove
* @returns
*/
this.removeItem = function removeItem(id) {
var item = this.items.get(id);
if (item) {
_rootNode.removeChild(item);
this.items.set(id);
return true;
} else {
return false;
}
};
/**
* create a new node. Actually makes a clone of the initial one
* and adds pluginname_id to each node, then calls plugins.apply to apply all plugins
* @private
* @param id
* @param pluginName
* @returns the associated node
*/
this.create = function create(id) {
if (_model.has(id)) {
var newNode = _node.cloneNode(true),
nodes = DomUtils.getNodes(newNode);
Tools.toArray(nodes).forEach(function (child) {
child.setAttribute("data-" + _plugins.name+"_id", id);
});
this.items.set(id, newNode);
_plugins.apply(newNode);
return newNode;
}
};
/**
* Renders the dom tree, adds nodes that are in the boundaries
* and removes the others
* @private
* @returns true boundaries are set
*/
this.render = function render() {
// If the number of items to render is all (*)
// Then get the number of items
var _tmpNb = _nb == "*" ? _model.getNbItems() : _nb;
// This will store the items to remove
var marked = [];
// Render only if boundaries have been set
if (_nb !== null && _start !== null) {
// Loop through the existing items
this.items.loop(function (value, idx) {
// If an item is out of the boundary
if (idx < _start || idx >= (_start + _tmpNb) || !_model.has(idx)) {
// Mark it
marked.push(idx);
}
}, this);
// Remove the marked item from the highest id to the lowest
// Doing this will avoid the id change during removal
// (removing id 2 will make id 3 becoming 2)
marked.sort(Tools.compareNumbers).reverse().forEach(this.removeItem, this);
// Now that we have removed the old nodes
// Add the missing one
for (var i=_start, l=_tmpNb+_start; i<l; i++) {
this.addItem(i);
}
return true;
} else {
return false;
}
};
this.setPlugins($plugins);
this.setRootNode($rootNode);
};
/**
* Save an itemRenderer according to its id
* @private
* @param {String} id the id of the itemRenderer
* @param {ItemRenderer} itemRenderer an itemRenderer object
*/
this.setItemRenderer = function setItemRenderer(id, itemRenderer) {
id = id || "default";
_itemRenderers[id] = itemRenderer;
};
/**
* Get an itemRenderer
* @private
* @param {String} id the name of the itemRenderer
* @returns the itemRenderer
*/
this.getItemRenderer = function getItemRenderer(id) {
return _itemRenderers[id];
};
/**
* Expands the inner dom nodes of a given dom node, filling it with model's values
* @param {HTMLElement|SVGElement} node the dom node to apply foreach to
*/
this.foreach = function foreach(node, idItemRenderer, start, nb) {
var itemRenderer = new this.ItemRenderer(this.plugins, node);
itemRenderer.setStart(start || 0);
itemRenderer.setNb(nb || "*");
itemRenderer.render();
// Add the newly created item
_model.watch("added", itemRenderer.render, itemRenderer);
// If an item is deleted
_model.watch("deleted", function (idx) {
itemRenderer.render();
// Also remove all observers
this.observers[idx] && this.observers[idx].forEach(function (handler) {
_model.unwatchValue(handler);
}, this);
delete this.observers[idx];
},this);
this.setItemRenderer(idItemRenderer, itemRenderer);
};
/**
* Update the lower boundary of a foreach
* @param {String} id the id of the foreach to update
* @param {Number} start the new value
* @returns true if the foreach exists
*/
this.updateStart = function updateStart(id, start) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.setStart(start);
return true;
} else {
return false;
}
};
/**
* Update the number of item to display in a foreach
* @param {String} id the id of the foreach to update
* @param {Number} nb the number of items to display
* @returns true if the foreach exists
*/
this.updateNb = function updateNb(id, nb) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.setNb(nb);
return true;
} else {
return false;
}
};
/**
* Refresh a foreach after having modified its limits
* @param {String} id the id of the foreach to refresh
* @returns true if the foreach exists
*/
this.refresh = function refresh(id) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.render();
return true;
} else {
return false;
}
};
/**
* Both ways binding between a dom node attributes and the model
* @param {HTMLElement|SVGElement} node the dom node to apply the plugin to
* @param {String} name the name of the property to look for in the model's value
* @returns
*/
this.bind = function bind(node, property, name) {
// Name can be unset if the value of a row is plain text
name = name || "";
// In case of an array-like model the id is the index of the model's item to look for.
// The _id is added by the foreach function
var id = node.getAttribute("data-" + this.plugins.name+"_id"),
// Else, it is the first element of the following
split = name.split("."),
// So the index of the model is either id or the first element of split
modelIdx = id || split.shift(),
// And the name of the property to look for in the value is
prop = id ? name : split.join("."),
// Get the model's value
get = Tools.getNestedProperty(_model.get(modelIdx), prop),
// When calling bind like bind:newBinding,param1, param2... we need to get them
extraParam = Tools.toArray(arguments).slice(3);
// 0 and false are acceptable falsy values
if (get || get === 0 || get === false) {
// If the binding hasn't been overriden
if (!this.execBinding.apply(this,
[node, property, get]
// Extra params are passed to the new binding too
.concat(extraParam))) {
// Execute the default one which is a simple assignation
//node[property] = get;
DomUtils.setAttribute(node, property, get);
}
}
// Only watch for changes (double way data binding) if the binding
// has not been redefined
if (!this.hasBinding(property)) {
node.addEventListener("change", function (event) {
if (_model.has(modelIdx)) {
if (prop) {
_model.update(modelIdx, name, node[property]);
} else {
_model.set(modelIdx, node[property]);
}
}
}, true);
}
// Watch for changes
this.observers[modelIdx] = this.observers[modelIdx] || [];
this.observers[modelIdx].push(_model.watchValue(modelIdx, function (value) {
if (!this.execBinding.apply(this,
[node, property, Tools.getNestedProperty(value, prop)]
// passing extra params too
.concat(extraParam))) {
//node[property] = Tools.getNestedProperty(value, prop);
DomUtils.setAttribute(node, property, Tools.getNestedProperty(value, prop));
}
}, this));
};
/**
* Set the node's value into the model, the name is the model's property
* @private
* @param {HTMLElement|SVGElement} node
* @returns true if the property is added
*/
this.set = function set(node) {
if (DomUtils.isAcceptedType(node) && node.name) {
_model.set(node.name, node.value);
return true;
} else {
return false;
}
};
this.getItemIndex = function getElementId(dom) {
var dataset = DomUtils.getDataset(dom);
if (dataset && typeof dataset[this.plugins.name + "_id"] != "undefined") {
return +dataset[this.plugins.name + "_id"];
} else {
return false;
}
};
/**
* Prevents the submit and set the model with all form's inputs
* @param {HTMLFormElement} form
* @returns true if valid form
*/
this.form = function form(form) {
if (form && form.nodeName == "FORM") {
var that = this;
form.addEventListener("submit", function (event) {
Tools.toArray(form.querySelectorAll("[name]")).forEach(that.set, that);
event.preventDefault();
}, true);
return true;
} else {
return false;
}
};
/**
* Add a new way to handle a binding
* @param {String} name of the binding
* @param {Function} binding the function to handle the binding
* @returns
*/
this.addBinding = function addBinding(name, binding) {
if (name && typeof name == "string" && typeof binding == "function") {
_bindings[name] = binding;
return true;
} else {
return false;
}
};
/**
* Execute a binding
* Only used by the plugin
* @private
* @param {HTMLElement} node the dom node on which to execute the binding
* @param {String} name the name of the binding
* @param {Any type} value the value to pass to the function
* @returns
*/
this.execBinding = function execBinding(node, name) {
if (this.hasBinding(name)) {
_bindings[name].apply(node, Array.prototype.slice.call(arguments, 2));
return true;
} else {
return false;
}
};
/**
* Check if the binding exists
* @private
* @param {String} name the name of the binding
* @returns
*/
this.hasBinding = function hasBinding(name) {
return _bindings.hasOwnProperty(name);
};
/**
* Get a binding
* For debugging only
* @private
* @param {String} name the name of the binding
* @returns
*/
this.getBinding = function getBinding(name) {
return _bindings[name];
};
/**
* Add multiple binding at once
* @param {Object} list the list of bindings to add
* @returns
*/
this.addBindings = function addBindings(list) {
return Tools.loop(list, function (binding, name) {
this.addBinding(name, binding);
}, this);
};
// Inits the model
this.setModel($model);
// Inits bindings
this.addBindings($bindings);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('Event.plugin',["DomUtils"],
/**
* @class
* Event plugin adds events listeners to DOM nodes.
* It can also delegate the event handling to a parent dom node
* @requires Utils
*/
function EventPlugin(Utils) {
/**
* The event plugin constructor.
* ex: new EventPlugin({method: function(){} ...}, false);
* @param {Object} the object that has the event handling methods
* @param {Boolean} $isMobile if the event handler has to map with touch events
*/
return function EventPluginConstructor($parent, $isMobile) {
/**
* The parent callback
* @private
*/
var _parent = null,
/**
* The mapping object.
* @private
*/
_map = {
"mousedown" : "touchstart",
"mouseup" : "touchend",
"mousemove" : "touchmove"
},
/**
* Is touch device.
* @private
*/
_isMobile = !!$isMobile;
/**
* Add mapped event listener (for testing purpose).
* @private
*/
this.addEventListener = function addEventListener(node, event, callback, useCapture) {
node.addEventListener(this.map(event), callback, !!useCapture);
};
/**
* Listen to DOM events.
* @param {Object} node DOM node
* @param {String} name event's name
* @param {String} listener callback's name
* @param {String} useCapture string
*/
this.listen = function listen(node, name, listener, useCapture) {
this.addEventListener(node, name, function(e){
_parent[listener].call(_parent, e, node);
}, !!useCapture);
};
/**
* Delegate the event handling to a parent DOM element
* @param {Object} node DOM node
* @param {String} selector CSS3 selector to the element that listens to the event
* @param {String} name event's name
* @param {String} listener callback's name
* @param {String} useCapture string
*/
this.delegate = function delegate(node, selector, name, listener, useCapture) {
this.addEventListener(node, name, function(event){
if (Utils.matches(node, selector, event.target)) {
_parent[listener].call(_parent, event, node);
}
}, !!useCapture);
};
/**
* Get the parent object.
* @return {Object} the parent object
*/
this.getParent = function getParent() {
return _parent;
};
/**
* Set the parent object.
* The parent object is an object which the functions are called by node listeners.
* @param {Object} the parent object
* @return true if object has been set
*/
this.setParent = function setParent(parent) {
if (parent instanceof Object){
_parent = parent;
return true;
}
return false;
};
/**
* Get event mapping.
* @param {String} event's name
* @return the mapped event's name
*/
this.map = function map(name) {
return _isMobile ? (_map[name] || name) : name;
};
/**
* Set event mapping.
* @param {String} event's name
* @param {String} event's value
* @return true if mapped
*/
this.setMap = function setMap(name, value) {
if (typeof name == "string" &&
typeof value == "string") {
_map[name] = value;
return true;
}
return false;
};
//init
this.setParent($parent);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('LocalStore',["Store", "Tools"],
/**
* @class
* LocalStore is an Emily's Store that can be synchronized with localStorage
* Synchronize the store, reload your page/browser and resynchronize it with the same value
* and it gets restored.
* Only valid JSON data will be stored
*/
function LocalStore(Store, Tools) {
function LocalStoreConstructor() {
/**
* The name of the property in which to store the data
* @private
*/
var _name = null,
/**
* The localStorage
* @private
*/
_localStorage = localStorage,
/**
* Saves the current values in localStorage
* @private
*/
setLocalStorage = function setLocalStorage() {
_localStorage.setItem(_name, this.toJSON());
};
/**
* Override default localStorage with a new one
* @param local$torage the new localStorage
* @returns {Boolean} true if success
* @private
*/
this.setLocalStorage = function setLocalStorage(local$torage) {
if (local$torage && local$torage.setItem instanceof Function) {
_localStorage = local$torage;
return true;
} else {
return false;
}
};
/**
* Get the current localStorage
* @returns localStorage
* @private
*/
this.getLocalStorage = function getLocalStorage() {
return _localStorage;
};
/**
* Synchronize the store with localStorage
* @param {String} name the name in which to save the data
* @returns {Boolean} true if the param is a string
*/
this.sync = function sync(name) {
var json;
if (typeof name == "string") {
_name = name;
json = JSON.parse(_localStorage.getItem(name));
Tools.loop(json, function (value, idx) {
if (!this.has(idx)) {
this.set(idx, value);
}
}, this);
setLocalStorage.call(this);
// Watch for modifications to update localStorage
this.watch("added", setLocalStorage, this);
this.watch("updated", setLocalStorage, this);
this.watch("deleted", setLocalStorage, this);
return true;
} else {
return false;
}
};
}
return function LocalStoreFactory(init) {
LocalStoreConstructor.prototype = new Store(init);
return new LocalStoreConstructor;
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('Plugins',["Tools", "DomUtils"],
/**
* @class
* Plugins is the link between the UI and your plugins.
* You can design your own plugin, declare them in your UI, and call them
* from the template, like :
* <tag data-yourPlugin="method: param"></tag>
* @see Model-Plugin for instance
* @requires Tools
*/
function Plugins(Tools, DomUtils) {
return function PluginsConstructor($plugins) {
/**
* The list of plugins
* @private
*/
var _plugins = {},
/**
* Just a "functionalification" of trim
* for code readability
* @private
*/
trim = function trim(string) {
return string.trim();
},
/**
* Call the plugins methods, passing them the dom node
* A phrase can be :
* <tag data-plugin='method: param, param; method:param...'/>
* the function has to call every method of the plugin
* passing it the node, and the given params
* @private
*/
applyPlugin = function applyPlugin(node, phrase, plugin) {
// Split the methods
phrase.split(";")
.forEach(function (couple) {
// Split the result between method and params
var split = couple.split(":"),
// Trim the name
method = split[0].trim(),
// And the params, if any
params = split[1] ? split[1].split(",").map(trim) : [];
// The first param must be the dom node
params.unshift(node);
if (_plugins[plugin] && _plugins[plugin][method]) {
// Call the method with the following params for instance :
// [node, "param1", "param2" .. ]
_plugins[plugin][method].apply(_plugins[plugin], params);
}
});
};
/**
* Add a plugin
*
* Note that once added, the function adds a "plugins" property to the plugin.
* It's an object that holds a name property, with the registered name of the plugin
* and an apply function, to use on new nodes that the plugin would generate
*
* @param {String} name the name of the data that the plugin should look for
* @param {Object} plugin the plugin that has the functions to execute
* @returns true if plugin successfully added.
*/
this.add = function add(name, plugin) {
var that = this,
propertyName = "plugins";
if (typeof name == "string" && typeof plugin == "object" && plugin) {
_plugins[name] = plugin;
plugin[propertyName] = {
name: name,
apply: function apply() {
return that.apply.apply(that, arguments);
}
};
return true;
} else {
return false;
}
};
/**
* Add multiple plugins at once
* @param {Object} list key is the plugin name and value is the plugin
* @returns true if correct param
*/
this.addAll = function addAll(list) {
return Tools.loop(list, function (plugin, name) {
this.add(name, plugin);
}, this);
};
/**
* Get a previously added plugin
* @param {String} name the name of the plugin
* @returns {Object} the plugin
*/
this.get = function get(name) {
return _plugins[name];
};
/**
* Delete a plugin from the list
* @param {String} name the name of the plugin
* @returns {Boolean} true if success
*/
this.del = function del(name) {
return delete _plugins[name];
};
/**
* Apply the plugins to a NodeList
* @param {HTMLElement|SVGElement} dom the dom nodes on which to apply the plugins
* @returns {Boolean} true if the param is a dom node
*/
this.apply = function apply(dom) {
var nodes;
if (DomUtils.isAcceptedType(dom)) {
nodes = DomUtils.getNodes(dom);
Tools.loop(Tools.toArray(nodes), function (node) {
Tools.loop(DomUtils.getDataset(node), function (phrase, plugin) {
applyPlugin(node, phrase, plugin);
});
});
return dom;
} else {
return false;
}
};
this.addAll($plugins);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('OObject',["StateMachine", "Store", "Plugins", "DomUtils", "Tools"],
/**
* @class
* OObject is a container for dom elements. It will also bind
* the dom to additional plugins like Data binding
* @requires StateMachine
*/
function OObject(StateMachine, Store, Plugins, DomUtils, Tools) {
return function OObjectConstructor(otherStore) {
/**
* This function creates the dom of the UI from its template
* It then queries the dom for data- attributes
* It can't be executed if the template is not set
* @private
*/
var render = function render(UI) {
// The place where the template will be created
// is either the currentPlace where the node is placed
// or a temporary div
var baseNode = _currentPlace || document.createElement("div");
// If the template is set
if (UI.template) {
// In this function, the thisObject is the UI's prototype
// UI is the UI that has OObject as prototype
if (typeof UI.template == "string") {
// Let the browser do the parsing, can't be faster & easier.
baseNode.innerHTML = UI.template.trim();
} else if (DomUtils.isAcceptedType(UI.template)) {
// If it's already an HTML element
baseNode.appendChild(UI.template);
}
// The UI must be placed in a unique dom node
// If not, there can't be multiple UIs placed in the same parentNode
// as it wouldn't be possible to know which node would belong to which UI
// This is probably a DOM limitation.
if (baseNode.childNodes.length > 1) {
throw Error("UI.template should have only one parent node");
} else {
UI.dom = baseNode.childNodes[0];
}
UI.plugins.apply(UI.dom);
} else {
// An explicit message I hope
throw Error("UI.template must be set prior to render");
}
},
/**
* This function appends the dom tree to the given dom node.
* This dom node should be somewhere in the dom of the application
* @private
*/
place = function place(UI, place, beforeNode) {
if (place) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
beforeNode ? place.insertBefore(UI.dom, beforeNode) : place.appendChild(UI.dom);
// Also save the new place, so next renderings
// will be made inside it
_currentPlace = place;
}
},
/**
* Does rendering & placing in one function
* @private
*/
renderNPlace = function renderNPlace(UI, dom) {
render(UI);
place.apply(null, Tools.toArray(arguments));
},
/**
* This stores the current place
* If this is set, this is the place where new templates
* will be appended
* @private
*/
_currentPlace = null,
/**
* The UI's stateMachine.
* Much better than if(stuff) do(stuff) else if (!stuff and stuff but not stouff) do (otherstuff)
* Please open an issue if you want to propose a better one
* @private
*/
_stateMachine = new StateMachine("Init", {
"Init": [["render", render, this, "Rendered"],
["place", renderNPlace, this, "Rendered"]],
"Rendered": [["place", place, this],
["render", render, this]]
});
/**
* The UI's Store
* It has set/get/del/has/watch/unwatch methods
* @see Emily's doc for more info on how it works.
*/
this.model = otherStore instanceof Store ? otherStore : new Store;
/**
* The module that will manage the plugins for this UI
* @see Olives/Plugins' doc for more info on how it works.
*/
this.plugins = new Plugins();
/**
* Describes the template, can either be like "&lt;p&gt;&lt;/p&gt;" or HTMLElements
* @type string or HTMLElement|SVGElement
*/
this.template = null;
/**
* This will hold the dom nodes built from the template.
*/
this.dom = null;
/**
* Place the UI in a given dom node
* @param node the node on which to append the UI
* @param beforeNode the dom before which to append the UI
*/
this.place = function place(node, beforeNode) {
_stateMachine.event("place", this, node, beforeNode);
};
/**
* Renders the template to dom nodes and applies the plugins on it
* It requires the template to be set first
*/
this.render = function render() {
_stateMachine.event("render", this);
};
/**
* Set the UI's template from a DOM element
* @param {HTMLElement|SVGElement} dom the dom element that'll become the template of the UI
* @returns true if dom is an HTMLElement|SVGElement
*/
this.setTemplateFromDom = function setTemplateFromDom(dom) {
if (DomUtils.isAcceptedType(dom)) {
this.template = dom;
return true;
} else {
return false;
}
};
/**
* Transforms dom nodes into a UI.
* It basically does a setTemplateFromDOM, then a place
* It's a helper function
* @param {HTMLElement|SVGElement} node the dom to transform to a UI
* @returns true if dom is an HTMLElement|SVGElement
*/
this.alive = function alive(dom) {
if (DomUtils.isAcceptedType(dom)) {
this.setTemplateFromDom(dom);
this.place(dom.parentNode, dom.nextElementSibling);
return true;
} else {
return false;
}
};
/**
* Get the current dom node where the UI is placed.
* for debugging purpose
* @private
* @return {HTMLElement} node the dom where the UI is placed.
*/
this.getCurrentPlace = function(){
return _currentPlace;
};
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('Place.plugin',["OObject", "Tools"],
/**
* @class
* Place plugin places OObject in the DOM.
* @requires OObject, Tools
*/
function PlacePlugin(OObject, Tools) {
/**
* Intilialize a Place.plugin with a list of OObjects
* @param {Object} $uis a list of OObjects such as:
* {
* "header": new OObject(),
* "list": new OObject()
* }
* @Constructor
*/
return function PlacePluginConstructor($uis) {
/**
* The list of uis currently set in this place plugin
* @private
*/
var _uis = {};
/**
* Attach an OObject to this DOM element
* @param {HTML|SVGElement} node the dom node where to attach the OObject
* @param {String} the name of the OObject to attach
* @throws {NoSuchOObject} an error if there's no OObject for the given name
*/
this.place = function place(node, name) {
if (_uis[name] instanceof OObject) {
_uis[name].place(node);
} else {
throw new Error(name + " is not an OObject UI in place:"+name);
}
};
/**
* Add an OObject that can be attached to a dom element
* @param {String} the name of the OObject to add to the list
* @param {OObject} ui the OObject to add the list
* @returns {Boolean} true if the OObject was added
*/
this.set = function set(name, ui) {
if (typeof name == "string" && ui instanceof OObject) {
_uis[name] = ui;
return true;
} else {
return false;
}
};
/**
* Add multiple dom elements at once
* @param {Object} $uis a list of OObjects such as:
* {
* "header": new OObject(),
* "list": new OObject()
* }
*/
this.setAll = function setAll(uis) {
Tools.loop(uis, function (ui, name) {
this.set(name, ui);
}, this);
};
/**
* Returns an OObject from the list given its name
* @param {String} the name of the OObject to get
* @returns {OObject} OObject for the given name
*/
this.get = function get(name) {
return _uis[name];
};
this.setAll($uis);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define('SocketIOTransport',["Observable", "Tools"],
/**
* @class
* SocketIOTransport allows for client-server eventing.
* It's based on socket.io.
*/
function SocketIOTransport(Observable, Tools) {
/**
* Defines the SocketIOTransport
* @private
* @param {Object} $io socket.io's object
* @returns
*/
return function SocketIOTransportConstructor($socket) {
/**
* @private
* The socket.io's socket
*/
var _socket = null;
/**
* Set the socket created by SocketIO
* @param {Object} socket the socket.io socket
* @returns true if it seems to be a socket.io socket
*/
this.setSocket = function setSocket(socket) {
if (socket && typeof socket.emit == "function") {
_socket = socket;
return true;
} else {
return false;
}
};
/**
* Get the socket, for debugging purpose
* @private
* @returns {Object} the socket
*/
this.getSocket = function getSocket() {
return _socket;
},
/**
* Subscribe to a socket event
* @param {String} event the name of the event
* @param {Function} func the function to execute when the event fires
*/
this.on = function on(event, func) {
return _socket.on(event, func);
},
/**
* Subscribe to a socket event but disconnect as soon as it fires.
* @param {String} event the name of the event
* @param {Function} func the function to execute when the event fires
*/
this.once = function once(event, func) {
return _socket.once(event, func);
};
/**
* Publish an event on the socket
* @param {String} event the event to publish
* @param data
* @param {Function} callback is the function to be called for ack
*/
this.emit = function emit(event, data, callback) {
return _socket.emit(event, data, callback);
};
/**
* Stop listening to events on a channel
* @param {String} event the event to publish
* @param data
* @param {Function} callback is the function to be called for ack
*/
this.removeListener = function removeListener(event, data, callback) {
return _socket.removeListener(event, data, callback);
};
/**
* Make a request on the node server
* @param {String} channel watch the server's documentation to see available channels
* @param data the request data, it could be anything
* @param {Function} func the callback that will get the response.
* @param {Object} scope the scope in which to execute the callback
*/
this.request = function request(channel, data, func, scope) {
if (typeof channel == "string"
&& typeof data != "undefined") {
var reqData = {
eventId: Date.now() + Math.floor(Math.random()*1e6),
data: data
},
boundCallback = function () {
func && func.apply(scope || null, arguments);
};
this.once(reqData.eventId, boundCallback);
this.emit(channel, reqData);
return true;
} else {
return false;
}
};
/**
* Listen to an url and get notified on new data
* @param {String} channel watch the server's documentation to see available channels
* @param data the request data, it could be anything
* @param {Function} func the callback that will get the data
* @param {Object} scope the scope in which to execute the callback
* @returns
*/
this.listen = function listen(channel, data, func, scope) {
if (typeof channel == "string"
&& typeof data != "undefined"
&& typeof func == "function") {
var reqData = {
eventId: Date.now() + Math.floor(Math.random()*1e6),
data: data,
keepAlive: true
},
boundCallback = function () {
func && func.apply(scope || null, arguments);
},
that = this;
this.on(reqData.eventId, boundCallback);
this.emit(channel, reqData);
return function stop() {
that.emit("disconnect-" + reqData.eventId);
that.removeListener(reqData.eventId, boundCallback);
};
} else {
return false;
}
};
/**
* Sets the socket.io
*/
this.setSocket($socket);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["Store", "Observable", "Tools", "DomUtils"],
/**
* @class
* This plugin links dom nodes to a model
* @requires Store, Observable
*/
function BindPlugin(Store, Observable, Tools, DomUtils) {
return function BindPluginConstructor($model, $bindings) {
/**
* The model to watch
* @private
*/
var _model = null,
/**
* The list of custom bindings
* @private
*/
_bindings = {},
/**
* The list of itemRenderers
* each foreach has its itemRenderer
* @private
*/
_itemRenderers = {};
/**
* The observers handlers
* for debugging only
* @private
*/
this.observers = {};
/**
* Define the model to watch for
* @param {Store} model the model to watch for changes
* @returns {Boolean} true if the model was set
*/
this.setModel = function setModel(model) {
if (model instanceof Store) {
// Set the model
_model = model;
return true;
} else {
return false;
}
};
/**
* Get the store that is watched for
* for debugging only
* @private
* @returns the Store
*/
this.getModel = function getModel() {
return _model;
};
/**
* The item renderer defines a dom node that can be duplicated
* It is made available for debugging purpose, don't use it
* @private
*/
this.ItemRenderer = function ItemRenderer($plugins, $rootNode) {
/**
* The node that will be cloned
* @private
*/
var _node = null,
/**
* The object that contains plugins.name and plugins.apply
* @private
*/
_plugins = null,
/**
* The _rootNode where to append the created items
* @private
*/
_rootNode = null,
/**
* The lower boundary
* @private
*/
_start = null,
/**
* The number of item to display
* @private
*/
_nb = null;
/**
* Set the duplicated node
* @private
*/
this.setRenderer = function setRenderer(node) {
_node = node;
return true;
};
/**
* Returns the node that is going to be used for rendering
* @private
* @returns the node that is duplicated
*/
this.getRenderer = function getRenderer() {
return _node;
};
/**
* Sets the rootNode and gets the node to copy
* @private
* @param {HTMLElement|SVGElement} rootNode
* @returns
*/
this.setRootNode = function setRootNode(rootNode) {
var renderer;
if (DomUtils.isAcceptedType(rootNode)) {
_rootNode = rootNode;
renderer = _rootNode.querySelector("*");
this.setRenderer(renderer);
renderer && _rootNode.removeChild(renderer);
return true;
} else {
return false;
}
};
/**
* Gets the rootNode
* @private
* @returns _rootNode
*/
this.getRootNode = function getRootNode() {
return _rootNode;
};
/**
* Set the plugins objet that contains the name and the apply function
* @private
* @param plugins
* @returns true
*/
this.setPlugins = function setPlugins(plugins) {
_plugins = plugins;
return true;
};
/**
* Get the plugins object
* @private
* @returns the plugins object
*/
this.getPlugins = function getPlugins() {
return _plugins;
};
/**
* The nodes created from the items are stored here
* @private
*/
this.items = new Store([]);
/**
* Set the start limit
* @private
* @param {Number} start the value to start rendering the items from
* @returns the value
*/
this.setStart = function setStart(start) {
return _start = parseInt(start, 10);
};
/**
* Get the start value
* @private
* @returns the start value
*/
this.getStart = function getStart() {
return _start;
};
/**
* Set the number of item to display
* @private
* @param {Number/String} nb the number of item to display or "*" for all
* @returns the value
*/
this.setNb = function setNb(nb) {
return _nb = nb == "*" ? nb : parseInt(nb, 10);
};
/**
* Get the number of item to display
* @private
* @returns the value
*/
this.getNb = function getNb() {
return _nb;
};
/**
* Adds a new item and adds it in the items list
* @private
* @param {Number} id the id of the item
* @returns
*/
this.addItem = function addItem(id) {
var node,
next;
if (typeof id == "number" && !this.items.get(id)) {
node = this.create(id);
if (node) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
next = this.getNextItem(id);
next ? _rootNode.insertBefore(node, next) : _rootNode.appendChild(node);
return true;
} else {
return false;
}
} else {
return false;
}
};
/**
* Get the next item in the item store given an id.
* @private
* @param {Number} id the id to start from
* @returns
*/
this.getNextItem = function getNextItem(id) {
return this.items.alter("slice", id+1).filter(function (value) {
if (DomUtils.isAcceptedType(value)) {
return true;
}
})[0];
};
/**
* Remove an item from the dom and the items list
* @private
* @param {Number} id the id of the item to remove
* @returns
*/
this.removeItem = function removeItem(id) {
var item = this.items.get(id);
if (item) {
_rootNode.removeChild(item);
this.items.set(id);
return true;
} else {
return false;
}
};
/**
* create a new node. Actually makes a clone of the initial one
* and adds pluginname_id to each node, then calls plugins.apply to apply all plugins
* @private
* @param id
* @param pluginName
* @returns the associated node
*/
this.create = function create(id) {
if (_model.has(id)) {
var newNode = _node.cloneNode(true),
nodes = DomUtils.getNodes(newNode);
Tools.toArray(nodes).forEach(function (child) {
child.setAttribute("data-" + _plugins.name+"_id", id);
});
this.items.set(id, newNode);
_plugins.apply(newNode);
return newNode;
}
};
/**
* Renders the dom tree, adds nodes that are in the boundaries
* and removes the others
* @private
* @returns true boundaries are set
*/
this.render = function render() {
// If the number of items to render is all (*)
// Then get the number of items
var _tmpNb = _nb == "*" ? _model.getNbItems() : _nb;
// This will store the items to remove
var marked = [];
// Render only if boundaries have been set
if (_nb !== null && _start !== null) {
// Loop through the existing items
this.items.loop(function (value, idx) {
// If an item is out of the boundary
if (idx < _start || idx >= (_start + _tmpNb) || !_model.has(idx)) {
// Mark it
marked.push(idx);
}
}, this);
// Remove the marked item from the highest id to the lowest
// Doing this will avoid the id change during removal
// (removing id 2 will make id 3 becoming 2)
marked.sort(Tools.compareNumbers).reverse().forEach(this.removeItem, this);
// Now that we have removed the old nodes
// Add the missing one
for (var i=_start, l=_tmpNb+_start; i<l; i++) {
this.addItem(i);
}
return true;
} else {
return false;
}
};
this.setPlugins($plugins);
this.setRootNode($rootNode);
};
/**
* Save an itemRenderer according to its id
* @private
* @param {String} id the id of the itemRenderer
* @param {ItemRenderer} itemRenderer an itemRenderer object
*/
this.setItemRenderer = function setItemRenderer(id, itemRenderer) {
id = id || "default";
_itemRenderers[id] = itemRenderer;
};
/**
* Get an itemRenderer
* @private
* @param {String} id the name of the itemRenderer
* @returns the itemRenderer
*/
this.getItemRenderer = function getItemRenderer(id) {
return _itemRenderers[id];
};
/**
* Expands the inner dom nodes of a given dom node, filling it with model's values
* @param {HTMLElement|SVGElement} node the dom node to apply foreach to
*/
this.foreach = function foreach(node, idItemRenderer, start, nb) {
var itemRenderer = new this.ItemRenderer(this.plugins, node);
itemRenderer.setStart(start || 0);
itemRenderer.setNb(nb || "*");
itemRenderer.render();
// Add the newly created item
_model.watch("added", itemRenderer.render, itemRenderer);
// If an item is deleted
_model.watch("deleted", function (idx) {
itemRenderer.render();
// Also remove all observers
this.observers[idx] && this.observers[idx].forEach(function (handler) {
_model.unwatchValue(handler);
}, this);
delete this.observers[idx];
},this);
this.setItemRenderer(idItemRenderer, itemRenderer);
};
/**
* Update the lower boundary of a foreach
* @param {String} id the id of the foreach to update
* @param {Number} start the new value
* @returns true if the foreach exists
*/
this.updateStart = function updateStart(id, start) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.setStart(start);
return true;
} else {
return false;
}
};
/**
* Update the number of item to display in a foreach
* @param {String} id the id of the foreach to update
* @param {Number} nb the number of items to display
* @returns true if the foreach exists
*/
this.updateNb = function updateNb(id, nb) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.setNb(nb);
return true;
} else {
return false;
}
};
/**
* Refresh a foreach after having modified its limits
* @param {String} id the id of the foreach to refresh
* @returns true if the foreach exists
*/
this.refresh = function refresh(id) {
var itemRenderer = this.getItemRenderer(id);
if (itemRenderer) {
itemRenderer.render();
return true;
} else {
return false;
}
};
/**
* Both ways binding between a dom node attributes and the model
* @param {HTMLElement|SVGElement} node the dom node to apply the plugin to
* @param {String} name the name of the property to look for in the model's value
* @returns
*/
this.bind = function bind(node, property, name) {
// Name can be unset if the value of a row is plain text
name = name || "";
// In case of an array-like model the id is the index of the model's item to look for.
// The _id is added by the foreach function
var id = node.getAttribute("data-" + this.plugins.name+"_id"),
// Else, it is the first element of the following
split = name.split("."),
// So the index of the model is either id or the first element of split
modelIdx = id || split.shift(),
// And the name of the property to look for in the value is
prop = id ? name : split.join("."),
// Get the model's value
get = Tools.getNestedProperty(_model.get(modelIdx), prop),
// When calling bind like bind:newBinding,param1, param2... we need to get them
extraParam = Tools.toArray(arguments).slice(3);
// 0 and false are acceptable falsy values
if (get || get === 0 || get === false) {
// If the binding hasn't been overriden
if (!this.execBinding.apply(this,
[node, property, get]
// Extra params are passed to the new binding too
.concat(extraParam))) {
// Execute the default one which is a simple assignation
//node[property] = get;
DomUtils.setAttribute(node, property, get);
}
}
// Only watch for changes (double way data binding) if the binding
// has not been redefined
if (!this.hasBinding(property)) {
node.addEventListener("change", function (event) {
if (_model.has(modelIdx)) {
if (prop) {
_model.update(modelIdx, name, node[property]);
} else {
_model.set(modelIdx, node[property]);
}
}
}, true);
}
// Watch for changes
this.observers[modelIdx] = this.observers[modelIdx] || [];
this.observers[modelIdx].push(_model.watchValue(modelIdx, function (value) {
if (!this.execBinding.apply(this,
[node, property, Tools.getNestedProperty(value, prop)]
// passing extra params too
.concat(extraParam))) {
//node[property] = Tools.getNestedProperty(value, prop);
DomUtils.setAttribute(node, property, Tools.getNestedProperty(value, prop));
}
}, this));
};
/**
* Set the node's value into the model, the name is the model's property
* @private
* @param {HTMLElement|SVGElement} node
* @returns true if the property is added
*/
this.set = function set(node) {
if (DomUtils.isAcceptedType(node) && node.name) {
_model.set(node.name, node.value);
return true;
} else {
return false;
}
};
this.getItemIndex = function getElementId(dom) {
var dataset = DomUtils.getDataset(dom);
if (dataset && typeof dataset[this.plugins.name + "_id"] != "undefined") {
return +dataset[this.plugins.name + "_id"];
} else {
return false;
}
};
/**
* Prevents the submit and set the model with all form's inputs
* @param {HTMLFormElement} form
* @returns true if valid form
*/
this.form = function form(form) {
if (form && form.nodeName == "FORM") {
var that = this;
form.addEventListener("submit", function (event) {
Tools.toArray(form.querySelectorAll("[name]")).forEach(that.set, that);
event.preventDefault();
}, true);
return true;
} else {
return false;
}
};
/**
* Add a new way to handle a binding
* @param {String} name of the binding
* @param {Function} binding the function to handle the binding
* @returns
*/
this.addBinding = function addBinding(name, binding) {
if (name && typeof name == "string" && typeof binding == "function") {
_bindings[name] = binding;
return true;
} else {
return false;
}
};
/**
* Execute a binding
* Only used by the plugin
* @private
* @param {HTMLElement} node the dom node on which to execute the binding
* @param {String} name the name of the binding
* @param {Any type} value the value to pass to the function
* @returns
*/
this.execBinding = function execBinding(node, name) {
if (this.hasBinding(name)) {
_bindings[name].apply(node, Array.prototype.slice.call(arguments, 2));
return true;
} else {
return false;
}
};
/**
* Check if the binding exists
* @private
* @param {String} name the name of the binding
* @returns
*/
this.hasBinding = function hasBinding(name) {
return _bindings.hasOwnProperty(name);
};
/**
* Get a binding
* For debugging only
* @private
* @param {String} name the name of the binding
* @returns
*/
this.getBinding = function getBinding(name) {
return _bindings[name];
};
/**
* Add multiple binding at once
* @param {Object} list the list of bindings to add
* @returns
*/
this.addBindings = function addBindings(list) {
return Tools.loop(list, function (binding, name) {
this.addBinding(name, binding);
}, this);
};
// Inits the model
this.setModel($model);
// Inits bindings
this.addBindings($bindings);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["Tools"], function (Tools) {
return {
/**
* Returns a NodeList including the given dom node,
* its childNodes and its siblingNodes
* @param {HTMLElement|SVGElement} dom the dom node to start with
* @param {String} query an optional CSS selector to narrow down the query
* @returns the list of nodes
*/
getNodes: function getNodes(dom, query) {
if (this.isAcceptedType(dom)) {
if (!dom.parentNode) {
document.createDocumentFragment().appendChild(dom);
}
return dom.parentNode.querySelectorAll(query || "*");
} else {
return false;
}
},
/**
* Get a domNode's dataset attribute. If dataset doesn't exist (IE)
* then the domNode is looped through to collect them.
* @param {HTMLElement|SVGElement} dom
* @returns {Object} dataset
*/
getDataset: function getDataset(dom) {
var i=0,
l,
dataset={},
split,
join;
if (this.isAcceptedType(dom)) {
if (dom.hasOwnProperty("dataset")) {
return dom.dataset;
} else {
for (l=dom.attributes.length;i<l;i++) {
split = dom.attributes[i].name.split("-");
if (split.shift() == "data") {
dataset[join = split.join("-")] = dom.getAttribute("data-"+join);
}
}
return dataset;
}
} else {
return false;
}
},
/**
* Olives can manipulate HTMLElement and SVGElements
* This function tells if an element is one of them
* @param {Element} type
* @returns true if HTMLElement or SVGElement
*/
isAcceptedType: function isAcceptedType(type) {
if (type instanceof HTMLElement ||
type instanceof SVGElement) {
return true;
} else {
return false;
}
},
/**
* Assign a new value to an Element's property. Works with HTMLElement and SVGElement.
* @param {HTMLElement|SVGElement} node the node which property should be changed
* @param {String} property the name of the property
* @param {any} value the value to set
* @returns true if assigned
*/
setAttribute: function setAttribute(node, property, value) {
if (node instanceof HTMLElement) {
node[property] = value;
return true;
} else if (node instanceof SVGElement){
node.setAttribute(property, value);
return true;
} else {
return false;
}
},
/**
* Determine if an element matches a certain CSS selector.
* @param {Element} the parent node
* @param {String} CSS selector
* @param {Element} the node to check out
* @param true if matches
*/
matches : function matches(parent, selector, node){
return Tools.toArray(this.getNodes(parent, selector)).indexOf(node) > -1;
}
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["DomUtils"],
/**
* @class
* Event plugin adds events listeners to DOM nodes.
* It can also delegate the event handling to a parent dom node
* @requires Utils
*/
function EventPlugin(Utils) {
/**
* The event plugin constructor.
* ex: new EventPlugin({method: function(){} ...}, false);
* @param {Object} the object that has the event handling methods
* @param {Boolean} $isMobile if the event handler has to map with touch events
*/
return function EventPluginConstructor($parent, $isMobile) {
/**
* The parent callback
* @private
*/
var _parent = null,
/**
* The mapping object.
* @private
*/
_map = {
"mousedown" : "touchstart",
"mouseup" : "touchend",
"mousemove" : "touchmove"
},
/**
* Is touch device.
* @private
*/
_isMobile = !!$isMobile;
/**
* Add mapped event listener (for testing purpose).
* @private
*/
this.addEventListener = function addEventListener(node, event, callback, useCapture) {
node.addEventListener(this.map(event), callback, !!useCapture);
};
/**
* Listen to DOM events.
* @param {Object} node DOM node
* @param {String} name event's name
* @param {String} listener callback's name
* @param {String} useCapture string
*/
this.listen = function listen(node, name, listener, useCapture) {
this.addEventListener(node, name, function(e){
_parent[listener].call(_parent, e, node);
}, !!useCapture);
};
/**
* Delegate the event handling to a parent DOM element
* @param {Object} node DOM node
* @param {String} selector CSS3 selector to the element that listens to the event
* @param {String} name event's name
* @param {String} listener callback's name
* @param {String} useCapture string
*/
this.delegate = function delegate(node, selector, name, listener, useCapture) {
this.addEventListener(node, name, function(event){
if (Utils.matches(node, selector, event.target)) {
_parent[listener].call(_parent, event, node);
}
}, !!useCapture);
};
/**
* Get the parent object.
* @return {Object} the parent object
*/
this.getParent = function getParent() {
return _parent;
};
/**
* Set the parent object.
* The parent object is an object which the functions are called by node listeners.
* @param {Object} the parent object
* @return true if object has been set
*/
this.setParent = function setParent(parent) {
if (parent instanceof Object){
_parent = parent;
return true;
}
return false;
};
/**
* Get event mapping.
* @param {String} event's name
* @return the mapped event's name
*/
this.map = function map(name) {
return _isMobile ? (_map[name] || name) : name;
};
/**
* Set event mapping.
* @param {String} event's name
* @param {String} event's value
* @return true if mapped
*/
this.setMap = function setMap(name, value) {
if (typeof name == "string" &&
typeof value == "string") {
_map[name] = value;
return true;
}
return false;
};
//init
this.setParent($parent);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["Store", "Tools"],
/**
* @class
* LocalStore is an Emily's Store that can be synchronized with localStorage
* Synchronize the store, reload your page/browser and resynchronize it with the same value
* and it gets restored.
* Only valid JSON data will be stored
*/
function LocalStore(Store, Tools) {
function LocalStoreConstructor() {
/**
* The name of the property in which to store the data
* @private
*/
var _name = null,
/**
* The localStorage
* @private
*/
_localStorage = localStorage,
/**
* Saves the current values in localStorage
* @private
*/
setLocalStorage = function setLocalStorage() {
_localStorage.setItem(_name, this.toJSON());
};
/**
* Override default localStorage with a new one
* @param local$torage the new localStorage
* @returns {Boolean} true if success
* @private
*/
this.setLocalStorage = function setLocalStorage(local$torage) {
if (local$torage && local$torage.setItem instanceof Function) {
_localStorage = local$torage;
return true;
} else {
return false;
}
};
/**
* Get the current localStorage
* @returns localStorage
* @private
*/
this.getLocalStorage = function getLocalStorage() {
return _localStorage;
};
/**
* Synchronize the store with localStorage
* @param {String} name the name in which to save the data
* @returns {Boolean} true if the param is a string
*/
this.sync = function sync(name) {
var json;
if (typeof name == "string") {
_name = name;
json = JSON.parse(_localStorage.getItem(name));
Tools.loop(json, function (value, idx) {
if (!this.has(idx)) {
this.set(idx, value);
}
}, this);
setLocalStorage.call(this);
// Watch for modifications to update localStorage
this.watch("added", setLocalStorage, this);
this.watch("updated", setLocalStorage, this);
this.watch("deleted", setLocalStorage, this);
return true;
} else {
return false;
}
};
}
return function LocalStoreFactory(init) {
LocalStoreConstructor.prototype = new Store(init);
return new LocalStoreConstructor;
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["StateMachine", "Store", "Plugins", "DomUtils", "Tools"],
/**
* @class
* OObject is a container for dom elements. It will also bind
* the dom to additional plugins like Data binding
* @requires StateMachine
*/
function OObject(StateMachine, Store, Plugins, DomUtils, Tools) {
return function OObjectConstructor(otherStore) {
/**
* This function creates the dom of the UI from its template
* It then queries the dom for data- attributes
* It can't be executed if the template is not set
* @private
*/
var render = function render(UI) {
// The place where the template will be created
// is either the currentPlace where the node is placed
// or a temporary div
var baseNode = _currentPlace || document.createElement("div");
// If the template is set
if (UI.template) {
// In this function, the thisObject is the UI's prototype
// UI is the UI that has OObject as prototype
if (typeof UI.template == "string") {
// Let the browser do the parsing, can't be faster & easier.
baseNode.innerHTML = UI.template.trim();
} else if (DomUtils.isAcceptedType(UI.template)) {
// If it's already an HTML element
baseNode.appendChild(UI.template);
}
// The UI must be placed in a unique dom node
// If not, there can't be multiple UIs placed in the same parentNode
// as it wouldn't be possible to know which node would belong to which UI
// This is probably a DOM limitation.
if (baseNode.childNodes.length > 1) {
throw Error("UI.template should have only one parent node");
} else {
UI.dom = baseNode.childNodes[0];
}
UI.plugins.apply(UI.dom);
} else {
// An explicit message I hope
throw Error("UI.template must be set prior to render");
}
},
/**
* This function appends the dom tree to the given dom node.
* This dom node should be somewhere in the dom of the application
* @private
*/
place = function place(UI, place, beforeNode) {
if (place) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
beforeNode ? place.insertBefore(UI.dom, beforeNode) : place.appendChild(UI.dom);
// Also save the new place, so next renderings
// will be made inside it
_currentPlace = place;
}
},
/**
* Does rendering & placing in one function
* @private
*/
renderNPlace = function renderNPlace(UI, dom) {
render(UI);
place.apply(null, Tools.toArray(arguments));
},
/**
* This stores the current place
* If this is set, this is the place where new templates
* will be appended
* @private
*/
_currentPlace = null,
/**
* The UI's stateMachine.
* Much better than if(stuff) do(stuff) else if (!stuff and stuff but not stouff) do (otherstuff)
* Please open an issue if you want to propose a better one
* @private
*/
_stateMachine = new StateMachine("Init", {
"Init": [["render", render, this, "Rendered"],
["place", renderNPlace, this, "Rendered"]],
"Rendered": [["place", place, this],
["render", render, this]]
});
/**
* The UI's Store
* It has set/get/del/has/watch/unwatch methods
* @see Emily's doc for more info on how it works.
*/
this.model = otherStore instanceof Store ? otherStore : new Store;
/**
* The module that will manage the plugins for this UI
* @see Olives/Plugins' doc for more info on how it works.
*/
this.plugins = new Plugins();
/**
* Describes the template, can either be like "&lt;p&gt;&lt;/p&gt;" or HTMLElements
* @type string or HTMLElement|SVGElement
*/
this.template = null;
/**
* This will hold the dom nodes built from the template.
*/
this.dom = null;
/**
* Place the UI in a given dom node
* @param node the node on which to append the UI
* @param beforeNode the dom before which to append the UI
*/
this.place = function place(node, beforeNode) {
_stateMachine.event("place", this, node, beforeNode);
};
/**
* Renders the template to dom nodes and applies the plugins on it
* It requires the template to be set first
*/
this.render = function render() {
_stateMachine.event("render", this);
};
/**
* Set the UI's template from a DOM element
* @param {HTMLElement|SVGElement} dom the dom element that'll become the template of the UI
* @returns true if dom is an HTMLElement|SVGElement
*/
this.setTemplateFromDom = function setTemplateFromDom(dom) {
if (DomUtils.isAcceptedType(dom)) {
this.template = dom;
return true;
} else {
return false;
}
};
/**
* Transforms dom nodes into a UI.
* It basically does a setTemplateFromDOM, then a place
* It's a helper function
* @param {HTMLElement|SVGElement} node the dom to transform to a UI
* @returns true if dom is an HTMLElement|SVGElement
*/
this.alive = function alive(dom) {
if (DomUtils.isAcceptedType(dom)) {
this.setTemplateFromDom(dom);
this.place(dom.parentNode, dom.nextElementSibling);
return true;
} else {
return false;
}
};
/**
* Get the current dom node where the UI is placed.
* for debugging purpose
* @private
* @return {HTMLElement} node the dom where the UI is placed.
*/
this.getCurrentPlace = function(){
return _currentPlace;
};
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["OObject", "Tools"],
/**
* @class
* Place plugin places OObject in the DOM.
* @requires OObject, Tools
*/
function PlacePlugin(OObject, Tools) {
/**
* Intilialize a Place.plugin with a list of OObjects
* @param {Object} $uis a list of OObjects such as:
* {
* "header": new OObject(),
* "list": new OObject()
* }
* @Constructor
*/
return function PlacePluginConstructor($uis) {
/**
* The list of uis currently set in this place plugin
* @private
*/
var _uis = {};
/**
* Attach an OObject to this DOM element
* @param {HTML|SVGElement} node the dom node where to attach the OObject
* @param {String} the name of the OObject to attach
* @throws {NoSuchOObject} an error if there's no OObject for the given name
*/
this.place = function place(node, name) {
if (_uis[name] instanceof OObject) {
_uis[name].place(node);
} else {
throw new Error(name + " is not an OObject UI in place:"+name);
}
};
/**
* Add an OObject that can be attached to a dom element
* @param {String} the name of the OObject to add to the list
* @param {OObject} ui the OObject to add the list
* @returns {Boolean} true if the OObject was added
*/
this.set = function set(name, ui) {
if (typeof name == "string" && ui instanceof OObject) {
_uis[name] = ui;
return true;
} else {
return false;
}
};
/**
* Add multiple dom elements at once
* @param {Object} $uis a list of OObjects such as:
* {
* "header": new OObject(),
* "list": new OObject()
* }
*/
this.setAll = function setAll(uis) {
Tools.loop(uis, function (ui, name) {
this.set(name, ui);
}, this);
};
/**
* Returns an OObject from the list given its name
* @param {String} the name of the OObject to get
* @returns {OObject} OObject for the given name
*/
this.get = function get(name) {
return _uis[name];
};
this.setAll($uis);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["Tools", "DomUtils"],
/**
* @class
* Plugins is the link between the UI and your plugins.
* You can design your own plugin, declare them in your UI, and call them
* from the template, like :
* <tag data-yourPlugin="method: param"></tag>
* @see Model-Plugin for instance
* @requires Tools
*/
function Plugins(Tools, DomUtils) {
return function PluginsConstructor($plugins) {
/**
* The list of plugins
* @private
*/
var _plugins = {},
/**
* Just a "functionalification" of trim
* for code readability
* @private
*/
trim = function trim(string) {
return string.trim();
},
/**
* Call the plugins methods, passing them the dom node
* A phrase can be :
* <tag data-plugin='method: param, param; method:param...'/>
* the function has to call every method of the plugin
* passing it the node, and the given params
* @private
*/
applyPlugin = function applyPlugin(node, phrase, plugin) {
// Split the methods
phrase.split(";")
.forEach(function (couple) {
// Split the result between method and params
var split = couple.split(":"),
// Trim the name
method = split[0].trim(),
// And the params, if any
params = split[1] ? split[1].split(",").map(trim) : [];
// The first param must be the dom node
params.unshift(node);
if (_plugins[plugin] && _plugins[plugin][method]) {
// Call the method with the following params for instance :
// [node, "param1", "param2" .. ]
_plugins[plugin][method].apply(_plugins[plugin], params);
}
});
};
/**
* Add a plugin
*
* Note that once added, the function adds a "plugins" property to the plugin.
* It's an object that holds a name property, with the registered name of the plugin
* and an apply function, to use on new nodes that the plugin would generate
*
* @param {String} name the name of the data that the plugin should look for
* @param {Object} plugin the plugin that has the functions to execute
* @returns true if plugin successfully added.
*/
this.add = function add(name, plugin) {
var that = this,
propertyName = "plugins";
if (typeof name == "string" && typeof plugin == "object" && plugin) {
_plugins[name] = plugin;
plugin[propertyName] = {
name: name,
apply: function apply() {
return that.apply.apply(that, arguments);
}
};
return true;
} else {
return false;
}
};
/**
* Add multiple plugins at once
* @param {Object} list key is the plugin name and value is the plugin
* @returns true if correct param
*/
this.addAll = function addAll(list) {
return Tools.loop(list, function (plugin, name) {
this.add(name, plugin);
}, this);
};
/**
* Get a previously added plugin
* @param {String} name the name of the plugin
* @returns {Object} the plugin
*/
this.get = function get(name) {
return _plugins[name];
};
/**
* Delete a plugin from the list
* @param {String} name the name of the plugin
* @returns {Boolean} true if success
*/
this.del = function del(name) {
return delete _plugins[name];
};
/**
* Apply the plugins to a NodeList
* @param {HTMLElement|SVGElement} dom the dom nodes on which to apply the plugins
* @returns {Boolean} true if the param is a dom node
*/
this.apply = function apply(dom) {
var nodes;
if (DomUtils.isAcceptedType(dom)) {
nodes = DomUtils.getNodes(dom);
Tools.loop(Tools.toArray(nodes), function (node) {
Tools.loop(DomUtils.getDataset(node), function (phrase, plugin) {
applyPlugin(node, phrase, plugin);
});
});
return dom;
} else {
return false;
}
};
this.addAll($plugins);
};
});
/**
* Olives http://flams.github.com/olives
* The MIT License (MIT)
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define(["Observable", "Tools"],
/**
* @class
* SocketIOTransport allows for client-server eventing.
* It's based on socket.io.
*/
function SocketIOTransport(Observable, Tools) {
/**
* Defines the SocketIOTransport
* @private
* @param {Object} $io socket.io's object
* @returns
*/
return function SocketIOTransportConstructor($socket) {
/**
* @private
* The socket.io's socket
*/
var _socket = null;
/**
* Set the socket created by SocketIO
* @param {Object} socket the socket.io socket
* @returns true if it seems to be a socket.io socket
*/
this.setSocket = function setSocket(socket) {
if (socket && typeof socket.emit == "function") {
_socket = socket;
return true;
} else {
return false;
}
};
/**
* Get the socket, for debugging purpose
* @private
* @returns {Object} the socket
*/
this.getSocket = function getSocket() {
return _socket;
},
/**
* Subscribe to a socket event
* @param {String} event the name of the event
* @param {Function} func the function to execute when the event fires
*/
this.on = function on(event, func) {
return _socket.on(event, func);
},
/**
* Subscribe to a socket event but disconnect as soon as it fires.
* @param {String} event the name of the event
* @param {Function} func the function to execute when the event fires
*/
this.once = function once(event, func) {
return _socket.once(event, func);
};
/**
* Publish an event on the socket
* @param {String} event the event to publish
* @param data
* @param {Function} callback is the function to be called for ack
*/
this.emit = function emit(event, data, callback) {
return _socket.emit(event, data, callback);
};
/**
* Stop listening to events on a channel
* @param {String} event the event to publish
* @param data
* @param {Function} callback is the function to be called for ack
*/
this.removeListener = function removeListener(event, data, callback) {
return _socket.removeListener(event, data, callback);
};
/**
* Make a request on the node server
* @param {String} channel watch the server's documentation to see available channels
* @param data the request data, it could be anything
* @param {Function} func the callback that will get the response.
* @param {Object} scope the scope in which to execute the callback
*/
this.request = function request(channel, data, func, scope) {
if (typeof channel == "string"
&& typeof data != "undefined") {
var reqData = {
eventId: Date.now() + Math.floor(Math.random()*1e6),
data: data
},
boundCallback = function () {
func && func.apply(scope || null, arguments);
};
this.once(reqData.eventId, boundCallback);
this.emit(channel, reqData);
return true;
} else {
return false;
}
};
/**
* Listen to an url and get notified on new data
* @param {String} channel watch the server's documentation to see available channels
* @param data the request data, it could be anything
* @param {Function} func the callback that will get the data
* @param {Object} scope the scope in which to execute the callback
* @returns
*/
this.listen = function listen(channel, data, func, scope) {
if (typeof channel == "string"
&& typeof data != "undefined"
&& typeof func == "function") {
var reqData = {
eventId: Date.now() + Math.floor(Math.random()*1e6),
data: data,
keepAlive: true
},
boundCallback = function () {
func && func.apply(scope || null, arguments);
},
that = this;
this.on(reqData.eventId, boundCallback);
this.emit(channel, reqData);
return function stop() {
that.emit("disconnect-" + reqData.eventId);
that.removeListener(reqData.eventId, boundCallback);
};
} else {
return false;
}
};
/**
* Sets the socket.io
*/
this.setSocket($socket);
};
});
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
//Not using strict: uneven strict support in browsers, #392, and causes
//problems with requirejs.exec()/transpiler plugins that may not be strict.
/*jslint regexp: true, nomen: true, sloppy: true */
/*global window, navigator, document, importScripts, setTimeout, opera */
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.5',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
ap = Array.prototype,
apsp = ap.splice,
isBrowser = !!(typeof window !== 'undefined' && navigator && document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value !== 'string') {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
//Allow getting a global that expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite and existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i += 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts,
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
if (getOwn(config.pkgs, baseName)) {
//If the baseName is a package name, then just treat it as one
//name to concat the name with.
normalizedBaseParts = baseParts = [baseName];
} else {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
}
name = normalizedBaseParts.concat(name.split('/'));
trimDots(name);
//Some use of packages may use a . path to reference the
//'main' module name, so normalize for that.
pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
name = name.join('/');
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName;
}
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
foundStarMap = getOwn(starMap, nameSegment);
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = getOwn(config.paths, id);
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
removeScript(id);
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
context.require([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
nameParts = splitPrefix(name);
prefix = nameParts[0];
name = nameParts[1];
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = getOwn(defined, prefix);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
normalizedName = normalize(name, parentName, applyMap);
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
getModule(depMap).on(name, fn);
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length - 1, 0].concat(globalDefQueue));
globalDefQueue = [];
}
}
handlers = {
'require': function (mod) {
if (mod.require) {
return mod.require;
} else {
return (mod.require = context.makeRequire(mod.map));
}
},
'exports': function (mod) {
mod.usingExports = true;
if (mod.map.isDefine) {
if (mod.exports) {
return mod.exports;
} else {
return (mod.exports = defined[mod.map.id] = {});
}
}
},
'module': function (mod) {
if (mod.module) {
return mod.module;
} else {
return (mod.module = {
id: mod.map.id,
uri: mod.map.url,
config: function () {
return (config.config && getOwn(config.config, mod.map.id)) || {};
},
exports: defined[mod.map.id]
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
delete registry[id];
delete enabledRegistry[id];
}
function breakCycle(mod, traced, processed) {
var id = mod.map.id;
if (mod.error) {
mod.emit('error', mod.error);
} else {
traced[id] = true;
each(mod.depMaps, function (depMap, i) {
var depId = depMap.id,
dep = getOwn(registry, depId);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var map, modId, err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
map = mod.map;
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
this.fetch();
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error.
if (this.events.error) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
if (this.map.isDefine) {
//If setting exports via 'module' is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
cjsModule = this.module;
if (cjsModule &&
cjsModule.exports !== undefined &&
//Make sure it is not already the exports value
cjsModule.exports !== this.exports) {
exports = cjsModule.exports;
} else if (exports === undefined && this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = [this.map.id];
err.requireType = 'define';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
req.onResourceLoad(context, this.map, this.depMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap);
on(normalizedMap,
'defined', bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', this.errback);
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
eachProp(this.pluginMaps, bind(this, function (pluginMap) {
var mod = getOwn(registry, pluginMap.id);
if (mod && !mod.enabled) {
context.enable(pluginMap, this);
}
}));
this.enabling = false;
this.check();
},
on: function (name, cb) {
var cbs = this.events[name];
if (!cbs) {
cbs = this.events[name] = [];
}
cbs.push(cb);
},
emit: function (name, evt) {
each(this.events[name], function (cb) {
cb(evt);
});
if (name === 'error') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
//Save off the paths and packages since they require special processing,
//they are additive.
var pkgs = config.pkgs,
shim = config.shim,
objs = {
paths: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (prop === 'map') {
if (!config.map) {
config.map = {};
}
mixin(config[prop], value, true, true);
} else {
mixin(config[prop], value, true);
}
} else {
config[prop] = value;
}
});
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
location = pkgObj.location;
//Create a brand new object on pkgs, since currentPackages can
//be passed in again, and config.pkgs is the internal transformed
//state for all package configs.
pkgs[pkgObj.name] = {
name: pkgObj.name,
location: location || pkgObj.name,
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//envs have different conventions: some use a module name,
//some use a file name.
main: (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '')
};
});
//Done with modifications, assing packages back to context config
config.pkgs = pkgs;
}
//If there are any "waiting to execute" modules in the registry,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
},
makeShimExports: function (value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
},
makeRequire: function (relMap, options) {
options = options || {};
function localRequire(deps, callback, errback) {
var id, map, requireMod;
if (options.enableBuildCallback && callback && isFunction(callback)) {
callback.__requireJsBuild = true;
}
if (typeof deps === 'string') {
if (isFunction(callback)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
map = makeModuleMap(deps, relMap, false, true);
id = map.id;
if (!hasProp(defined, id)) {
return onError(makeError('notloaded', 'Module name "' +
id +
'" has not been loaded yet for context: ' +
contextName +
(relMap ? '' : '. Use require([])')));
}
return defined[id];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
if (index !== -1 && (!isRelative || index > 1)) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(normalize(moduleNamePlusExt,
relMap && relMap.id, true), ext, true);
},
defined: function (id) {
return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
},
specified: function (id) {
id = makeModuleMap(id, relMap, false, true).id;
return hasProp(defined, id) || hasProp(registry, id);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overriden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var found, args, mod,
shim = getOwn(config.shim, moduleName) || {},
shExports = shim.exports;
takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
//If already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
mod = getOwn(registry, moduleName);
if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
if (hasPathFallback(moduleName)) {
return;
} else {
return onError(makeError('nodefine',
'No define call for ' + moduleName,
null,
[moduleName]));
}
} else {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
parentPath;
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
pkgs = config.pkgs;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
pkg = getOwn(pkgs, parentModule);
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
} else if (pkg) {
//If module name is just the package name, then looking
//for the main module.
if (moduleName === pkg.name) {
pkgPath = pkg.location + '/' + pkg.main;
} else {
pkgPath = pkg.location;
}
syms.splice(0, i, pkgPath);
break;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callack function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
return onError(makeError('scripterror', 'Script error', evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = function (err) {
throw err;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation that a build has been done so that
//only one script needs to be loaded anyway. This may need to be
//reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = dataMain.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
dataMain = mainScript;
}
//Strip off any trailing .js since dataMain is now
//like a module name.
dataMain = dataMain.replace(jsSuffixRegExp, '');
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = [];
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps.length && isFunction(callback)) {
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this));
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
color: inherit;
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #eaeaea url('bg.png');
color: #4d4d4d;
width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
border: 1px solid #ccc;
position: relative;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
#todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
width: 2px;
position: absolute;
top: 0;
left: 40px;
height: 100%;
}
#todoapp input::-webkit-input-placeholder {
font-style: italic;
}
#todoapp input:-moz-placeholder {
font-style: italic;
color: #a9a9a9;
}
#todoapp h1 {
position: absolute;
top: -120px;
width: 100%;
font-size: 70px;
font-weight: bold;
text-align: center;
color: #b3b3b3;
color: rgba(255, 255, 255, 0.3);
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
#header {
padding-top: 15px;
border-radius: inherit;
}
#header:before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
height: 15px;
z-index: 2;
border-bottom: 1px solid #6c615c;
background: #8d7d77;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
#new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
z-index: 2;
box-shadow: none;
}
#main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
}
label[for='toggle-all'] {
display: none;
}
#toggle-all {
position: absolute;
top: -42px;
left: -4px;
width: 40px;
text-align: center;
border: none; /* Mobile Safari */
}
#toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
}
#toggle-all:checked:before {
color: #737373;
}
#todo-list {
margin: 0;
padding: 0;
list-style: none;
}
#todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
}
#todo-list li:last-child {
border-bottom: none;
}
#todo-list li.editing {
border-bottom: none;
padding: 0;
}
#todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
#todo-list li.editing .view {
display: none;
}
#todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
#todo-list li .toggle:after {
content: '✔';
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;
color: #d9d9d9;
text-shadow: 0 -1px 0 #bfbfbf;
}
#todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
}
#todo-list li label {
word-break: break-word;
padding: 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
-webkit-transition: color 0.4s;
-moz-transition: color 0.4s;
-ms-transition: color 0.4s;
-o-transition: color 0.4s;
transition: color 0.4s;
}
#todo-list li.completed label {
color: #a9a9a9;
text-decoration: line-through;
}
#todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 22px;
color: #a88a8a;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
#todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
-moz-transform: scale(1.3);
-ms-transform: scale(1.3);
-o-transform: scale(1.3);
transform: scale(1.3);
}
#todo-list li .destroy:after {
content: '✖';
}
#todo-list li:hover .destroy {
display: block;
}
#todo-list li .edit {
display: none;
}
#todo-list li.editing:last-child {
margin-bottom: -1px;
}
#footer {
color: #777;
padding: 0 15px;
position: absolute;
right: 0;
bottom: -31px;
left: 0;
height: 20px;
z-index: 1;
text-align: center;
}
#footer:before {
content: '';
position: absolute;
right: 0;
bottom: 31px;
left: 0;
height: 50px;
z-index: -1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
0 6px 0 -3px rgba(255, 255, 255, 0.8),
0 7px 1px -3px rgba(0, 0, 0, 0.3),
0 43px 0 -6px rgba(255, 255, 255, 0.8),
0 44px 2px -6px rgba(0, 0, 0, 0.2);
}
#todo-count {
float: left;
text-align: left;
}
#filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
#filters li {
display: inline;
}
#filters li a {
color: #83756f;
margin: 2px;
text-decoration: none;
}
#filters li a.selected {
font-weight: bold;
}
#clear-completed {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
font-size: 11px;
padding: 0 10px;
border-radius: 3px;
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
}
#clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
}
#info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
text-align: center;
}
#info a {
color: inherit;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
#toggle-all,
#todo-list li .toggle {
background: none;
}
#todo-list li .toggle {
height: 40px;
}
#toggle-all {
top: -56px;
left: -15px;
width: 65px;
height: 41px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
.hidden{
display:none;
}
(function () {
'use strict';
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
function getSourcePath() {
// If accessed via addyosmani.github.com/todomvc/, strip the project
// path.
if (location.hostname.indexOf('github.com') > 0) {
return location.pathname.replace(/todomvc\//, '');
}
return location.pathname;
}
function appendSourceLink() {
var sourceLink = document.createElement('a');
var paragraph = document.createElement('p');
var footer = document.getElementById('info');
var urlBase = 'https://github.com/addyosmani/todomvc/tree/gh-pages';
if (footer) {
sourceLink.href = urlBase + getSourcePath();
sourceLink.appendChild(document.createTextNode('Check out the source'));
paragraph.appendChild(sourceLink);
footer.appendChild(paragraph);
}
}
function redirect() {
if (location.hostname === 'addyosmani.github.com') {
location.href = location.href.replace('addyosmani.github.com/todomvc',
'todomvc.com');
}
}
appendSourceLink();
redirect();
})();
...@@ -4,11 +4,8 @@ ...@@ -4,11 +4,8 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Olives • TodoMVC</title> <title>Olives • TodoMVC</title>
<link rel="stylesheet" href="../../../assets/base.css"> <link rel="stylesheet" href="components/todomvc-common/base.css">
<link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/app.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head> </head>
<body> <body>
<section id="todoapp"> <section id="todoapp">
...@@ -42,10 +39,10 @@ ...@@ -42,10 +39,10 @@
<p>Created by <a href="http://github.com/podefr">Olivier Scherrer</a></p> <p>Created by <a href="http://github.com/podefr">Olivier Scherrer</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer> </footer>
<script src="../../../assets/base.js"></script> <script src="components/todomvc-common/base.js"></script>
<script src="js/lib/require.js"></script> <script src="components/requirejs/require.js"></script>
<script src="js/lib/Emily.js"></script> <script src="components/emily/build/Emily.js"></script>
<script src="js/lib/Olives.js"></script> <script src="components/olives/build/Olives.js"></script>
<script src="js/lib/Tools.js"></script> <script src="js/lib/Tools.js"></script>
<script src="js/uis/Input.js"></script> <script src="js/uis/Input.js"></script>
<script src="js/uis/List.js"></script> <script src="js/uis/List.js"></script>
......
/*jshint newcap:false*/
/*global require*/ /*global require*/
(function () { (function () {
'use strict'; 'use strict';
// These are the UIs that compose the Todo application // These are the UIs that compose the Todo application
require(['Todos/Input', 'Todos/List', 'Todos/Controls', 'Olives/LocalStore', 'Store'], require([
'Todos/Input',
'Todos/List',
'Todos/Controls',
'components/olives/src/LocalStore',
'Store'
],
// The application // The application
function Todos(Input, List, Controls, LocalStore, Store) { function Todos(Input, List, Controls, LocalStore, Store) {
...@@ -13,10 +17,10 @@ ...@@ -13,10 +17,10 @@
// so tasks are indexed by a number // so tasks are indexed by a number
// This store is shared among several UIs of this application // This store is shared among several UIs of this application
// that's why it's created here // that's why it's created here
var tasks = new LocalStore([]), var tasks = new LocalStore([]);
// Also create a shared stats store // Also create a shared stats store
stats = new Store({ var stats = new Store({
nbItems: 0, nbItems: 0,
nbLeft: 0, nbLeft: 0,
nbCompleted: 0, nbCompleted: 0,
...@@ -34,7 +38,5 @@ ...@@ -34,7 +38,5 @@
// Same goes for the control UI // Same goes for the control UI
Controls(document.querySelector('#footer'), tasks, stats); Controls(document.querySelector('#footer'), tasks, stats);
}); });
})();
}());
/*
Emily
The MIT License (MIT)
Copyright (c) 2012 Olivier Scherrer <pode.fr@gmail.com>
*/
define("CouchDBStore",["Store","StateMachine","Tools","Promise"],function(b,e,h,f){function c(){var c=null,a={},d=new f,b={getView:function(){a.query=a.query||{};a.query.update_seq=true;c.request("CouchDB",{method:"GET",path:"/"+a.database+"/_design/"+a.design+"/_view/"+a.view,query:a.query},function(d){var b=JSON.parse(d);if(b.rows)this.reset(b.rows),i.event("subscribeToViewChanges",b.update_seq);else throw Error("CouchDBStore ["+a.database+", "+a.design+", "+a.view+"].sync() failed: "+d);},this)},
getDocument:function(){c.request("CouchDB",{method:"GET",path:"/"+a.database+"/"+a.document,query:a.query},function(a){a=JSON.parse(a);a._id?(this.reset(a),i.event("subscribeToDocumentChanges")):d.reject(this)},this)},getBulkDocuments:function(){var d={path:"/"+a.database+"/_all_docs",query:a.query},b;a.keys instanceof Array?(d.method="POST",d.data=JSON.stringify({keys:a.keys}),d.headers={"Content-Type":"application/json"},b=d.data):(d.method="GET",b=JSON.stringify(a.query));a.query.include_docs=
true;a.query.update_seq=true;c.request("CouchDB",d,function(d){var c=JSON.parse(d);if(c.rows)this.reset(c.rows),i.event("subscribeToBulkChanges",c.update_seq);else throw Error('CouchDBStore.sync("'+a.database+'", '+b+") failed: "+d);},this)},createDocument:function(d){c.request("CouchDB",{method:"PUT",path:"/"+a.database+"/"+a.document,headers:{"Content-Type":"application/json"},data:this.toJSON()},function(a){a=JSON.parse(a);a.ok?(d.resolve(a),i.event("subscribeToDocumentChanges")):d.reject(a)})},
subscribeToViewChanges:function(d){h.mixin({feed:"continuous",heartbeat:2E4,since:d},a.query);this.stopListening=c.listen("CouchDB",{path:"/"+a.database+"/_changes",query:a.query},function(a){if(a=="\n")return false;var a=JSON.parse(a),d;d=a.deleted?"delete":a.changes[0].rev.search("1-")==0?"add":"change";i.event(d,a.id)},this)},subscribeToDocumentChanges:function(){this.stopListening=c.listen("CouchDB",{path:"/"+a.database+"/_changes",query:{feed:"continuous",heartbeat:2E4}},function(d){if(d=="\n")return false;
d=JSON.parse(d);d.id==a.document&&d.changes.pop().rev!=this.get("_rev")&&(d.deleted?i.event("deleteDoc"):i.event("updateDoc"))},this)},subscribeToBulkChanges:function(d){h.mixin({feed:"continuous",heartbeat:2E4,since:d,include_docs:true},a.query);this.stopListening=c.listen("CouchDB",{path:"/"+a.database+"/_changes",query:a.query},function(a){if(a=="\n")return false;var a=JSON.parse(a),d;d=a.changes[0].rev.search("1-")==0?"bulkAdd":a.deleted?"delete":"bulkChange";i.event(d,a.id,a.doc)},this)},updateDocInStore:function(d){c.request("CouchDB",
{method:"GET",path:"/"+a.database+"/_design/"+a.design+"/_view/"+a.view,query:a.query},function(a){JSON.parse(a).rows.some(function(a,b){a.id==d&&this.set(b,a)},this)},this)},addBulkDocInStore:function(d){if(a.query.startkey||a.query.endkey)a.query.include_docs=true,a.query.update_seq=true,c.request("CouchDB",{method:"GET",path:"/"+a.database+"/_all_docs",query:a.query},function(a){JSON.parse(a).rows.forEach(function(a,b){a.id==d&&this.alter("splice",b,0,a.doc)},this)},this);else return false},updateBulkDocInStore:function(a,
d){this.loop(function(b,c){b.id==a&&this.set(c,d)},this)},removeDocInStore:function(a){this.loop(function(d,b){d.id==a&&this.del(b)},this)},addDocInStore:function(d){c.request("CouchDB",{method:"GET",path:"/"+a.database+"/_design/"+a.design+"/_view/"+a.view,query:a.query},function(a){JSON.parse(a).rows.some(function(a,b){a.id==d&&this.alter("splice",b,0,a)},this)},this)},updateDoc:function(){c.request("CouchDB",{method:"GET",path:"/"+a.database+"/"+a.document},function(a){this.reset(JSON.parse(a))},
this)},deleteDoc:function(){this.reset({})},updateDatabase:function(d){c.request("CouchDB",{method:"PUT",path:"/"+a.database+"/"+a.document,headers:{"Content-Type":"application/json"},data:this.toJSON()},function(a){a=JSON.parse(a);a.ok?d.resolve(a):d.reject(a)})},updateDatabaseWithBulkDoc:function(d){var b=[];this.loop(function(a){b.push(a.doc)});c.request("CouchDB",{method:"POST",path:"/"+a.database+"/_bulk_docs",headers:{"Content-Type":"application/json"},data:JSON.stringify({docs:b})},function(a){d.resolve(JSON.parse(a))})},
removeFromDatabase:function(){c.request("CouchDB",{method:"DELETE",path:"/"+a.database+"/"+a.document,query:{rev:this.get("_rev")}})},resolve:function(){d.resolve(this)},unsync:function(){this.stopListening();delete this.stopListening}},i=new e("Unsynched",{Unsynched:[["getView",b.getView,this,"Synched"],["getDocument",b.getDocument,this,"Synched"],["getBulkDocuments",b.getBulkDocuments,this,"Synched"]],Synched:[["updateDatabase",b.createDocument,this],["subscribeToViewChanges",b.subscribeToViewChanges,
this,"Listening"],["subscribeToDocumentChanges",b.subscribeToDocumentChanges,this,"Listening"],["subscribeToBulkChanges",b.subscribeToBulkChanges,this,"Listening"],["unsync",function(){},"Unsynched"]],Listening:[["entry",b.resolve,this],["change",b.updateDocInStore,this],["bulkAdd",b.addBulkDocInStore,this],["bulkChange",b.updateBulkDocInStore,this],["delete",b.removeDocInStore,this],["add",b.addDocInStore,this],["updateDoc",b.updateDoc,this],["deleteDoc",b.deleteDoc,this],["updateDatabase",b.updateDatabase,
this],["updateDatabaseWithBulkDoc",b.updateDatabaseWithBulkDoc,this],["removeFromDatabase",b.removeFromDatabase,this],["unsync",b.unsync,this,"Unsynched"]]});this.sync=function(a,b,c,f){if(typeof a=="string"&&typeof b=="string"&&typeof c=="string")return this.setSyncInfo(a,b,c,f),i.event("getView"),d;else if(typeof a=="string"&&typeof b=="string"&&typeof c!="string")return this.setSyncInfo(a,b,c),i.event("getDocument"),d;else if(typeof a=="string"&&b instanceof Object)return this.setSyncInfo(a,b),
i.event("getBulkDocuments"),d;return false};this.setSyncInfo=function(d,b,c,f){if(typeof d=="string"&&typeof b=="string"&&typeof c=="string")return a.database=d,a.design=b,a.view=c,a.query=f,true;else if(typeof d=="string"&&typeof b=="string"&&typeof c!="string")return a.database=d,a.document=b,a.query=c,true;else if(typeof d=="string"&&b instanceof Object){a.database=d;a.query=b;if(a.query.keys instanceof Array)a.keys=a.query.keys,delete a.query.keys;return true}return false};this.getSyncInfo=function(){return a};
this.unsync=function(){return i.event("unsync")};this.upload=function(){var d=new f;if(a.document)return i.event("updateDatabase",d),d;else if(!a.view)return i.event("updateDatabaseWithBulkDoc",d),d;return false};this.remove=function(){return a.document?i.event("removeFromDatabase"):false};this.setTransport=function(a){return a&&typeof a.listen=="function"&&typeof a.request=="function"?(c=a,true):false};this.getStateMachine=function(){return i};this.getTransport=function(){return c};this.actions=
b}return function(){c.prototype=new b;return new c}});
define("Observable",["Tools"],function(b){return function(){var e={};this.watch=function(b,f,c){if(typeof f=="function"){var g=e[b]=e[b]||[];observer=[f,c];g.push(observer);return[b,g.indexOf(observer)]}else return false};this.unwatch=function(b){var f=b[0],b=b[1];return e[f]&&e[f][b]?(delete e[f][b],e[f].some(function(b){return!!b})||delete e[f],true):false};this.notify=function(h){var f=e[h],c;if(f){for(c=f.length;c--;)f[c]&&f[c][0].apply(f[c][1]||null,b.toArray(arguments).slice(1));return true}else return false};
this.hasObserver=function(b){return!(!b||!e[b[0]]||!e[b[0]][b[1]])};this.hasTopic=function(b){return!!e[b]};this.unwatchAll=function(b){e[b]?delete e[b]:e={};return true}}});
define("Promise",["Observable","StateMachine"],function(b,e){return function(){var h,f,c=new e("Unresolved",{Unresolved:[["resolve",function(a){h=a;g.notify("success",a)},"Resolved"],["reject",function(a){f=a;g.notify("fail",a)},"Rejected"],["addSuccess",function(a,d){g.watch("success",a,d)}],["addFail",function(a,d){g.watch("fail",a,d)}]],Resolved:[["addSuccess",function(a,d){a.call(d,h)}]],Rejected:[["addFail",function(a,d){a.call(d,f)}]]}),g=new b;this.resolve=function(a){return c.event("resolve",
a)};this.reject=function(a){return c.event("reject",a)};this.then=function(a,d,b,f){a instanceof Function&&(d instanceof Function?c.event("addSuccess",a):c.event("addSuccess",a,d));d instanceof Function&&c.event("addFail",d,b);b instanceof Function&&c.event("addFail",b,f);return this};this.getObservable=function(){return g};this.getStateMachine=function(){return c}}});
define("StateMachine",["Tools"],function(b){function e(){var e={};this.add=function(b,c,g,a){var d=[];if(e[b])return false;return typeof b=="string"&&typeof c=="function"?(d[0]=c,typeof g=="object"&&(d[1]=g),typeof g=="string"&&(d[2]=g),typeof a=="string"&&(d[2]=a),e[b]=d,true):false};this.has=function(b){return!!e[b]};this.get=function(b){return e[b]||false};this.event=function c(c){var g=e[c];return g?(g[0].apply(g[1],b.toArray(arguments).slice(1)),g[2]):false}}return function(h,f){var c={},g="";
this.init=function(a){return c[a]?(g=a,true):false};this.add=function(a){return c[a]?false:c[a]=new e};this.get=function(a){return c[a]};this.getCurrent=function(){return g};this.event=function(a){var d;d=c[g].event.apply(c[g].event,b.toArray(arguments));return d===false?false:(d&&(c[g].event("exit"),g=d,c[g].event("entry")),true)};b.loop(f,function(a,b){var c=this.add(b);a.forEach(function(a){c.add.apply(null,a)})},this);this.init(h)}});
define("Store",["Observable","Tools"],function(b,e){return function(h){var f=e.clone(h)||{},c=new b,g=new b,a=function(a){var b=e.objectsDiffs(a,f);["updated","deleted","added"].forEach(function(a){b[a].forEach(function(b){c.notify(a,b,f[b]);g.notify(b,f[b],a)})})};this.getNbItems=function(){return f instanceof Array?f.length:e.count(f)};this.get=function(a){return f[a]};this.has=function(a){return f.hasOwnProperty(a)};this.set=function(a,b){var e;return typeof a!="undefined"?(e=this.has(a),f[a]=
b,e=e?"updated":"added",c.notify(e,a,f[a]),g.notify(a,f[a],e),true):false};this.update=function(a,b,f){var h;return this.has(a)?(h=this.get(a),e.setNestedProperty(h,b,f),c.notify("updated",b,f),g.notify(a,h,"updated"),true):false};this.del=function(a){return this.has(a)?(this.alter("splice",a,1)||(delete f[a],c.notify("deleted",a),g.notify(a,f[a],"deleted")),true):false};this.delAll=function(a){return a instanceof Array?(a.sort(e.compareNumbers).reverse().forEach(this.del,this),true):false};this.alter=
function(b){var c,g;return f[b]?(g=e.clone(f),c=f[b].apply(f,Array.prototype.slice.call(arguments,1)),a(g),c):false};this.watch=function(a,b,f){return c.watch(a,b,f)};this.unwatch=function(a){return c.unwatch(a)};this.getStoreObservable=function(){return c};this.watchValue=function(a,b,c){return g.watch(a,b,c)};this.unwatchValue=function(a){return g.unwatch(a)};this.getValueObservable=function(){return g};this.loop=function(a,b){e.loop(f,a,b)};this.reset=function(b){if(b instanceof Object){var c=
e.clone(f);f=e.clone(b)||{};a(c);return true}else return false};this.toJSON=function(){return JSON.stringify(f)}}});
define("Tools",function(){return{getGlobal:function(){return function(){return this}.call(null)},mixin:function(b,e,h){this.loop(b,function(f,c){if(!e[c]||!h)e[c]=b[c]});return e},count:function(b){var e=0;this.loop(b,function(){e++});return e},compareObjects:function(b,e){return Object.getOwnPropertyNames(b).sort().join("")==Object.getOwnPropertyNames(e).sort().join("")},compareNumbers:function(b,e){return b>e?1:b<e?-1:0},toArray:function(b){return Array.prototype.slice.call(b)},loop:function(b,
e,h){var f,c;if(b instanceof Object&&typeof e=="function"){if(c=b.length)for(f=0;f<c;f++)e.call(h,b[f],f,b);else for(f in b)b.hasOwnProperty(f)&&e.call(h,b[f],f,b);return true}else return false},objectsDiffs:function(b,e){if(b instanceof Object&&e instanceof Object){var h=[],f=[],c=[],g=[];this.loop(e,function(a,c){typeof b[c]=="undefined"?g.push(c):a!==b[c]?f.push(c):a===b[c]&&h.push(c)});this.loop(b,function(a,b){typeof e[b]=="undefined"&&c.push(b)});return{updated:f,unchanged:h,added:g,deleted:c}}else return false},
jsonify:function(b){return b instanceof Object?JSON.parse(JSON.stringify(b)):false},clone:function(b){return b instanceof Array?b.slice(0):typeof b=="object"&&b!==null&&!(b instanceof RegExp)?this.mixin(b,{}):false},getNestedProperty:function(b,e){return b&&b instanceof Object?typeof e=="string"&&e!=""?e.split(".").reduce(function(b,f){return b&&b[f]},b):typeof e=="number"?b[e]:b:b},setNestedProperty:function(b,e,h){if(b&&b instanceof Object)if(typeof e=="string"&&e!=""){var f=e.split(".");return f.reduce(function(b,
e,a){b[e]=b[e]||{};f.length==a+1&&(b[e]=h);return b[e]},b)}else return typeof e=="number"?(b[e]=h,b[e]):b;else return b}}});
define("Transport",["Store","Tools"],function(b,e){return function(h){var f=null;this.setReqHandlers=function(c){return c instanceof b?(f=c,true):false};this.getReqHandlers=function(){return f};this.request=function(b,e,a,d){return f.has(b)&&typeof e=="object"?(f.get(b)(e,function(){a&&a.apply(d,arguments)}),true):false};this.listen=function(b,g,a,d){if(f.has(b)&&typeof g=="object"&&typeof g.path=="string"&&typeof a=="function"){var h=function(){a.apply(d,arguments)},i;e.mixin({keptAlive:true,method:"get"},
g);i=f.get(b)(g,h,h);return function(){i.func.call(i.scope)}}else return false};this.setReqHandlers(h)}});
/*
Olives http://flams.github.com/olives
The MIT License (MIT)
Copyright (c) 2012 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com>
*/
define("Olives/DomUtils",function(){return{getNodes:function(f,g){return f instanceof HTMLElement?(f.parentNode||document.createDocumentFragment().appendChild(f),f.parentNode.querySelectorAll(g||"*")):false},getDataset:function(f){var g=0,i,k={},d,a;if(f instanceof HTMLElement)if(f.hasOwnProperty("dataset"))return f.dataset;else{for(i=f.attributes.length;g<i;g++)d=f.attributes[g].name.split("-"),d.shift()=="data"&&(k[a=d.join("-")]=f.getAttribute("data-"+a));return k}else return false}}});
define("Olives/Event-plugin",function(){return function(f){this.listen=function(g,i,k,d){g.addEventListener(i,function(a){f[k].call(f,a,g)},d=="true")}}});
define("Olives/LocalStore",["Store","Tools"],function(f,g){function i(){var f=null,d=localStorage,a=function(){d.setItem(f,this.toJSON())};this.setLocalStorage=function(c){return c&&c.setItem instanceof Function?(d=c,true):false};this.getLocalStorage=function(){return d};this.sync=function(c){return typeof c=="string"?(f=c,c=JSON.parse(d.getItem(c)),g.loop(c,function(c,a){this.has(a)||this.set(a,c)},this),a.call(this),this.watch("added",a,this),this.watch("updated",a,this),this.watch("deleted",a,
this),true):false}}return function(g){i.prototype=new f(g);return new i}});
define("Olives/Model-plugin",["Store","Observable","Tools","Olives/DomUtils"],function(f,g,i,k){return function(d,a){var c=null,e={},j={};this.observers={};this.setModel=function(l){return l instanceof f?(c=l,true):false};this.getModel=function(){return c};this.ItemRenderer=function(l,a){var b=null,e=null,d=null,j=null,g=null;this.setRenderer=function(a){b=a;return true};this.getRenderer=function(){return b};this.setRootNode=function(b){return b instanceof HTMLElement?(d=b,b=d.querySelector("*"),
this.setRenderer(b),b&&d.removeChild(b),true):false};this.getRootNode=function(){return d};this.setPlugins=function(b){e=b;return true};this.getPlugins=function(){return e};this.items=new f([]);this.setStart=function(b){return j=parseInt(b,10)};this.getStart=function(){return j};this.setNb=function(b){return g=b=="*"?b:parseInt(b,10)};this.getNb=function(){return g};this.addItem=function(b){var a;return typeof b=="number"&&!this.items.get(b)?(a=this.create(b))?((b=this.getNextItem(b))?d.insertBefore(a,
b):d.appendChild(a),true):false:false};this.getNextItem=function(b){return this.items.alter("slice",b+1).filter(function(b){if(b instanceof HTMLElement)return true})[0]};this.removeItem=function(b){var a=this.items.get(b);return a?(d.removeChild(a),this.items.set(b),true):false};this.create=function(a){if(c.has(a)){var l=b.cloneNode(true),h=k.getNodes(l);i.toArray(h).forEach(function(b){b.setAttribute("data-"+e.name+"_id",a)});this.items.set(a,l);e.apply(l);return l}};this.render=function(){var b=
g=="*"?c.getNbItems():g,a=[];if(g!==null&&j!==null){this.items.loop(function(l,h){(h<j||h>=j+b||!c.has(h))&&a.push(h)},this);a.sort(i.compareNumbers).reverse().forEach(this.removeItem,this);for(var l=j,h=b+j;l<h;l++)this.addItem(l);return true}else return false};this.setPlugins(l);this.setRootNode(a)};this.setItemRenderer=function(a,h){j[a||"default"]=h};this.getItemRenderer=function(a){return j[a]};this.foreach=function(a,h,b,d){var e=new this.ItemRenderer(this.plugins,a);e.setStart(b||0);e.setNb(d||
"*");e.render();c.watch("added",e.render,e);c.watch("deleted",function(b){e.render();this.observers[b]&&this.observers[b].forEach(function(b){c.unwatchValue(b)},this);delete this.observers[b]},this);this.setItemRenderer(h,e)};this.updateStart=function(a,h){var b=this.getItemRenderer(a);return b?(b.setStart(h),true):false};this.updateNb=function(a,h){var b=this.getItemRenderer(a);return b?(b.setNb(h),true):false};this.refresh=function(a){return(a=this.getItemRenderer(a))?(a.render(),true):false};this.bind=
function(a,h,b){var b=b||"",e=a.getAttribute("data-"+this.plugins.name+"_id"),d=b.split("."),j=e||d.shift(),f=e?b:d.join("."),e=i.getNestedProperty(c.get(j),f),g=i.toArray(arguments).slice(3);if(e||e===0||e===false)this.execBinding.apply(this,[a,h,e].concat(g))||(a[h]=e);this.hasBinding(h)||a.addEventListener("change",function(){c.has(j)&&(f?c.update(j,b,a[h]):c.set(j,a[h]))},true);this.observers[j]=this.observers[j]||[];this.observers[j].push(c.watchValue(j,function(b){this.execBinding.apply(this,
[a,h,i.getNestedProperty(b,f)].concat(g))||(a[h]=i.getNestedProperty(b,f))},this))};this.set=function(a){return a instanceof HTMLElement&&a.name?(c.set(a.name,a.value),true):false};this.form=function h(h){if(h&&h.nodeName=="FORM"){var b=this;h.addEventListener("submit",function(a){i.toArray(h.querySelectorAll("[name]")).forEach(b.set,b);a.preventDefault()},true);return true}else return false};this.addBinding=function(a,b){return a&&typeof a=="string"&&typeof b=="function"?(e[a]=b,true):false};this.execBinding=
function(a,b){return this.hasBinding(b)?(e[b].apply(a,Array.prototype.slice.call(arguments,2)),true):false};this.hasBinding=function(a){return e.hasOwnProperty(a)};this.getBinding=function(a){return e[a]};this.addBindings=function(a){return i.loop(a,function(a,e){this.addBinding(e,a)},this)};this.setModel(d);this.addBindings(a)}});
define("Olives/OObject",["StateMachine","Store","Olives/Plugins","Olives/DomUtils","Tools"],function(f,g,i,k,d){return function(a){var c=function(a){var b=j||document.createElement("div");if(a.template){typeof a.template=="string"?b.innerHTML=a.template.trim():a.template instanceof HTMLElement&&b.appendChild(a.template);if(b.childNodes.length>1)throw Error("UI.template should have only one parent node");else a.dom=b.childNodes[0];a.plugins.apply(a.dom)}else throw Error("UI.template must be set prior to render");
},e=function b(a,b,e){b&&(e?b.insertBefore(a.dom,e):b.appendChild(a.dom),j=b)},j=null,l=new f("Init",{Init:[["render",c,this,"Rendered"],["place",function(a,j){c(a);e.apply(null,d.toArray(arguments))},this,"Rendered"]],Rendered:[["place",e,this],["render",c,this]]});this.model=a instanceof g?a:new g;this.plugins=new i;this.dom=this.template=null;this.place=function(a,e){l.event("place",this,a,e)};this.render=function(){l.event("render",this)};this.setTemplateFromDom=function(a){return a instanceof
HTMLElement?(this.template=a,true):false};this.alive=function(a){return a instanceof HTMLElement?(this.setTemplateFromDom(a),this.place(a.parentNode,a.nextElementSibling),true):false}}});
define("Olives/Plugins",["Tools","Olives/DomUtils"],function(f,g){return function(){var i={},k=function(a){return a.trim()},d=function(a,c,e){c.split(";").forEach(function(c){var d=c.split(":"),c=d[0].trim(),d=d[1]?d[1].split(",").map(k):[];d.unshift(a);i[e]&&i[e][c]&&i[e][c].apply(i[e],d)})};this.add=function(a,c){var e=this;return typeof a=="string"&&typeof c=="object"&&c?(i[a]=c,c.plugins={name:a,apply:function(){return e.apply.apply(e,arguments)}},true):false};this.addAll=function(a){return f.loop(a,
function(a,e){this.add(e,a)},this)};this.get=function(a){return i[a]};this.del=function(a){return delete i[a]};this.apply=function(a){var c;return a instanceof HTMLElement?(c=g.getNodes(a),f.loop(f.toArray(c),function(a){f.loop(g.getDataset(a),function(c,f){d(a,c,f)})}),a):false}}});
define("Olives/Transport",["Observable","Tools"],function(f,g){return function(i,k){var d=null,a=null,c=new f;this.setIO=function(e){return e&&typeof e.connect=="function"?(a=e,true):false};this.getIO=function(){return a};this.connect=function(e){return typeof e=="string"?(d=a.connect(e),true):false};this.getSocket=function(){return d};this.on=function(a,c){d.on(a,c)};this.once=function(a,c){d.once(a,c)};this.emit=function(a,c,f){d.emit(a,c,f)};this.request=function(a,c,f,h){var b=Date.now()+Math.floor(Math.random()*
1E6),g=function(){f&&f.apply(h||null,arguments)};d[c.keptAlive?"on":"once"](b,g);c.__eventId__=b;d.emit(a,c);if(c.keptAlive)return function(){d.emit("disconnect-"+b);d.removeListener(b,g)}};this.listen=function(a,d,f,h){var b=a+"/"+d.path,i,k;c.hasTopic(b)||(g.mixin({method:"GET",keptAlive:true},d),k=this.request(a,d,function(a){c.notify(b,a)},this));i=c.watch(b,f,h);return function(){c.unwatch(i);c.hasTopic(b)||k()}};this.getListenObservable=function(){return c};this.setIO(i);this.connect(k)}});
define("Olives/UI-plugin",["Olives/OObject","Tools"],function(f,g){return function(i){var k={};this.place=function(d,a){if(k[a]instanceof f)k[a].place(d);else throw Error(a+" is not an OObject UI in place:"+a);};this.set=function(d,a){return typeof d=="string"&&a instanceof f?(k[d]=a,true):false};this.setAll=function(d){g.loop(d,function(a,c){this.set(c,a)},this)};this.get=function(d){return k[d]};this.setAll(i)}});
/* /*global define*/
* A set of commonly used functions. (function () {
* They're useful for several UIs in the app. 'use strict';
* They could also be reused in other projects
*/
define( 'Todos/Tools', {
// className is set to the 'this' dom node according to the value's truthiness /*
'toggleClass': function ( value, className ) { * A set of commonly used functions.
value ? this.classList.add( className ) : this.classList.remove( className ); * They're useful for several UIs in the app.
} * They could also be reused in other projects
*/
}); define('Todos/Tools', {
// className is set to the 'this' dom node according to the value's truthiness
'toggleClass': function (value, className) {
if (value) {
this.classList.add(className);
} else {
this.classList.remove(className);
}
}
});
})();
/*
RequireJS 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(){function J(a){return M.call(a)==="[object Function]"}function E(a){return M.call(a)==="[object Array]"}function Z(a,c,h){for(var k in c)if(!(k in K)&&(!(k in a)||h))a[k]=c[k];return d}function N(a,c,d){a=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+a);if(d)a.originalError=d;return a}function $(a,c,d){var k,j,q;for(k=0;q=c[k];k++){q=typeof q==="string"?{name:q}:q;j=q.location;if(d&&(!j||j.indexOf("/")!==0&&j.indexOf(":")===-1))j=d+"/"+(j||q.name);a[q.name]={name:q.name,location:j||
q.name,main:(q.main||"main").replace(ea,"").replace(aa,"")}}}function V(a,c){a.holdReady?a.holdReady(c):c?a.readyWait+=1:a.ready(!0)}function fa(a){function c(b,l){var f,a;if(b&&b.charAt(0)===".")if(l){p.pkgs[l]?l=[l]:(l=l.split("/"),l=l.slice(0,l.length-1));f=b=l.concat(b.split("/"));var c;for(a=0;c=f[a];a++)if(c===".")f.splice(a,1),a-=1;else if(c==="..")if(a===1&&(f[2]===".."||f[0]===".."))break;else a>0&&(f.splice(a-1,2),a-=2);a=p.pkgs[f=b[0]];b=b.join("/");a&&b===f+"/"+a.main&&(b=f)}else b.indexOf("./")===
0&&(b=b.substring(2));return b}function h(b,l){var f=b?b.indexOf("!"):-1,a=null,d=l?l.name:null,i=b,e,h;f!==-1&&(a=b.substring(0,f),b=b.substring(f+1,b.length));a&&(a=c(a,d));b&&(a?e=(f=m[a])&&f.normalize?f.normalize(b,function(b){return c(b,d)}):c(b,d):(e=c(b,d),h=E[e],h||(h=g.nameToUrl(e,null,l),E[e]=h)));return{prefix:a,name:e,parentMap:l,url:h,originalName:i,fullName:a?a+"!"+(e||""):e}}function k(){var b=!0,l=p.priorityWait,f,a;if(l){for(a=0;f=l[a];a++)if(!s[f]){b=!1;break}b&&delete p.priorityWait}return b}
function j(b,l,f){return function(){var a=ga.call(arguments,0),c;if(f&&J(c=a[a.length-1]))c.__requireJsBuild=!0;a.push(l);return b.apply(null,a)}}function q(b,l){var a=j(g.require,b,l);Z(a,{nameToUrl:j(g.nameToUrl,b),toUrl:j(g.toUrl,b),defined:j(g.requireDefined,b),specified:j(g.requireSpecified,b),isBrowser:d.isBrowser});return a}function o(b){var l,a,c,C=b.callback,i=b.map,e=i.fullName,ba=b.deps;c=b.listeners;if(C&&J(C)){if(p.catchError.define)try{a=d.execCb(e,b.callback,ba,m[e])}catch(k){l=k}else a=
d.execCb(e,b.callback,ba,m[e]);if(e)(C=b.cjsModule)&&C.exports!==void 0&&C.exports!==m[e]?a=m[e]=b.cjsModule.exports:a===void 0&&b.usingExports?a=m[e]:(m[e]=a,F[e]&&(Q[e]=!0))}else e&&(a=m[e]=C,F[e]&&(Q[e]=!0));if(D[b.id])delete D[b.id],b.isDone=!0,g.waitCount-=1,g.waitCount===0&&(I=[]);delete R[e];if(d.onResourceLoad&&!b.placeholder)d.onResourceLoad(g,i,b.depArray);if(l)return a=(e?h(e).url:"")||l.fileName||l.sourceURL,c=l.moduleTree,l=N("defineerror",'Error evaluating module "'+e+'" at location "'+
a+'":\n'+l+"\nfileName:"+a+"\nlineNumber: "+(l.lineNumber||l.line),l),l.moduleName=e,l.moduleTree=c,d.onError(l);for(l=0;C=c[l];l++)C(a)}function r(b,a){return function(f){b.depDone[a]||(b.depDone[a]=!0,b.deps[a]=f,b.depCount-=1,b.depCount||o(b))}}function u(b,a){var f=a.map,c=f.fullName,h=f.name,i=L[b]||(L[b]=m[b]),e;if(!a.loading)a.loading=!0,e=function(b){a.callback=function(){return b};o(a);s[a.id]=!0;w()},e.fromText=function(b,a){var l=O;s[b]=!1;g.scriptCount+=1;g.fake[b]=!0;l&&(O=!1);d.exec(a);
l&&(O=!0);g.completeLoad(b)},c in m?e(m[c]):i.load(h,q(f.parentMap,!0),e,p)}function v(b){D[b.id]||(D[b.id]=b,I.push(b),g.waitCount+=1)}function B(b){this.listeners.push(b)}function t(b,a){var f=b.fullName,c=b.prefix,d=c?L[c]||(L[c]=m[c]):null,i,e;f&&(i=R[f]);if(!i&&(e=!0,i={id:(c&&!d?M++ +"__p@:":"")+(f||"__r@"+M++),map:b,depCount:0,depDone:[],depCallbacks:[],deps:[],listeners:[],add:B},y[i.id]=!0,f&&(!c||L[c])))R[f]=i;c&&!d?(f=t(h(c),!0),f.add(function(){var a=h(b.originalName,b.parentMap),a=t(a,
!0);i.placeholder=!0;a.add(function(b){i.callback=function(){return b};o(i)})})):e&&a&&(s[i.id]=!1,g.paused.push(i),v(i));return i}function x(b,a,f,c){var b=h(b,c),d=b.name,i=b.fullName,e=t(b),k=e.id,j=e.deps,n;if(i){if(i in m||s[k]===!0||i==="jquery"&&p.jQuery&&p.jQuery!==f().fn.jquery)return;y[k]=!0;s[k]=!0;i==="jquery"&&f&&S(f())}e.depArray=a;e.callback=f;for(f=0;f<a.length;f++)if(k=a[f])k=h(k,d?b:c),n=k.fullName,a[f]=n,n==="require"?j[f]=q(b):n==="exports"?(j[f]=m[i]={},e.usingExports=!0):n===
"module"?e.cjsModule=j[f]={id:d,uri:d?g.nameToUrl(d,null,c):void 0,exports:m[i]}:n in m&&!(n in D)&&(!(i in F)||i in F&&Q[n])?j[f]=m[n]:(i in F&&(F[n]=!0,delete m[n],T[k.url]=!1),e.depCount+=1,e.depCallbacks[f]=r(e,f),t(k,!0).add(e.depCallbacks[f]));e.depCount?v(e):o(e)}function n(b){x.apply(null,b)}function z(b,a){if(!b.isDone){var c=b.map.fullName,d=b.depArray,g,i,e,k;if(c){if(a[c])return m[c];a[c]=!0}if(d)for(g=0;g<d.length;g++)if(i=d[g])if((e=h(i).prefix)&&(k=D[e])&&z(k,a),(e=D[i])&&!e.isDone&&
s[i])i=z(e,a),b.depCallbacks[g](i);return c?m[c]:void 0}}function A(){var b=p.waitSeconds*1E3,a=b&&g.startTime+b<(new Date).getTime(),b="",c=!1,h=!1,j;if(!(g.pausedCount>0)){if(p.priorityWait)if(k())w();else return;for(j in s)if(!(j in K)&&(c=!0,!s[j]))if(a)b+=j+" ";else{h=!0;break}if(c||g.waitCount){if(a&&b)return j=N("timeout","Load timeout for modules: "+b),j.requireType="timeout",j.requireModules=b,d.onError(j);if(h||g.scriptCount){if((G||ca)&&!W)W=setTimeout(function(){W=0;A()},50)}else{if(g.waitCount){for(H=
0;b=I[H];H++)z(b,{});g.paused.length&&w();X<5&&(X+=1,A())}X=0;d.checkReadyState()}}}}var g,w,p={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},catchError:{}},P=[],y={require:!0,exports:!0,module:!0},E={},m={},s={},D={},I=[],T={},M=0,R={},L={},F={},Q={},Y=0;S=function(b){if(!g.jQuery&&(b=b||(typeof jQuery!=="undefined"?jQuery:null))&&!(p.jQuery&&b.fn.jquery!==p.jQuery)&&("holdReady"in b||"readyWait"in b))if(g.jQuery=b,n(["jquery",[],function(){return jQuery}]),g.scriptCount)V(b,!0),g.jQueryIncremented=
!0};w=function(){var b,a,c,h,j,i;Y+=1;if(g.scriptCount<=0)g.scriptCount=0;for(;P.length;)if(b=P.shift(),b[0]===null)return d.onError(N("mismatch","Mismatched anonymous define() module: "+b[b.length-1]));else n(b);if(!p.priorityWait||k())for(;g.paused.length;){j=g.paused;g.pausedCount+=j.length;g.paused=[];for(h=0;b=j[h];h++)a=b.map,c=a.url,i=a.fullName,a.prefix?u(a.prefix,b):!T[c]&&!s[i]&&(d.load(g,i,c),c.indexOf("empty:")!==0&&(T[c]=!0));g.startTime=(new Date).getTime();g.pausedCount-=j.length}Y===
1&&A();Y-=1};g={contextName:a,config:p,defQueue:P,waiting:D,waitCount:0,specified:y,loaded:s,urlMap:E,urlFetched:T,scriptCount:0,defined:m,paused:[],pausedCount:0,plugins:L,needFullExec:F,fake:{},fullExec:Q,managerCallbacks:R,makeModuleMap:h,normalize:c,configure:function(b){var a,c,d;b.baseUrl&&b.baseUrl.charAt(b.baseUrl.length-1)!=="/"&&(b.baseUrl+="/");a=p.paths;d=p.pkgs;Z(p,b,!0);if(b.paths){for(c in b.paths)c in K||(a[c]=b.paths[c]);p.paths=a}if((a=b.packagePaths)||b.packages){if(a)for(c in a)c in
K||$(d,a[c],c);b.packages&&$(d,b.packages);p.pkgs=d}if(b.priority)c=g.requireWait,g.requireWait=!1,g.takeGlobalQueue(),w(),g.require(b.priority),w(),g.requireWait=c,p.priorityWait=b.priority;if(b.deps||b.callback)g.require(b.deps||[],b.callback)},requireDefined:function(b,a){return h(b,a).fullName in m},requireSpecified:function(b,a){return h(b,a).fullName in y},require:function(b,c,f){if(typeof b==="string"){if(J(c))return d.onError(N("requireargs","Invalid require call"));if(d.get)return d.get(g,
b,c);c=h(b,c);b=c.fullName;return!(b in m)?d.onError(N("notloaded","Module name '"+c.fullName+"' has not been loaded yet for context: "+a)):m[b]}(b&&b.length||c)&&x(null,b,c,f);if(!g.requireWait)for(;!g.scriptCount&&g.paused.length;)g.takeGlobalQueue(),w();return g.require},takeGlobalQueue:function(){U.length&&(ha.apply(g.defQueue,[g.defQueue.length-1,0].concat(U)),U=[])},completeLoad:function(b){var a;for(g.takeGlobalQueue();P.length;)if(a=P.shift(),a[0]===null){a[0]=b;break}else if(a[0]===b)break;
else n(a),a=null;a?n(a):n([b,[],b==="jquery"&&typeof jQuery!=="undefined"?function(){return jQuery}:null]);S();d.isAsync&&(g.scriptCount-=1);w();d.isAsync||(g.scriptCount-=1)},toUrl:function(a,c){var d=a.lastIndexOf("."),h=null;d!==-1&&(h=a.substring(d,a.length),a=a.substring(0,d));return g.nameToUrl(a,h,c)},nameToUrl:function(a,h,f){var j,k,i,e,m=g.config,a=c(a,f&&f.fullName);if(d.jsExtRegExp.test(a))h=a+(h?h:"");else{j=m.paths;k=m.pkgs;f=a.split("/");for(e=f.length;e>0;e--)if(i=f.slice(0,e).join("/"),
j[i]){f.splice(0,e,j[i]);break}else if(i=k[i]){a=a===i.name?i.location+"/"+i.main:i.location;f.splice(0,e,a);break}h=f.join("/")+(h||".js");h=(h.charAt(0)==="/"||h.match(/^\w+:/)?"":m.baseUrl)+h}return m.urlArgs?h+((h.indexOf("?")===-1?"?":"&")+m.urlArgs):h}};g.jQueryCheck=S;g.resume=w;return g}function ia(){var a,c,d;if(n&&n.readyState==="interactive")return n;a=document.getElementsByTagName("script");for(c=a.length-1;c>-1&&(d=a[c]);c--)if(d.readyState==="interactive")return n=d;return null}var ja=
/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ka=/require\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/^\.\//,aa=/\.js$/,M=Object.prototype.toString,r=Array.prototype,ga=r.slice,ha=r.splice,G=!!(typeof window!=="undefined"&&navigator&&document),ca=!G&&typeof importScripts!=="undefined",la=G&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,da=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",K={},t={},U=[],n=null,X=0,O=!1,d,r={},I,v,x,y,u,z,A,H,B,S,W;if(typeof define==="undefined"){if(typeof requirejs!==
"undefined")if(J(requirejs))return;else r=requirejs,requirejs=void 0;typeof require!=="undefined"&&!J(require)&&(r=require,require=void 0);d=requirejs=function(a,c,d){var k="_",j;!E(a)&&typeof a!=="string"&&(j=a,E(c)?(a=c,c=d):a=[]);if(j&&j.context)k=j.context;d=t[k]||(t[k]=fa(k));j&&d.configure(j);return d.require(a,c)};d.config=function(a){return d(a)};require||(require=d);d.toUrl=function(a){return t._.toUrl(a)};d.version="1.0.2";d.jsExtRegExp=/^\/|:|\?|\.js$/;v=d.s={contexts:t,skipAsync:{}};if(d.isAsync=
d.isBrowser=G)if(x=v.head=document.getElementsByTagName("head")[0],y=document.getElementsByTagName("base")[0])x=v.head=y.parentNode;d.onError=function(a){throw a;};d.load=function(a,c,h){d.resourcesReady(!1);a.scriptCount+=1;d.attach(h,a,c);if(a.jQuery&&!a.jQueryIncremented)V(a.jQuery,!0),a.jQueryIncremented=!0};define=function(a,c,d){var k,j;typeof a!=="string"&&(d=c,c=a,a=null);E(c)||(d=c,c=[]);!c.length&&J(d)&&d.length&&(d.toString().replace(ja,"").replace(ka,function(a,d){c.push(d)}),c=(d.length===
1?["require"]:["require","exports","module"]).concat(c));if(O&&(k=I||ia()))a||(a=k.getAttribute("data-requiremodule")),j=t[k.getAttribute("data-requirecontext")];(j?j.defQueue:U).push([a,c,d])};define.amd={multiversion:!0,plugins:!0,jQuery:!0};d.exec=function(a){return eval(a)};d.execCb=function(a,c,d,k){return c.apply(k,d)};d.addScriptToDom=function(a){I=a;y?x.insertBefore(a,y):x.appendChild(a);I=null};d.onScriptLoad=function(a){var c=a.currentTarget||a.srcElement,h;if(a.type==="load"||c&&la.test(c.readyState))n=
null,a=c.getAttribute("data-requirecontext"),h=c.getAttribute("data-requiremodule"),t[a].completeLoad(h),c.detachEvent&&!da?c.detachEvent("onreadystatechange",d.onScriptLoad):c.removeEventListener("load",d.onScriptLoad,!1)};d.attach=function(a,c,h,k,j,n){var o;if(G)return k=k||d.onScriptLoad,o=c&&c.config&&c.config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"),o.type=j||"text/javascript",o.charset="utf-8",o.async=!v.skipAsync[a],c&&o.setAttribute("data-requirecontext",
c.contextName),o.setAttribute("data-requiremodule",h),o.attachEvent&&!da?(O=!0,n?o.onreadystatechange=function(){if(o.readyState==="loaded")o.onreadystatechange=null,o.attachEvent("onreadystatechange",k),n(o)}:o.attachEvent("onreadystatechange",k)):o.addEventListener("load",k,!1),o.src=a,n||d.addScriptToDom(o),o;else ca&&(importScripts(a),c.completeLoad(h));return null};if(G){u=document.getElementsByTagName("script");for(H=u.length-1;H>-1&&(z=u[H]);H--){if(!x)x=z.parentNode;if(A=z.getAttribute("data-main")){if(!r.baseUrl)u=
A.split("/"),z=u.pop(),u=u.length?u.join("/")+"/":"./",r.baseUrl=u,A=z.replace(aa,"");r.deps=r.deps?r.deps.concat(A):[A];break}}}d.checkReadyState=function(){var a=v.contexts,c;for(c in a)if(!(c in K)&&a[c].waitCount)return;d.resourcesReady(!0)};d.resourcesReady=function(a){var c,h;d.resourcesDone=a;if(d.resourcesDone)for(h in a=v.contexts,a)if(!(h in K)&&(c=a[h],c.jQueryIncremented))V(c.jQuery,!1),c.jQueryIncremented=!1};d.pageLoaded=function(){if(document.readyState!=="complete")document.readyState=
"complete"};if(G&&document.addEventListener&&!document.readyState)document.readyState="loading",window.addEventListener("load",d.pageLoaded,!1);d(r);if(d.isAsync&&typeof setTimeout!=="undefined")B=v.contexts[r.context||"_"],B.requireWait=!0,setTimeout(function(){B.requireWait=!1;B.takeGlobalQueue();B.jQueryCheck();B.scriptCount||B.resume();d.checkReadyState()},0)}})();
/*global define*/ /*global define*/
(function () {
define('Todos/Controls',
['Olives/OObject', 'Olives/Event-plugin', 'Olives/Model-plugin', 'Olives/LocalStore', 'Todos/Tools'],
// The Controls UI
function Controls(OObject, EventPlugin, ModelPlugin, Store, Tools) {
'use strict'; 'use strict';
return function ControlsInit(view, model, stats) { define('Todos/Controls', [
// The OObject (the controller) inits with a default model which is a simple store 'components/olives/src/OObject',
// But it can be init'ed with any other store, like the LocalStore 'components/olives/src/Event.plugin',
var controls = new OObject(model), 'components/olives/src/Bind.plugin',
'LocalStore',
// A function to get the completed tasks 'Todos/Tools'
getCompleted = function () { ],
var completed = [];
model.loop(function (value, id) {
if (value.completed) {
completed.push(id);
}
});
return completed;
},
// Update all stats // The Controls UI
updateStats = function () { function Controls(OObject, EventPlugin, ModelPlugin, Store, Tools) {
var nbCompleted = getCompleted().length; return function ControlsInit(view, model, stats) {
// The OObject (the controller) inits with a default model which is a simple store
// But it can be init'ed with any other store, like the LocalStore
var controls = new OObject(model);
stats.set('nbItems', model.getNbItems()); // A function to get the completed tasks
stats.set('nbLeft', stats.get('nbItems') - nbCompleted); var getCompleted = function () {
stats.set('nbCompleted', nbCompleted); var completed = [];
stats.set('plural', stats.get('nbLeft') === 1 ? 'item' : 'items'); model.loop(function (value, id) {
}; if (value.completed) {
completed.push(id);
}
});
return completed;
};
// Add plugins to the UI. // Update all stats
controls.plugins.addAll({ var updateStats = function () {
'event': new EventPlugin(controls), var nbCompleted = getCompleted().length;
'stats': new ModelPlugin(stats, {
'toggleClass': Tools.toggleClass
})
});
// Alive applies the plugins to the HTML view stats.set('nbItems', model.getNbItems());
controls.alive(view); stats.set('nbLeft', stats.get('nbItems') - nbCompleted);
stats.set('nbCompleted', nbCompleted);
stats.set('plural', stats.get('nbLeft') === 1 ? 'item' : 'items');
};
// Delete all tasks // Add plugins to the UI.
controls.delAll = function () { controls.plugins.addAll({
model.delAll(getCompleted()); 'event': new EventPlugin(controls),
}; 'stats': new ModelPlugin(stats, {
'toggleClass': Tools.toggleClass
})
});
// Update stats when the tasks list is modified // Alive applies the plugins to the HTML view
model.watch('added', updateStats); controls.alive(view);
model.watch('deleted', updateStats);
model.watch('updated', updateStats);
// I could either update stats at init or save them in a localStore // Delete all tasks
updateStats(); controls.delAll = function () {
model.delAll(getCompleted());
};
}; // Update stats when the tasks list is modified
}); model.watch('added', updateStats);
model.watch('deleted', updateStats);
model.watch('updated', updateStats);
// I could either update stats at init or save them in a localStore
updateStats();
};
});
})();
/*global define*/ /*global define*/
(function () {
// It's going to be called Input
define('Todos/Input',
// It uses the Olives' OObject and the Event Plugin to listen to dom events and connect them to methods
['Olives/OObject', 'Olives/Event-plugin'],
// The Input UI
function Input(OObject, EventPlugin) {
'use strict'; 'use strict';
// It returns an init function // It's going to be called Input
return function InputInit(view, model) { define('Todos/Input', [
// The OObject (the controller) inits with a default model which is a simple store // It uses the Olives' OObject and the Event Plugin to listen to dom events and connect them to methods
// But it can be init'ed with any other store, like the LocalStore 'components/olives/src/OObject',
var input = new OObject(model), 'components/olives/src/Event.plugin'
],
ENTER_KEY = 13;
// The Input UI
// The event plugin that is added to the OObject function Input(OObject, EventPlugin) {
// We have to tell it where to find the methods // It returns an init function
input.plugins.add('event', new EventPlugin(input)); return function InputInit(view, model) {
// The OObject (the controller) inits with a default model which is a simple store
// The method to add a new taks // But it can be init'ed with any other store, like the LocalStore
input.addTask = function addTask(event, node) { var input = new OObject(model);
if (event.keyCode === ENTER_KEY && node.value.trim()) { var ENTER_KEY = 13;
model.alter('push', {
title: node.value.trim(), // The event plugin that is added to the OObject
completed: false // We have to tell it where to find the methods
}); input.plugins.add('event', new EventPlugin(input));
node.value = '';
} // The method to add a new taks
input.addTask = function addTask(event, node) {
if (event.keyCode === ENTER_KEY && node.value.trim()) {
model.alter('push', {
title: node.value.trim(),
completed: false
});
node.value = '';
}
};
// Alive applies the plugins to the HTML view
input.alive(view);
}; };
});
// Alive applies the plugins to the HTML view })();
input.alive(view);
};
});
/*global define*/ /*global define*/
define('Todos/List', (function () {
['Olives/OObject', 'Olives/Event-plugin', 'Olives/Model-plugin', 'Todos/Tools'],
// The List UI
function List(OObject, EventPlugin, ModelPlugin, Tools) {
'use strict'; 'use strict';
return function ListInit(view, model, stats) { define('Todos/List', [
// The OObject (the controller) inits with a default model which is a simple store 'components/olives/src/OObject',
// But it can be init'ed with any other store, like the LocalStore 'components/olives/src/Event.plugin',
var list = new OObject(model), 'components/olives/src/Bind.plugin',
'Todos/Tools'
ENTER_KEY = 13; ],
// The plugins // The List UI
list.plugins.addAll({ function List(OObject, EventPlugin, ModelPlugin, Tools) {
'event': new EventPlugin(list), return function ListInit(view, model, stats) {
'model': new ModelPlugin(model, { // The OObject (the controller) inits with a default model which is a simple store
'toggleClass': Tools.toggleClass // But it can be init'ed with any other store, like the LocalStore
}), var list = new OObject(model);
'stats': new ModelPlugin(stats, { var ENTER_KEY = 13;
'toggleClass': Tools.toggleClass,
'toggleCheck': function (value) { // The plugins
this.checked = model.getNbItems() === value ? 'on' : ''; list.plugins.addAll({
} 'event': new EventPlugin(list),
}) 'model': new ModelPlugin(model, {
}); 'toggleClass': Tools.toggleClass
}),
// Remove the completed task 'stats': new ModelPlugin(stats, {
list.remove = function remove(event, node) { 'toggleClass': Tools.toggleClass,
model.del(node.getAttribute('data-model_id')); 'toggleCheck': function (value) {
}; this.checked = model.getNbItems() === value ? 'on' : '';
}
// Un/check all tasks })
list.toggleAll = function toggleAll(event, node) { });
var checked = !!node.checked;
// Remove the completed task
model.loop(function (value, idx) { list.remove = function remove(event, node) {
this.update(idx, 'completed', checked); model.del(node.getAttribute('data-model_id'));
}, model); };
};
// Un/check all tasks
// Enter edit mode list.toggleAll = function toggleAll(event, node) {
list.startEdit = function (event, node) { var checked = !!node.checked;
var taskId = node.getAttribute('data-model_id');
model.loop(function (value, idx) {
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), true, 'editing'); this.update(idx, 'completed', checked);
view.querySelector('input.edit[data-model_id="' + taskId + '"]').focus(); }, model);
}; };
// Leave edit mode // Enter edit mode
list.stopEdit = function (event, node) { list.startEdit = function (event, node) {
var taskId = node.getAttribute('data-model_id'), var taskId = node.getAttribute('data-model_id');
value;
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), true, 'editing');
if (event.keyCode === ENTER_KEY) { view.querySelector('input.edit[data-model_id="' + taskId + '"]').focus();
value = node.value.trim(); };
if (value) { // Leave edit mode
model.update(taskId, 'title', value); list.stopEdit = function (event, node) {
} else { var taskId = node.getAttribute('data-model_id');
model.del(taskId); var value;
}
if (event.keyCode === ENTER_KEY) {
// When task #n is removed, #n+1 becomes #n, the dom node is updated to the new value, so editing mode should exit anyway value = node.value.trim();
if (model.has(taskId)) {
if (value) {
model.update(taskId, 'title', value);
} else {
model.del(taskId);
}
// When task #n is removed, #n+1 becomes #n, the dom node is updated to the new value, so editing mode should exit anyway
if (model.has(taskId)) {
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), false, 'editing');
}
} else if (event.type === 'blur') {
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), false, 'editing'); Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), false, 'editing');
} }
} else if (event.type === 'blur') { };
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), false, 'editing');
}
};
// Alive applies the plugins to the HTML view
list.alive(view);
}; // Alive applies the plugins to the HTML view
list.alive(view);
}); };
});
})();
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