Commit 5a3c81c5 authored by Olivier Scherrer's avatar Olivier Scherrer Committed by Arthur Verschaeve

Olives: update to olives and emily 3.x, remove requirejs

* Update to the latest version of the Olives framework.
* Update to the latest version of Emily
* Remove requirejs in favor of browserify
   - also implemented npm scripts and updated the readme

As a result of updating dependencies, this fixes the issue in #1029.

Ref #1029
Close #1242
parent 65a8ecfa
......@@ -40,13 +40,6 @@
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<script src="node_modules/todomvc-common/base.js"></script>
<script src="node_modules/requirejs/require.js"></script>
<script src="node_modules/emily/build/Emily.js"></script>
<script src="node_modules/olives/build/Olives.js"></script>
<script src="js/lib/Tools.js"></script>
<script src="js/uis/Input.js"></script>
<script src="js/uis/List.js"></script>
<script src="js/uis/Controls.js"></script>
<script src="js/app.js"></script>
<script src="olives-todo.js"></script>
</body>
</html>
/*global require*/
(function () {
'use strict';
'use strict';
var input = require('./uis/input');
var list = require('./uis/list');
var controls = require('./uis/controls');
// These are the UIs that compose the Todo application
require([
'Todos/Input',
'Todos/List',
'Todos/Controls',
'node_modules/olives/build/src/LocalStore',
'Store'
],
var LocalStore = require('olives').LocalStore;
var Store = require('emily').Store;
// The application
function Todos(Input, List, Controls, LocalStore, Store) {
// The tasks Store is told to init on an array
// so tasks are indexed by a number
// This store is shared among several UIs of this application
// that's why it's created here
var tasks = new LocalStore([]);
// The tasks Store is told to init on an array
// so tasks are indexed by a number
// This store is shared among several UIs of this application
// that's why it's created here
var tasks = new LocalStore([]);
// Also create a shared stats store
var stats = new Store({
nbItems: 0,
nbLeft: 0,
nbCompleted: 0,
plural: 'items'
});
// Also create a shared stats store
var stats = new Store({
nbItems: 0,
nbLeft: 0,
nbCompleted: 0,
plural: 'items'
});
// Synchronize the store on 'todos-olives' localStorage
tasks.sync('todos-olives');
// Synchronize the store on 'todos-olives' localStorage
tasks.sync('todos-olives');
// Initialize Input UI by giving it a view and a model.
Input(document.querySelector('#header input'), tasks);
// Initialize Input UI by giving it a view and a model.
input(document.querySelector('#header input'), tasks);
// Init the List UI the same way, pass it the stats store too
List(document.querySelector('#main'), tasks, stats);
// Init the List UI the same way, pass it the stats store too
list(document.querySelector('#main'), tasks, stats);
// Same goes for the control UI
Controls(document.querySelector('#footer'), tasks, stats);
});
})();
// Same goes for the control UI
controls(document.querySelector('#footer'), tasks, stats);
/*global define*/
(function () {
'use strict';
'use strict';
/*
* A set of commonly used functions.
* 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);
}
/*
* A set of commonly used functions.
* They're useful for several UIs in the app.
* They could also be reused in other projects
*/
module.exports = {
// 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);
}
});
})();
}
};
/*global define*/
(function () {
'use strict';
define('Todos/Controls', [
'node_modules/olives/build/src/OObject',
'node_modules/olives/build/src/Event.plugin',
'node_modules/olives/build/src/Bind.plugin',
'LocalStore',
'Todos/Tools'
],
// The Controls UI
function Controls(OObject, EventPlugin, ModelPlugin, Store, Tools) {
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);
// A function to get the completed tasks
var getCompleted = function () {
var completed = [];
model.loop(function (value, id) {
if (value.completed) {
completed.push(id);
}
});
return completed;
};
// Update all stats
var updateStats = function () {
var nbCompleted = getCompleted().length;
stats.set('nbItems', model.getNbItems());
stats.set('nbLeft', stats.get('nbItems') - nbCompleted);
stats.set('nbCompleted', nbCompleted);
stats.set('plural', stats.get('nbLeft') === 1 ? 'item' : 'items');
};
// Add plugins to the UI.
controls.plugins.addAll({
'event': new EventPlugin(controls),
'stats': new ModelPlugin(stats, {
'toggleClass': Tools.toggleClass
})
});
// Alive applies the plugins to the HTML view
controls.alive(view);
// Delete all tasks
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*/
(function () {
'use strict';
// 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
'node_modules/olives/build/src/OObject',
'node_modules/olives/build/src/Event.plugin'
],
// The Input UI
function Input(OObject, EventPlugin) {
// It returns an init function
return function InputInit(view, model) {
// 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 input = new OObject(model);
var ENTER_KEY = 13;
// The event plugin that is added to the OObject
// We have to tell it where to find the methods
input.plugins.add('event', new EventPlugin(input));
// 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);
};
});
})();
/*global define*/
(function () {
'use strict';
define('Todos/List', [
'node_modules/olives/build/src/OObject',
'node_modules/olives/build/src/Event.plugin',
'node_modules/olives/build/src/Bind.plugin',
'Todos/Tools'
],
// The List UI
function List(OObject, EventPlugin, ModelPlugin, Tools) {
return function ListInit(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 list = new OObject(model);
var ENTER_KEY = 13;
// The plugins
list.plugins.addAll({
'event': new EventPlugin(list),
'model': new ModelPlugin(model, {
'toggleClass': Tools.toggleClass
}),
'stats': new ModelPlugin(stats, {
'toggleClass': Tools.toggleClass,
'toggleCheck': function (value) {
this.checked = model.getNbItems() === value ? 'on' : '';
}
})
});
// Remove the completed task
list.remove = function remove(event, node) {
model.del(node.getAttribute('data-model_id'));
};
// Un/check all tasks
list.toggleAll = function toggleAll(event, node) {
var checked = !!node.checked;
model.loop(function (value, idx) {
this.update(idx, 'completed', checked);
}, model);
};
// Enter edit mode
list.startEdit = function (event, node) {
var taskId = node.getAttribute('data-model_id');
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), true, 'editing');
view.querySelector('input.edit[data-model_id="' + taskId + '"]').focus();
};
// Leave edit mode
list.stopEdit = function (event, node) {
var taskId = node.getAttribute('data-model_id');
var value;
if (event.keyCode === ENTER_KEY) {
value = node.value.trim();
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');
}
};
// Alive applies the plugins to the HTML view
list.alive(view);
};
});
})();
'use strict';
var OObject = require('olives').OObject;
var EventPlugin = require('olives')['Event.plugin'];
var BindPlugin = require('olives')['Bind.plugin'];
var Tools = require('../lib/Tools');
module.exports = 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);
// A function to get the completed tasks
var getCompleted = function () {
var completed = [];
model.loop(function (value, id) {
if (value.completed) {
completed.push(id);
}
});
return completed;
};
// Update all stats
var updateStats = function () {
var nbCompleted = getCompleted().length;
stats.set('nbItems', model.count());
stats.set('nbLeft', stats.get('nbItems') - nbCompleted);
stats.set('nbCompleted', nbCompleted);
stats.set('plural', stats.get('nbLeft') === 1 ? 'item' : 'items');
};
// Add plugins to the UI.
controls.seam.addAll({
event: new EventPlugin(controls),
stats: new BindPlugin(stats, {
toggleClass: Tools.toggleClass
})
});
// Alive applies the plugins to the HTML view
controls.alive(view);
// Delete all tasks
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();
};
'use strict';
var OObject = require('olives').OObject;
var EventPlugin = require('olives')['Event.plugin'];
// It returns an init function
module.exports = function inputInit(view, model) {
// 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 input = new OObject(model);
var ENTER_KEY = 13;
// The event plugin that is added to the OObject
// We have to tell it where to find the methods
input.seam.add('event', new EventPlugin(input));
// 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);
};
'use strict';
var OObject = require('olives').OObject;
var EventPlugin = require('olives')['Event.plugin'];
var BindPlugin = require('olives')['Bind.plugin'];
var Tools = require('../lib/Tools');
module.exports = function listInit(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 list = new OObject(model);
var ENTER_KEY = 13;
// The plugins
list.seam.addAll({
event: new EventPlugin(list),
model: new BindPlugin(model, {
toggleClass: Tools.toggleClass
}),
stats: new BindPlugin(stats, {
toggleClass: Tools.toggleClass,
toggleCheck: function (value) {
this.checked = model.count() === value ? 'on' : '';
}
})
});
// Remove the completed task
list.remove = function remove(event, node) {
model.del(node.getAttribute('data-model_id'));
};
// Un/check all tasks
list.toggleAll = function toggleAll(event, node) {
var checked = !!node.checked;
model.loop(function (value, idx) {
this.update(idx, 'completed', checked);
}, model);
};
// Enter edit mode
list.startEdit = function (event, node) {
var taskId = node.getAttribute('data-model_id');
Tools.toggleClass.call(view.querySelector('li[data-model_id="' + taskId + '"]'), true, 'editing');
view.querySelector('input.edit[data-model_id="' + taskId + '"]').focus();
};
// Leave edit mode
list.stopEdit = function (event, node) {
var taskId = node.getAttribute('data-model_id');
var value;
if (event.keyCode === ENTER_KEY) {
value = node.value.trim();
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');
}
};
// Alive applies the plugins to the HTML view
list.alive(view);
};
/**
* @license Emily <VERSION> http://flams.github.com/emily
*
* The MIT License (MIT)
*
* Copyright (c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
*/
/**
* Emily.js - http://flams.github.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(){
/**
* Get the closest number in an array
* @param {Number} item the base number
* @param {Array} array the array to search into
* @param {Function} getDiff returns the difference between the base number and
* and the currently read item in the array. The item which returned the smallest difference wins.
* @private
*/
function _getClosest(item, array, getDiff) {
var closest,
diff;
if (!array) {
return;
}
array.forEach(function (comparedItem, comparedItemIndex) {
var thisDiff = getDiff(comparedItem, item);
if (thisDiff >= 0 && (typeof diff == "undefined" || thisDiff < diff)) {
diff = thisDiff;
closest = comparedItemIndex;
}
});
return closest;
}
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;
}
},
/**
* Get the closest number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 3 as 29 is the closest item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closest: function closest(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return Math.abs(comparedItem - item);
});
},
/**
* Get the closest greater number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 2 as 50 is the closest greater item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closestGreater: function closestGreater(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return comparedItem - item;
});
},
/**
* Get the closest lower number in an array given a base number
* Example: closest(30, [20, 0, 50, 29]) will return 0 as 20 is the closest lower item
* @param {Number} item the base number
* @param {Array} array the array of numbers to search into
* @returns {Number} the index of the closest item in the array
*/
closestLower: function closestLower(item, array) {
return _getClosest(item, array, function (comparedItem, item) {
return item - comparedItem;
});
}
};
});
/**
* Emily.js - http://flams.github.com/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;
}
};
/**
* Listen to an event just once before removing the handler
* @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.once = function once(topic, callback, scope) {
var handle = this.watch(topic, function () {
callback.apply(scope, arguments);
this.unwatch(handle);
}, this);
return handle;
};
/**
* 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 {
if (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.js - http://flams.github.com/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]) {
var transition = _states[name] = new Transition();
return 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(newEvent) {
var _transition = _transitions[newEvent];
if (_transition) {
_transition[0].apply(_transition[1], Tools.toArray(arguments).slice(1));
return _transition[2];
} else {
return false;
}
};
}
return StateMachineConstructor;
});
/**
* Emily.js - http://flams.github.com/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.js - http://flams.github.com/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(),
/**
* Saves the handles for the subscriptions of the computed properties
* @private
*/
_computed = [],
/**
* 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 by calling one of it's method
* When the modifications are done, it notifies on changes.
* If the function called doesn't alter the data, consider using proxy instead
* which is much, much faster.
* @param {String} func the name of the method
* @params {*} any number of params to be given to the func
* @returns the result of the method call
*/
this.alter = function alter(func) {
var apply,
previousData;
if (_data[func]) {
previousData = Tools.clone(_data);
apply = this.proxy.apply(this, arguments);
_notifyDiffs(previousData);
_storeObservable.notify("altered", _data, previousData);
return apply;
} else {
return false;
}
};
/**
* Proxy is similar to alter but doesn't trigger events.
* It's preferable to call proxy for functions that don't
* update the interal data source, like slice or filter.
* @param {String} func the name of the method
* @params {*} any number of params to be given to the func
* @returns the result of the method call
*/
this.proxy = function proxy(func) {
if (_data[func]) {
return _data[func].apply(_data, Array.prototype.slice.call(arguments, 1));
} else {
return false;
}
};
/**
* 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);
_storeObservable.notify("resetted", _data, previousData);
return true;
} else {
return false;
}
};
/**
* Compute a new property from other properties.
* The computed property will look exactly similar to any none
* computed property, it can be watched upon.
* @param {String} name the name of the computed property
* @param {Array} computeFrom a list of properties to compute from
* @param {Function} callback the callback to compute the property
* @param {Object} scope the scope in which to execute the callback
* @returns {Boolean} false if wrong params given to the function
*/
this.compute = function compute(name, computeFrom, callback, scope) {
var args = [];
if (typeof name == "string" &&
typeof computeFrom == "object" &&
typeof callback == "function" &&
!this.isCompute(name)) {
_computed[name] = [];
Tools.loop(computeFrom, function (property) {
_computed[name].push(this.watchValue(property, function () {
this.set(name, callback.call(scope));
}, this));
}, this);
this.set(name, callback.call(scope));
return true;
} else {
return false;
}
};
/**
* Remove a computed property
* @param {String} name the name of the computed to remove
* @returns {Boolean} true if the property is removed
*/
this.removeCompute = function removeCompute(name) {
if (this.isCompute(name)) {
Tools.loop(_computed[name], function (handle) {
this.unwatchValue(handle);
}, this);
this.del(name);
return true;
} else {
return false;
}
};
/**
* Tells if a property is a computed property
* @param {String} name the name of the property to test
* @returns {Boolean} true if it's a computed property
*/
this.isCompute = function isCompute(name) {
return !!_computed[name];
};
/**
* 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.js - http://flams.github.com/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 () {
if (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);
};
});
/**
* Emily.js - http://flams.github.com/emily/
* Copyright(c) 2012-2013 Olivier Scherrer <pode.fr@gmail.com>
* MIT Licensed
*/
define('Router',["Observable", "Store", "Tools"],
/**
* @class
* Routing allows for navigating in an application by defining routes.
*/
function Router(Observable, Store, Tools) {
return function RouterConstructor() {
/**
* The routes observable (the applications use it)
* @private
*/
var _routes = new Observable(),
/**
* The events observable (used by Routing)
* @private
*/
_events = new Observable(),
/**
* The routing history
* @private
*/
_history = new Store([]),
/**
* For navigating through the history, remembers the current position
* @private
*/
_currentPos = -1,
/**
* The depth of the history
* @private
*/
_maxHistory = 10;
/**
* Only for debugging
* @private
*/
this.getRoutesObservable = function getRoutesObservable() {
return _routes;
};
/**
* Only for debugging
* @private
*/
this.getEventsObservable = function getEventsObservable() {
return _events;
};
/**
* Set the maximum length of history
* As the user navigates through the application, the
* routeur keeps track of the history. Set the depth of the history
* depending on your need and the amount of memory that you can allocate it
* @param {Number} maxHistory the depth of history
* @returns {Boolean} true if maxHistory is equal or greater than 0
*/
this.setMaxHistory = function setMaxHistory(maxHistory) {
if (maxHistory >= 0) {
_maxHistory = maxHistory;
return true;
} else {
return false;
}
};
/**
* Get the current max history setting
* @returns {Number} the depth of history
*/
this.getMaxHistory = function getMaxHistory() {
return _maxHistory;
};
/**
* Set a new route
* @param {String} route the name of the route
* @param {Function} func the function to be execute when navigating to the route
* @param {Object} scope the scope in which to execute the function
* @returns a handle to remove the route
*/
this.set = function set() {
return _routes.watch.apply(_routes, arguments);
};
/**
* Remove a route
* @param {Object} handle the handle provided by the set method
* @returns true if successfully removed
*/
this.unset = function unset(handle) {
return _routes.unwatch(handle);
};
/**
* Navigate to a route
* @param {String} route the route to navigate to
* @param {*} *params
* @returns
*/
this.navigate = function get(route, params) {
if (this.load.apply(this, arguments)) {
// Before adding a new route to the history, we must clear the forward history
_history.proxy("splice", _currentPos +1, _history.count());
_history.proxy("push", Tools.toArray(arguments));
this.ensureMaxHistory(_history);
_currentPos = _history.count() -1;
return true;
} else {
return false;
}
};
/**
* Ensure that history doesn't grow bigger than the max history setting
* @param {Store} history the history store
* @private
*/
this.ensureMaxHistory = function ensureMaxHistory(history) {
var count = history.count(),
max = this.getMaxHistory(),
excess = count - max;
if (excess > 0) {
history.proxy("splice", 0, excess);
}
};
/**
* Actually loads the route
* @private
*/
this.load = function load() {
var copy = Tools.toArray(arguments);
if (_routes.notify.apply(_routes, copy)) {
copy.unshift("route");
_events.notify.apply(_events, copy);
return true;
} else {
return false;
}
};
/**
* Watch for route changes
* @param {Function} func the func to execute when the route changes
* @param {Object} scope the scope in which to execute the function
* @returns {Object} the handle to unwatch for route changes
*/
this.watch = function watch(func, scope) {
return _events.watch("route", func, scope);
};
/**
* Unwatch routes changes
* @param {Object} handle the handle was returned by the watch function
* @returns true if unwatch
*/
this.unwatch = function unwatch(handle) {
return _events.unwatch(handle);
};
/**
* Get the history store, for debugging only
* @private
*/
this.getHistoryStore = function getHistoryStore() {
return _history;
};
/**
* Get the current length of history
* @returns {Number} the length of history
*/
this.getHistoryCount = function getHistoryCount() {
return _history.count();
};
/**
* Flush the entire history
*/
this.clearHistory = function clearHistory() {
_history.reset([]);
};
/**
* Go back and forth in the history
* @param {Number} nb the amount of history to rewind/forward
* @returns true if history exists
*/
this.go = function go(nb) {
var history = _history.get(_currentPos + nb);
if (history) {
_currentPos += nb;
this.load.apply(this, history);
return true;
} else {
return false;
}
};
/**
* Go back in the history, short for go(-1)
* @returns
*/
this.back = function back() {
return this.go(-1);
};
/**
* Go forward in the history, short for go(1)
* @returns
*/
this.forward = function forward() {
return this.go(1);
};
};
});
\ No newline at end of file
/**
* @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
* @private
*/
_observers = {};
/**
* Exposed for debugging purpose
* @private
*/
this.observers = _observers;
function _removeObserversForId(id) {
if (_observers[id]) {
_observers[id].forEach(function (handler) {
_model.unwatchValue(handler);
});
delete _observers[id];
}
}
/**
* 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);
if (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 = {};
/**
* Set the start limit
* @private
* @param {Number} start the value to start rendering the items from
* @returns the value
*/
this.setStart = function setStart(start) {
_start = parseInt(start, 10);
return _start;
};
/**
* 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) {
_nb = nb == "*" ? nb : parseInt(nb, 10);
return _nb;
};
/**
* 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[id]) {
next = this.getNextItem(id);
node = this.create(id);
if (node) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
if (next) {
_rootNode.insertBefore(node, next);
} else {
_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) {
var keys = Object.keys(this.items).map(function (string) {
return Number(string);
}),
closest = Tools.closestGreater(id, keys),
closestId = keys[closest];
// Only return if different
if (closestId != id) {
return this.items[closestId];
} else {
return;
}
};
/**
* 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[id];
if (item) {
_rootNode.removeChild(item);
delete this.items[id];
_removeObserversForId(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[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
Tools.loop(this.items, function (value, idx) {
// If an item is out of the boundary
idx = Number(idx);
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
_removeObserversForId(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} DOMfrom
* @returns true if valid form
*/
this.form = function form(DOMform) {
if (DOMform && DOMform.nodeName == "FORM") {
var that = this;
DOMform.addEventListener("submit", function (event) {
Tools.toArray(DOMform.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 new 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 new 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, DOMplace, beforeNode) {
if (DOMplace) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
if (beforeNode) {
DOMplace.insertBefore(UI.dom, beforeNode);
} else {
DOMplace.appendChild(UI.dom);
}
// Also save the new place, so next renderings
// will be made inside it
_currentPlace = DOMplace;
}
},
/**
* 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 () {
if (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 () {
if (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('Stack',['Tools'],
/**
* @class
* A Stack is a tool for managing DOM elements as groups. Within a group, dom elements
* can be added, removed, moved around. The group can be moved to another parent node
* while keeping the DOM elements in the same order, excluding the parent dom elements's
* children that are not in the Stack.
*/
function Stack() {
var Tools = require("Tools");
return function StackConstructor($parent) {
/**
* The parent DOM element is a documentFragment by default
* @private
*/
var _parent = document.createDocumentFragment(),
/**
* The place where the dom elements hide
* @private
*/
_hidePlace = document.createElement("div"),
/**
* The list of dom elements that are part of the stack
* Helps for excluding elements that are not part of it
* @private
*/
_childNodes = [],
_lastTransit = null;
/**
* Add a DOM element to the stack. It will be appended.
* @param {HTMLElement} dom the DOM element to add
* @returns {HTMLElement} dom
*/
this.add = function add(dom) {
if (!this.has(dom) && dom instanceof HTMLElement) {
_parent.appendChild(dom);
_childNodes.push(dom);
return dom;
} else {
return false;
}
};
/**
* Remove a DOM element from the stack.
* @param {HTMLElement} dom the DOM element to remove
* @returns {HTMLElement} dom
*/
this.remove = function remove(dom) {
var index;
if (this.has(dom)) {
index = _childNodes.indexOf(dom);
_parent.removeChild(dom);
_childNodes.splice(index, 1);
return dom;
} else {
return false;
}
};
/**
* Place a stack by appending its DOM elements to a new parent
* @param {HTMLElement} newParentDom the new DOM element to append the stack to
* @returns {HTMLElement} newParentDom
*/
this.place = function place(newParentDom) {
if (newParentDom instanceof HTMLElement) {
[].slice.call(_parent.childNodes).forEach(function (childDom) {
if (this.has(childDom)) {
newParentDom.appendChild(childDom);
}
}, this);
return this._setParent(newParentDom);
} else {
return false;
}
};
/**
* Move an element up in the stack
* @param {HTMLElement} dom the dom element to move up
* @returns {HTMLElement} dom
*/
this.up = function up(dom) {
if (this.has(dom)) {
var domPosition = this.getPosition(dom);
this.move(dom, domPosition + 1);
return dom;
} else {
return false;
}
};
/**
* Move an element down in the stack
* @param {HTMLElement} dom the dom element to move down
* @returns {HTMLElement} dom
*/
this.down = function down(dom) {
if (this.has(dom)) {
var domPosition = this.getPosition(dom);
this.move(dom, domPosition - 1);
return dom;
} else {
return false;
}
};
/**
* Move an element that is already in the stack to a new position
* @param {HTMLElement} dom the dom element to move
* @param {Number} position the position to which to move the DOM element
* @returns {HTMLElement} dom
*/
this.move = function move(dom, position) {
if (this.has(dom)) {
var domIndex = _childNodes.indexOf(dom);
_childNodes.splice(domIndex, 1);
// Preventing a bug in IE when insertBefore is not given a valid
// second argument
var nextElement = getNextElementInDom(position);
if (nextElement) {
_parent.insertBefore(dom, nextElement);
} else {
_parent.appendChild(dom);
}
_childNodes.splice(position, 0, dom);
return dom;
} else {
return false;
}
};
function getNextElementInDom(position) {
if (position >= _childNodes.length) {
return;
}
var nextElement = _childNodes[position];
if (Tools.toArray(_parent.childNodes).indexOf(nextElement) == -1) {
return getNextElementInDom(position +1);
} else {
return nextElement;
}
}
/**
* Insert a new element at a specific position in the stack
* @param {HTMLElement} dom the dom element to insert
* @param {Number} position the position to which to insert the DOM element
* @returns {HTMLElement} dom
*/
this.insert = function insert(dom, position) {
if (!this.has(dom) && dom instanceof HTMLElement) {
_childNodes.splice(position, 0, dom);
_parent.insertBefore(dom, _parent.childNodes[position]);
return dom;
} else {
return false;
}
};
/**
* Get the position of an element in the stack
* @param {HTMLElement} dom the dom to get the position from
* @returns {HTMLElement} dom
*/
this.getPosition = function getPosition(dom) {
return _childNodes.indexOf(dom);
};
/**
* Count the number of elements in a stack
* @returns {Number} the number of items
*/
this.count = function count() {
return _parent.childNodes.length;
};
/**
* Tells if a DOM element is in the stack
* @param {HTMLElement} dom the dom to tell if its in the stack
* @returns {HTMLElement} dom
*/
this.has = function has(childDom) {
return this.getPosition(childDom) >= 0;
};
/**
* Hide a dom element that was previously added to the stack
* It will be taken out of the dom until displayed again
* @param {HTMLElement} dom the dom to hide
* @return {boolean} if dom element is in the stack
*/
this.hide = function hide(dom) {
if (this.has(dom)) {
_hidePlace.appendChild(dom);
return true;
} else {
return false;
}
};
/**
* Show a dom element that was previously hidden
* It will be added back to the dom
* @param {HTMLElement} dom the dom to show
* @return {boolean} if dom element is current hidden
*/
this.show = function show(dom) {
if (this.has(dom) && dom.parentNode === _hidePlace) {
this.move(dom, _childNodes.indexOf(dom));
return true;
} else {
return false;
}
};
/**
* Helper function for hiding all the dom elements
*/
this.hideAll = function hideAll() {
_childNodes.forEach(this.hide, this);
};
/**
* Helper function for showing all the dom elements
*/
this.showAll = function showAll() {
_childNodes.forEach(this.show, this);
};
/**
* Get the parent node that a stack is currently attached to
* @returns {HTMLElement} parent node
*/
this.getParent = function _getParent() {
return _parent;
};
/**
* Set the parent element (without appending the stacks dom elements to)
* @private
*/
this._setParent = function _setParent(parent) {
if (parent instanceof HTMLElement) {
_parent = parent;
return _parent;
} else {
return false;
}
};
/**
* Get the place where the DOM elements are hidden
* @private
*/
this.getHidePlace = function getHidePlace() {
return _hidePlace;
};
/**
* Set the place where the DOM elements are hidden
* @private
*/
this.setHidePlace = function setHidePlace(hidePlace) {
if (hidePlace instanceof HTMLElement) {
_hidePlace = hidePlace;
return true;
} else {
return false;
}
};
/**
* Get the last dom element that the stack transitted to
* @returns {HTMLElement} the last dom element
*/
this.getLastTransit = function getLastTransit() {
return _lastTransit;
};
/**
* Transit between views, will show the new one and hide the previous
* element that the stack transitted to, if any.
* @param {HTMLElement} dom the element to transit to
* @returns {Boolean} false if the element can't be shown
*/
this.transit = function transit(dom) {
if (_lastTransit) {
this.hide(_lastTransit);
}
if (this.show(dom)) {
_lastTransit = dom;
return true;
} else {
return false;
}
};
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('LocationRouter',["Router", "Tools"],
/**
* @class
* A locationRouter is a router which navigates to the route defined in the URL and updates this URL
* while navigating. It's a subtype of Emily's Router
*/
function LocationRouter(Router, Tools) {
function LocationRouterConstructor() {
/**
* The handle on the watch
* @private
*/
var _watchHandle,
/**
* The default route to navigate to when nothing is supplied in the url
* @private
*/
_defaultRoute = "",
/**
* The last route that was navigated to
* @private
*/
_lastRoute = window.location.hash;
/**
* Navigates to the current hash or to the default route if none is supplied in the url
* @private
*/
/*jshint validthis:true*/
function doNavigate() {
if (window.location.hash) {
var parsedHash = this.parse(window.location.hash);
this.navigate.apply(this, parsedHash);
} else {
this.navigate(_defaultRoute);
}
}
/**
* Set the default route to navigate to when nothing is defined in the url
* @param {String} defaultRoute the defaultRoute to navigate to
* @returns {Boolean} true if it's not an empty string
*/
this.setDefaultRoute = function setDefaultRoute(defaultRoute) {
if (defaultRoute && typeof defaultRoute == "string") {
_defaultRoute = defaultRoute;
return true;
} else {
return false;
}
};
/**
* Get the currently set default route
* @returns {String} the default route
*/
this.getDefaultRoute = function getDefaultRoute() {
return _defaultRoute;
};
/**
* The function that parses the url to determine the route to navigate to.
* It has a default behavior explained below, but can be overriden as long as
* it has the same contract.
* @param {String} hash the hash coming from window.location.has
* @returns {Array} has to return an array with the list of arguments to call
* navigate with. The first item of the array must be the name of the route.
*
* Example: #album/holiday/2013
* will navigate to the route "album" and give two arguments "holiday" and "2013"
*/
this.parse = function parse(hash) {
return hash.split("#").pop().split("/");
};
/**
* The function that converts, or serialises the route and its arguments to a valid URL.
* It has a default behavior below, but can be overriden as long as it has the same contract.
* @param {Array} args the list of arguments to serialize
* @returns {String} the serialized arguments to add to the url hashmark
*
* Example:
* ["album", "holiday", "2013"];
* will give "album/holiday/2013"
*
*/
this.toUrl = function toUrl(args) {
return args.join("/");
};
/**
* When all the routes and handlers have been defined, start the location router
* so it parses the URL and navigates to the corresponding route.
* It will also start listening to route changes and hashmark changes to navigate.
* While navigating, the hashmark itself will also change to reflect the current route state
*/
this.start = function start(defaultRoute) {
this.setDefaultRoute(defaultRoute);
doNavigate.call(this);
this.bindOnHashChange();
this.bindOnRouteChange();
};
/**
* Remove the events handler for cleaning.
*/
this.destroy = function destroy() {
this.unwatch(_watchHandle);
window.removeEventListener("hashchange", this.boundOnHashChange, true);
};
/**
* Parse the hash and navigate to the corresponding url
* @private
*/
this.onHashChange = function onHashChange() {
if (window.location.hash != _lastRoute) {
doNavigate.call(this);
}
};
/**
* The bound version of onHashChange for add/removeEventListener
* @private
*/
this.boundOnHashChange = this.onHashChange.bind(this);
/**
* Add an event listener to hashchange to navigate to the corresponding route
* when it changes
* @private
*/
this.bindOnHashChange = function bindOnHashChange() {
window.addEventListener("hashchange", this.boundOnHashChange, true);
};
/**
* Watch route change events from the router to update the location
* @private
*/
this.bindOnRouteChange = function bindOnRouteChange() {
_watchHandle = this.watch(this.onRouteChange, this);
};
/**
* The handler for when the route changes
* It updates the location
* @private
*/
this.onRouteChange = function onRouteChange() {
window.location.hash = this.toUrl(Tools.toArray(arguments));
_lastRoute = window.location.hash;
};
this.getLastRoute = function getLastRoute() {
return _lastRoute;
};
}
return function LocationRouterFactory() {
LocationRouterConstructor.prototype = new Router();
return new LocationRouterConstructor();
};
});
/**
* 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) {
"use strict";
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
* @private
*/
_observers = {};
/**
* Exposed for debugging purpose
* @private
*/
this.observers = _observers;
function _removeObserversForId(id) {
if (_observers[id]) {
_observers[id].forEach(function (handler) {
_model.unwatchValue(handler);
});
delete _observers[id];
}
}
/**
* 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);
if (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 = {};
/**
* Set the start limit
* @private
* @param {Number} start the value to start rendering the items from
* @returns the value
*/
this.setStart = function setStart(start) {
_start = parseInt(start, 10);
return _start;
};
/**
* 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) {
_nb = nb == "*" ? nb : parseInt(nb, 10);
return _nb;
};
/**
* 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[id]) {
next = this.getNextItem(id);
node = this.create(id);
if (node) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
if (next) {
_rootNode.insertBefore(node, next);
} else {
_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) {
var keys = Object.keys(this.items).map(function (string) {
return Number(string);
}),
closest = Tools.closestGreater(id, keys),
closestId = keys[closest];
// Only return if different
if (closestId != id) {
return this.items[closestId];
} else {
return;
}
};
/**
* 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[id];
if (item) {
_rootNode.removeChild(item);
delete this.items[id];
_removeObserversForId(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[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
Tools.loop(this.items, function (value, idx) {
// If an item is out of the boundary
idx = Number(idx);
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
_removeObserversForId(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} DOMfrom
* @returns true if valid form
*/
this.form = function form(DOMform) {
if (DOMform && DOMform.nodeName == "FORM") {
var that = this;
DOMform.addEventListener("submit", function (event) {
Tools.toArray(DOMform.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(["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) {
"use strict";
/**
* 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) {
"use strict";
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) {
"use strict";
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 new 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 new 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, DOMplace, beforeNode) {
if (DOMplace) {
// IE (until 9) apparently fails to appendChild when insertBefore's second argument is null, hence this.
if (beforeNode) {
DOMplace.insertBefore(UI.dom, beforeNode);
} else {
DOMplace.appendChild(UI.dom);
}
// Also save the new place, so next renderings
// will be made inside it
_currentPlace = DOMplace;
}
},
/**
* 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;
};
};
});
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.16 Copyright (c) 2010-2015, 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.16',
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' && typeof navigator !== 'undefined' && window.document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
function defaultOnError(err) {
throw err;
}
//Allow getting a global that is 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 an 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: {},
bundles: {},
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 = {},
bundlesMap = {},
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; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} 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 pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
baseParts = (baseName && baseName.split('/')),
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//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);
}
trimDots(name);
name = name.join('/');
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: 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 outerLoop;
}
}
}
}
//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('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
}
function removeScript(name) {
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) {
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
//Custom require that does not do map translation, since
//ID is "absolute", already mapped/resolved.
context.makeRequire(null, {
skipMap: true
})([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 {
// If nested plugin references, then do not try to
// normalize, as it will not normalize correctly. This
// places a restriction on resourceIds, and the longer
// term solution is not to normalize until plugins are
// loaded and all normalizations to allow for async
// loading of a loader plugin. But for now, fixes the
// common uses. Details in #1131
normalizedName = name.indexOf('!') === -1 ?
normalize(name, parentName, applyMap) :
name;
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
mod = getModule(depMap);
if (mod.error && name === 'error') {
fn(mod.error);
} else {
mod.on(name, fn);
}
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length, 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 (defined[mod.map.id] = 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 getOwn(config.config, mod.map.id) || {};
},
exports: mod.exports || (mod.exports = {})
});
}
}
};
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 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) {
var map = mod.map,
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
this.fetch();
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error. However,
//only do it for define()'d modules. require
//errbacks should not be called for failures in
//their callbacks (#699). However if a global
//onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (this.map.isDefine && exports === undefined) {
cjsModule = this.module;
if (cjsModule) {
exports = cjsModule.exports;
} else if (this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = this.map.isDefine ? [this.map.id] : null;
err.requireType = this.map.isDefine ? 'define' : 'require';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
req.onResourceLoad(context, this.map, this.depMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
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;
}
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', bind(this, this.errback));
} else if (this.events.error) {
// No direct errback on this module, but something
// else is listening for errors, so be sure to
// propagate the error correctly.
on(depMap, 'error', bind(this, function(err) {
this.emit('error', err);
}));
}
}
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 since they require special processing,
//they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim
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, name;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Save pointer to main module ID for pkg 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.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
//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);
removeScript(id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function(args, i) {
if(args[0] === id) {
defQueue.splice(i, 1);
}
});
if (mod) {
//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 overridden 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, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just
//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;
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('/');
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;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callback function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
return node;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = req.createNode(config, moduleName, url);
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation that a build has been done so that
//only one script needs to be loaded anyway. This may need to be
//reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser && !cfg.skipDataMain) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = dataMain;
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this));
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"private": true,
"dependencies": {
"olives": "^1.6.0",
"emily": "^1.8.1",
"requirejs": "^2.1.5",
"todomvc-common": "^1.0.1",
"todomvc-app-css": "^1.0.1"
"emily": "^3.0.3",
"olives": "^3.0.5",
"todomvc-app-css": "^1.0.1",
"todomvc-common": "^1.0.1"
},
"scripts": {
"build": "browserify ./js/app.js -o olives-todo.js",
"watch": "watchify ./js/app.js -o olives-todo.js"
},
"devDependencies": {
"browserify": "^9.0.4",
"watchify": "^3.1.0"
}
}
......@@ -16,3 +16,23 @@ Here are some links you may find helpful:
* [Olives.js on GitHub](https://github.com/flams/olives)
_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
## Building the app
As this application is using node's module system, `browserify` or similar tool is required to package it for the browser. To build the app, simply do:
```
npm run build
```
To automatically rebuild the application as you make changes to the source code, you can do:
```
npm run watch
```
Make sure that you've installed all the dependencies first:
```
npm install
```
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