code
stringlengths 2
1.05M
|
---|
//DO NOT DELETE THIS, this is in use...
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.MacroContainerController",
function($scope, dialogService, entityResource, macroService){
$scope.renderModel = [];
$scope.allowOpenButton = true;
$scope.allowRemoveButton = true;
$scope.sortableOptions = {};
if($scope.model.value){
var macros = $scope.model.value.split('>');
angular.forEach(macros, function(syntax, key){
if(syntax && syntax.length > 10){
//re-add the char we split on
syntax = syntax + ">";
var parsed = macroService.parseMacroSyntax(syntax);
if(!parsed){
parsed = {};
}
parsed.syntax = syntax;
collectDetails(parsed);
$scope.renderModel.push(parsed);
setSortingState($scope.renderModel);
}
});
}
function collectDetails(macro){
macro.details = "";
macro.icon = "icon-settings-alt";
if(macro.macroParamsDictionary){
angular.forEach((macro.macroParamsDictionary), function(value, key){
macro.details += key + ": " + value + " ";
});
}
}
function openDialog(index){
var dialogData = {
allowedMacros: $scope.model.config.allowed
};
if(index !== null && $scope.renderModel[index]) {
var macro = $scope.renderModel[index];
dialogData["macroData"] = macro;
}
$scope.macroPickerOverlay = {};
$scope.macroPickerOverlay.view = "macropicker";
$scope.macroPickerOverlay.dialogData = dialogData;
$scope.macroPickerOverlay.show = true;
$scope.macroPickerOverlay.submit = function(model) {
var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine);
collectDetails(macroObject);
//update the raw syntax and the list...
if(index !== null && $scope.renderModel[index]) {
$scope.renderModel[index] = macroObject;
} else {
$scope.renderModel.push(macroObject);
}
setSortingState($scope.renderModel);
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
$scope.macroPickerOverlay.close = function(oldModel) {
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
}
$scope.edit =function(index){
openDialog(index);
};
$scope.add = function () {
if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) {
//cannot add more than the max
return;
}
openDialog();
};
$scope.remove =function(index){
$scope.renderModel.splice(index, 1);
setSortingState($scope.renderModel);
};
$scope.clear = function() {
$scope.model.value = "";
$scope.renderModel = [];
};
var unsubscribe = $scope.$on("formSubmitting", function (ev, args) {
var syntax = [];
angular.forEach($scope.renderModel, function(value, key){
syntax.push(value.syntax);
});
$scope.model.value = syntax.join("");
});
//when the scope is destroyed we need to unsubscribe
$scope.$on('$destroy', function () {
unsubscribe();
});
function trim(str, chr) {
var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g');
return str.replace(rgxtrim, '');
}
function setSortingState(items) {
// disable sorting if the list only consist of one item
if(items.length > 1) {
$scope.sortableOptions.disabled = false;
} else {
$scope.sortableOptions.disabled = true;
}
}
});
|
/*!
* Copyright (c) 2015, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var vows = require('vows');
var assert = require('assert');
var async = require('async');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
var CookieJar = tough.CookieJar;
var atNow = Date.now();
function at(offset) {
return {now: new Date(atNow + offset)};
}
vows
.describe('Regression tests')
.addBatch({
"Issue 1": {
topic: function () {
var cj = new CookieJar();
cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) {
this.callback(err, {cj: cj, cookie: cookie});
}.bind(this));
},
"stored a cookie": function (t) {
assert.ok(t.cookie);
},
"getting it back": {
topic: function (t) {
t.cj.getCookies('http://domain/some/path/file', function (err, cookies) {
this.callback(err, {cj: t.cj, cookies: cookies || []});
}.bind(this));
},
"got one cookie": function (t) {
assert.lengthOf(t.cookies, 1);
},
"it's the right one": function (t) {
var c = t.cookies[0];
assert.equal(c.key, 'hello');
assert.equal(c.value, 'world');
}
}
}
})
.addBatch({
"trailing semi-colon set into cj": {
topic: function () {
var cb = this.callback;
var cj = new CookieJar();
var ex = 'http://www.example.com';
var tasks = [];
tasks.push(function (next) {
cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next);
});
tasks.push(function (next) {
cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next);
});
async.parallel(tasks, function (err, cookies) {
cb(null, {
cj: cj,
cookies: cookies
});
});
},
"check number of cookies": function (t) {
assert.lengthOf(t.cookies, 2, "didn't set");
},
"check *broken_path* was set properly": function (t) {
assert.equal(t.cookies[0].key, "broken_path");
assert.equal(t.cookies[0].value, "testme");
assert.equal(t.cookies[0].path, "/");
},
"check *b* was set properly": function (t) {
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
},
"retrieve the cookie": {
topic: function (t) {
var cb = this.callback;
t.cj.getCookies('http://www.example.com', {}, function (err, cookies) {
t.cookies = cookies;
cb(err, t);
});
},
"get the cookie": function (t) {
assert.lengthOf(t.cookies, 2);
assert.equal(t.cookies[0].key, 'broken_path');
assert.equal(t.cookies[0].value, 'testme');
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
}
}
}
})
.addBatch({
"tough-cookie throws exception on malformed URI (GH-32)": {
topic: function () {
var url = "http://www.example.com/?test=100%";
var cj = new CookieJar();
cj.setCookieSync("Test=Test", url);
return cj.getCookieStringSync(url);
},
"cookies are set": function (cookieStr) {
assert.strictEqual(cookieStr, "Test=Test");
}
}
})
.export(module);
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Promise = require('bluebird');
var MongoClient = require('mongodb');
function defaultSerializeFunction(session) {
// Copy each property of the session to a new object
var obj = {};
var prop = void 0;
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
} else {
obj[prop] = session[prop];
}
}
return obj;
}
function computeTransformFunctions(options, defaultStringify) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || function (x) {
return x;
}
};
}
if (options.stringify === false || defaultStringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: function (x) {
return x;
}
};
}
if (options.stringify === true || defaultStringify === true) {
return {
serialize: JSON.stringify,
unserialize: JSON.parse
};
}
}
module.exports = function connectMongo(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
var MongoStore = function (_Store) {
_inherits(MongoStore, _Store);
function MongoStore(options) {
_classCallCheck(this, MongoStore);
options = options || {};
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
var _ret;
return _ret = new MemoryStore(), _possibleConstructorReturn(_this, _ret);
}
/* Options */
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MongoStore).call(this, options));
_this.ttl = options.ttl || 1209600; // 14 days
_this.collectionName = options.collection || 'sessions';
_this.autoRemove = options.autoRemove || 'native';
_this.autoRemoveInterval = options.autoRemoveInterval || 10;
_this.transformFunctions = computeTransformFunctions(options, true);
_this.options = options;
_this.changeState('init');
var newConnectionCallback = function (err, db) {
if (err) {
_this.connectionFailed(err);
} else {
_this.handleNewConnectionAsync(db);
}
};
if (options.url) {
// New native connection using url + mongoOptions
MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback);
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
_this.handleNewConnectionAsync(options.mongooseConnection.db);
} else {
options.mongooseConnection.once('open', function () {
return _this.handleNewConnectionAsync(options.mongooseConnection.db);
});
}
} else if (options.db && options.db.listCollections) {
// Re-use existing or upcoming native connection
if (options.db.openCalled || options.db.openCalled === undefined) {
// openCalled is undefined in [email protected]
_this.handleNewConnectionAsync(options.db);
} else {
options.db.open(newConnectionCallback);
}
} else if (options.dbPromise) {
options.dbPromise.then(function (db) {
return _this.handleNewConnectionAsync(db);
}).catch(function (err) {
return _this.connectionFailed(err);
});
} else {
throw new Error('Connection strategy not found');
}
_this.changeState('connecting');
return _this;
}
_createClass(MongoStore, [{
key: 'connectionFailed',
value: function connectionFailed(err) {
this.changeState('disconnected');
throw err;
}
}, {
key: 'handleNewConnectionAsync',
value: function handleNewConnectionAsync(db) {
var _this2 = this;
this.db = db;
return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () {
return _this2.changeState('connected');
});
}
}, {
key: 'setAutoRemoveAsync',
value: function setAutoRemoveAsync() {
var _this3 = this;
switch (this.autoRemove) {
case 'native':
return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 });
case 'interval':
var removeQuery = { expires: { $lt: new Date() } };
this.timer = setInterval(function () {
return _this3.collection.remove(removeQuery, { w: 0 });
}, this.autoRemoveInterval * 1000 * 60);
this.timer.unref();
return Promise.resolve();
default:
return Promise.resolve();
}
}
}, {
key: 'changeState',
value: function changeState(newState) {
if (newState !== this.state) {
this.state = newState;
this.emit(newState);
}
}
}, {
key: 'setCollection',
value: function setCollection(collection) {
if (this.timer) {
clearInterval(this.timer);
}
this.collectionReadyPromise = undefined;
this.collection = collection;
// Promisify used collection methods
['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) {
collection[method + 'Async'] = Promise.promisify(collection[method], collection);
});
return this;
}
}, {
key: 'collectionReady',
value: function collectionReady() {
var _this4 = this;
var promise = this.collectionReadyPromise;
if (!promise) {
promise = new Promise(function (resolve, reject) {
switch (_this4.state) {
case 'connected':
resolve(_this4.collection);
break;
case 'connecting':
_this4.once('connected', function () {
return resolve(_this4.collection);
});
break;
case 'disconnected':
reject(new Error('Not connected'));
break;
}
});
this.collectionReadyPromise = promise;
}
return promise;
}
}, {
key: 'computeStorageId',
value: function computeStorageId(sessionId) {
if (this.options.transformId && typeof this.options.transformId === 'function') {
return this.options.transformId(sessionId);
} else {
return sessionId;
}
}
/* Public API */
}, {
key: 'get',
value: function get(sid, callback) {
var _this5 = this;
return this.collectionReady().then(function (collection) {
return collection.findOneAsync({
_id: _this5.computeStorageId(sid),
$or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }]
});
}).then(function (session) {
if (session) {
var s = _this5.transformFunctions.unserialize(session.session);
if (_this5.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified;
}
_this5.emit('touch', sid);
return s;
}
}).nodeify(callback);
}
}, {
key: 'set',
value: function set(sid, session, callback) {
var _this6 = this;
// removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified;
}
var s;
try {
s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) };
} catch (err) {
return callback(err);
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires);
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000);
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date();
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true });
}).then(function () {
return _this6.emit('set', sid);
}).nodeify(callback);
}
}, {
key: 'touch',
value: function touch(sid, session, callback) {
var _this7 = this;
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
// if the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
var timeElapsed = currentDate.getTime() - session.lastModified;
if (timeElapsed < touchAfter) {
return callback();
} else {
updateFields.lastModified = currentDate;
}
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires);
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000);
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields });
}).then(function (result) {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch');
} else {
_this7.emit('touch', sid);
}
}).nodeify(callback);
}
}, {
key: 'destroy',
value: function destroy(sid, callback) {
var _this8 = this;
return this.collectionReady().then(function (collection) {
return collection.removeAsync({ _id: _this8.computeStorageId(sid) });
}).then(function () {
return _this8.emit('destroy', sid);
}).nodeify(callback);
}
}, {
key: 'length',
value: function length(callback) {
return this.collectionReady().then(function (collection) {
return collection.countAsync({});
}).nodeify(callback);
}
}, {
key: 'clear',
value: function clear(callback) {
return this.collectionReady().then(function (collection) {
return collection.dropAsync();
}).nodeify(callback);
}
}, {
key: 'close',
value: function close() {
if (this.db) {
this.db.close();
}
}
}]);
return MongoStore;
}(Store);
return MongoStore;
}; |
import * as RSVP from 'rsvp';
import { backburner, _rsvpErrorQueue } from '@ember/runloop';
import { getDispatchOverride } from '@ember/-internals/error-handling';
import { assert } from '@ember/debug';
RSVP.configure('async', (callback, promise) => {
backburner.schedule('actions', null, callback, promise);
});
RSVP.configure('after', cb => {
backburner.schedule(_rsvpErrorQueue, null, cb);
});
RSVP.on('error', onerrorDefault);
export function onerrorDefault(reason) {
let error = errorFor(reason);
if (error) {
let overrideDispatch = getDispatchOverride();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
if (reason.errorThrown) {
return unwrapErrorThrown(reason);
}
if (reason.name === 'UnrecognizedURLError') {
assert(`The URL '${reason.message}' did not match any routes in your application`, false);
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
let error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '__reason_with_error_thrown__', {
value: reason,
enumerable: false,
});
return error;
}
export default RSVP;
|
/**
@module ember
@submodule ember-runtime
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { get } from 'ember-metal/property_get';
import { deprecateProperty } from 'ember-metal/deprecate_property';
/**
`Ember.ActionHandler` is available on some familiar classes including
`Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`.
(Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
and `Ember.Route` and available to the above classes through
inheritance.)
@class ActionHandler
@namespace Ember
@private
*/
var ActionHandler = Mixin.create({
mergedProperties: ['actions'],
/**
The collection of functions, keyed by name, available on this
`ActionHandler` as action targets.
These functions will be invoked when a matching `{{action}}` is triggered
from within a template and the application's current route is this route.
Actions can also be invoked from other parts of your application
via `ActionHandler#send`.
The `actions` hash will inherit action handlers from
the `actions` hash defined on extended parent classes
or mixins rather than just replace the entire hash, e.g.:
```js
App.CanDisplayBanner = Ember.Mixin.create({
actions: {
displayBanner: function(msg) {
// ...
}
}
});
App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, {
actions: {
playMusic: function() {
// ...
}
}
});
// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');
```
Within a Controller, Route, View or Component's action handler,
the value of the `this` context is the Controller, Route, View or
Component object:
```js
App.SongRoute = Ember.Route.extend({
actions: {
myAction: function() {
this.controllerFor("song");
this.transitionTo("other.route");
...
}
}
});
```
It is also possible to call `this._super.apply(this, arguments)` from within an
action handler if it overrides a handler defined on a parent
class or mixin:
Take for example the following routes:
```js
App.DebugRoute = Ember.Mixin.create({
actions: {
debugRouteInformation: function() {
console.debug("trololo");
}
}
});
App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, {
actions: {
debugRouteInformation: function() {
// also call the debugRouteInformation of mixed in App.DebugRoute
this._super.apply(this, arguments);
// show additional annoyance
window.alert(...);
}
}
});
```
## Bubbling
By default, an action will stop bubbling once a handler defined
on the `actions` hash handles it. To continue bubbling the action,
you must return `true` from the handler:
```js
App.Router.map(function() {
this.route("album", function() {
this.route("song");
});
});
App.AlbumRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
}
}
});
App.AlbumSongRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
// ...
if (actionShouldAlsoBeTriggeredOnParentRoute) {
return true;
}
}
}
});
```
@property actions
@type Object
@default null
@public
*/
/**
Triggers a named action on the `ActionHandler`. Any parameters
supplied after the `actionName` string will be passed as arguments
to the action target function.
If the `ActionHandler` has its `target` property set, actions may
bubble to the `target`. Bubbling happens when an `actionName` can
not be found in the `ActionHandler`'s `actions` hash or if the
action target function returns `true`.
Example
```js
App.WelcomeRoute = Ember.Route.extend({
actions: {
playTheme: function() {
this.send('playMusic', 'theme.mp3');
},
playMusic: function(track) {
// ...
}
}
});
```
@method send
@param {String} actionName The action to trigger
@param {*} context a context to send with the action
@public
*/
send(actionName, ...args) {
var target;
if (this.actions && this.actions[actionName]) {
var shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) { return; }
}
if (target = get(this, 'target')) {
Ember.assert('The `target` for ' + this + ' (' + target +
') does not have a `send` method', typeof target.send === 'function');
target.send(...arguments);
}
}
});
export default ActionHandler;
export function deprecateUnderscoreActions(factory) {
deprecateProperty(factory.prototype, '_actions', 'actions', {
id: 'ember-runtime.action-handler-_actions', until: '3.0.0'
});
}
|
"use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i==23) {
uuid[i] = '-';
}
else if (i==14) {
uuid[i] = '4';
}
else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
exports.in_array = function (item, array) {
return (array.indexOf(item) != -1);
};
exports.sort_keys = function (obj) {
return Object.keys(obj).sort();
};
exports.uniq = function (arr) {
var out = [];
var o = 0;
for (var i=0,l=arr.length; i < l; i++) {
if (out.length === 0) {
out.push(arr[i]);
}
else if (out[o] != arr[i]) {
out.push(arr[i]);
o++;
}
}
return out;
}
exports.ISODate = function (d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function _pad (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) +
' ' + d.toString().match(/\sGMT([+-]\d+)/)[1];
}
exports.decode_qp = function (line) {
line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n");
if (! /=/.test(line)) {
// this may be a pointless optimisation...
return new Buffer(line);
}
line = line.replace(/=\n/mg, '');
var buf = new Buffer(line.length);
var pos = 0;
for (var i=0,l=line.length; i < l; i++) {
if (line[i] === '=' &&
/=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) {
i++;
buf[pos] = parseInt(line[i] + line[i+1], 16);
i++;
}
else {
buf[pos] = line.charCodeAt(i);
}
pos++;
}
return buf.slice(0, pos);
}
function _char_to_qp (ch) {
return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2);
}
// Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code.
exports.encode_qp = function (str) {
str = str.replace(/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) {
return _char_to_qp(p1);
}).replace(/([ \t]+)$/gm, function (orig, p1) {
return p1.split('').map(_char_to_qp).join('');
});
// Now shorten lines to 76 chars, but don't break =XX encodes.
// Method: iterate over to char 73.
// If char 74, 75 or 76 is = we need to break before the =.
// Otherwise break at 76.
var cur_length = 0;
var out = '';
for (var i=0; i<str.length; i++) {
if (str[i] === '\n') {
out += '\n';
cur_length = 0;
continue;
}
cur_length++;
if (cur_length <= 73) {
out += str[i];
}
else if (cur_length > 73 && cur_length < 76) {
if (str[i] === '=') {
out += '=\n=';
cur_length = 1;
}
else {
out += str[i];
}
}
else {
// Otherwise got to char 76
// Don't insert '=\n' if end of string or next char is already \n:
if ((i === (str.length - 1)) || (str[i+1] === '\n')) {
out += str[i];
}
else {
out += '=\n' + str[i];
cur_length = 1;
}
}
}
return out;
}
var versions = process.version.split('.'),
version = Number(versions[0].substring(1)),
subversion = Number(versions[1]);
exports.existsSync = require((version > 0 || subversion >= 8) ? 'fs' : 'path').existsSync;
exports.indexOfLF = function (buf, maxlength) {
for (var i=0; i<buf.length; i++) {
if (maxlength && (i === maxlength)) break;
if (buf[i] === 0x0a) return i;
}
return -1;
}
|
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites
define({
// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
// specified browser environments in the `environments` array below as well. See
// <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for
// different services.
// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
maxConcurrency: 2,
// Non-functional test suite(s) to run in each browser
suites: [ 'tests/plugin' ],
// A regular expression matching URLs to files that should not be included in code coverage analysis
excludeInstrumentation: /^(?:tests|node_modules)\//
});
|
import {LooseParser} from "./state"
import {isDummy} from "./parseutil"
import {tokTypes as tt} from ".."
const lp = LooseParser.prototype
lp.checkLVal = function(expr) {
if (!expr) return expr
switch (expr.type) {
case "Identifier":
case "MemberExpression":
return expr
case "ParenthesizedExpression":
expr.expression = this.checkLVal(expr.expression)
return expr
default:
return this.dummyIdent()
}
}
lp.parseExpression = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseMaybeAssign(noIn)
if (this.tok.type === tt.comma) {
let node = this.startNodeAt(start)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
lp.parseParenExpression = function() {
this.pushCx()
this.expect(tt.parenL)
let val = this.parseExpression()
this.popCx()
this.expect(tt.parenR)
return val
}
lp.parseMaybeAssign = function(noIn) {
if (this.toks.isContextual("yield")) {
let node = this.startNode()
this.next()
if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
let start = this.storeCurrentPos()
let left = this.parseMaybeConditional(noIn)
if (this.tok.type.isAssign) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
}
return left
}
lp.parseMaybeConditional = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseExprOps(noIn)
if (this.eat(tt.question)) {
let node = this.startNodeAt(start)
node.test = expr
node.consequent = this.parseMaybeAssign()
node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent()
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
lp.parseExprOps = function(noIn) {
let start = this.storeCurrentPos()
let indent = this.curIndent, line = this.curLineStart
return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line)
}
lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) {
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left
let prec = this.tok.type.binop
if (prec != null && (!noIn || this.tok.type !== tt._in)) {
if (prec > minPrec) {
let node = this.startNodeAt(start)
node.left = left
node.operator = this.tok.value
this.next()
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) {
node.right = this.dummyIdent()
} else {
let rightStart = this.storeCurrentPos()
node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line)
}
this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression")
return this.parseExprOp(node, start, minPrec, noIn, indent, line)
}
}
return left
}
lp.parseMaybeUnary = function(sawUnary) {
let start = this.storeCurrentPos(), expr
if (this.tok.type.prefix) {
let node = this.startNode(), update = this.tok.type === tt.incDec
if (!update) sawUnary = true
node.operator = this.tok.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(true)
if (update) node.argument = this.checkLVal(node.argument)
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else if (this.tok.type === tt.ellipsis) {
let node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(sawUnary)
expr = this.finishNode(node, "SpreadElement")
} else {
expr = this.parseExprSubscripts()
while (this.tok.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.prefix = false
node.argument = this.checkLVal(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar)) {
let node = this.startNodeAt(start)
node.operator = "**"
node.left = expr
node.right = this.parseMaybeUnary(false)
return this.finishNode(node, "BinaryExpression")
}
return expr
}
lp.parseExprSubscripts = function() {
let start = this.storeCurrentPos()
return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart)
}
lp.parseSubscripts = function(base, start, noCalls, startIndent, line) {
for (;;) {
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) {
if (this.tok.type == tt.dot && this.curIndent == startIndent)
--startIndent
else
return base
}
if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine())
node.property = this.dummyIdent()
else
node.property = this.parsePropertyAccessor() || this.dummyIdent()
node.computed = false
base = this.finishNode(node, "MemberExpression")
} else if (this.tok.type == tt.bracketL) {
this.pushCx()
this.next()
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseExpression()
node.computed = true
this.popCx()
this.expect(tt.bracketR)
base = this.finishNode(node, "MemberExpression")
} else if (!noCalls && this.tok.type == tt.parenL) {
let node = this.startNodeAt(start)
node.callee = base
node.arguments = this.parseExprList(tt.parenR)
base = this.finishNode(node, "CallExpression")
} else if (this.tok.type == tt.backQuote) {
let node = this.startNodeAt(start)
node.tag = base
node.quasi = this.parseTemplate()
base = this.finishNode(node, "TaggedTemplateExpression")
} else {
return base
}
}
}
lp.parseExprAtom = function() {
let node
switch (this.tok.type) {
case tt._this:
case tt._super:
let type = this.tok.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
let start = this.storeCurrentPos()
let id = this.parseIdent()
return this.eat(tt.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id
case tt.regexp:
node = this.startNode()
let val = this.tok.value
node.regex = {pattern: val.pattern, flags: val.flags}
node.value = val.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt.num: case tt.string:
node = this.startNode()
node.value = this.tok.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true
node.raw = this.tok.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
let parenStart = this.storeCurrentPos()
this.next()
let inner = this.parseExpression()
this.expect(tt.parenR)
if (this.eat(tt.arrow)) {
return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner]))
}
if (this.options.preserveParens) {
let par = this.startNodeAt(parenStart)
par.expression = inner
inner = this.finishNode(par, "ParenthesizedExpression")
}
return inner
case tt.bracketL:
node = this.startNode()
node.elements = this.parseExprList(tt.bracketR, true)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj()
case tt._class:
return this.parseClass()
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
return this.dummyIdent()
}
}
lp.parseNew = function() {
let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
return this.finishNode(node, "MetaProperty")
}
let start = this.storeCurrentPos()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line)
if (this.tok.type == tt.parenL) {
node.arguments = this.parseExprList(tt.parenR)
} else {
node.arguments = []
}
return this.finishNode(node, "NewExpression")
}
lp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'),
cooked: this.tok.value
}
this.next()
elem.tail = this.tok.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
lp.parseTemplate = function() {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this.next()
node.expressions.push(this.parseExpression())
if (this.expect(tt.braceR)) {
curElt = this.parseTemplateElement()
} else {
curElt = this.startNode()
curElt.value = {cooked: '', raw: ''}
curElt.tail = true
}
node.quasis.push(curElt)
}
this.expect(tt.backQuote)
return this.finishNode(node, "TemplateLiteral")
}
lp.parseObj = function() {
let node = this.startNode()
node.properties = []
this.pushCx()
let indent = this.curIndent + 1, line = this.curLineStart
this.eat(tt.braceL)
if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart }
while (!this.closes(tt.braceR, indent, line)) {
let prop = this.startNode(), isGenerator, start
if (this.options.ecmaVersion >= 6) {
start = this.storeCurrentPos()
prop.method = false
prop.shorthand = false
isGenerator = this.eat(tt.star)
}
this.parsePropertyName(prop)
if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue }
if (this.eat(tt.colon)) {
prop.kind = "init"
prop.value = this.parseMaybeAssign()
} else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) {
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator)
} else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
!prop.computed && (prop.key.name === "get" || prop.key.name === "set") &&
(this.tok.type != tt.comma && this.tok.type != tt.braceR)) {
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
} else {
prop.kind = "init"
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.eq)) {
let assign = this.startNodeAt(start)
assign.operator = "="
assign.left = prop.key
assign.right = this.parseMaybeAssign()
prop.value = this.finishNode(assign, "AssignmentExpression")
} else {
prop.value = prop.key
}
} else {
prop.value = this.dummyIdent()
}
prop.shorthand = true
}
node.properties.push(this.finishNode(prop, "Property"))
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(tt.braceR)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return this.finishNode(node, "ObjectExpression")
}
lp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseExpression()
this.expect(tt.bracketR)
return
} else {
prop.computed = false
}
}
let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent()
prop.key = key || this.dummyIdent()
}
lp.parsePropertyAccessor = function() {
if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent()
}
lp.parseIdent = function() {
let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword
if (!name) return this.dummyIdent()
let node = this.startNode()
this.next()
node.name = name
return this.finishNode(node, "Identifier")
}
lp.initFunction = function(node) {
node.id = null
node.params = []
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
}
// Convert existing expression atom to assignable pattern
// if possible.
lp.toAssignable = function(node, binding) {
if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) {
// Okay
} else if (node.type == "ParenthesizedExpression") {
node.expression = this.toAssignable(node.expression, binding)
} else if (this.options.ecmaVersion < 6) {
return this.dummyIdent()
} else if (node.type == "ObjectExpression") {
node.type = "ObjectPattern"
let props = node.properties
for (let i = 0; i < props.length; i++)
props[i].value = this.toAssignable(props[i].value, binding)
} else if (node.type == "ArrayExpression") {
node.type = "ArrayPattern"
this.toAssignableList(node.elements, binding)
} else if (node.type == "SpreadElement") {
node.type = "RestElement"
node.argument = this.toAssignable(node.argument, binding)
} else if (node.type == "AssignmentExpression") {
node.type = "AssignmentPattern"
delete node.operator
} else {
return this.dummyIdent()
}
return node
}
lp.toAssignableList = function(exprList, binding) {
for (let i = 0; i < exprList.length; i++)
exprList[i] = this.toAssignable(exprList[i], binding)
return exprList
}
lp.parseFunctionParams = function(params) {
params = this.parseExprList(tt.parenR)
return this.toAssignableList(params, true)
}
lp.parseMethod = function(isGenerator) {
let node = this.startNode()
this.initFunction(node)
node.params = this.parseFunctionParams()
node.generator = isGenerator || false
node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "FunctionExpression")
}
lp.parseArrowExpression = function(node, params) {
this.initFunction(node)
node.params = this.toAssignableList(params, true)
node.expression = this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "ArrowFunctionExpression")
}
lp.parseExprList = function(close, allowEmpty) {
this.pushCx()
let indent = this.curIndent, line = this.curLineStart, elts = []
this.next() // Opening bracket
while (!this.closes(close, indent + 1, line)) {
if (this.eat(tt.comma)) {
elts.push(allowEmpty ? null : this.dummyIdent())
continue
}
let elt = this.parseMaybeAssign()
if (isDummy(elt)) {
if (this.closes(close, indent, line)) break
this.next()
} else {
elts.push(elt)
}
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(close)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return elts
}
|
var Model;
module("Ember.FilteredRecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 'abc', name: 'Charles'}
];
},
teardown: function() { }
});
test("must be created with a modelClass property", function() {
throws(function() {
Ember.FilteredRecordArray.create();
}, /FilteredRecordArrays must be created with a modelClass/);
});
test("must be created with a filterFunction property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model});
}, /FilteredRecordArrays must be created with a filterFunction/);
});
test("must be created with a filterProperties property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K});
}, /FilteredRecordArrays must be created with filterProperties/);
});
test("with a noop filter will return all the loaded records", function() {
expect(1);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: Ember.K,
filterProperties: []
});
equal(recordArray.get('length'), 3, "There are 3 records");
});
stop();
});
test("with a filter will return only the relevant loaded records", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 1, "There is still 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
stop();
});
test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() {
expect(3);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik' || record.get('name') === 'Kris';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 2, "There are 2 records");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches");
});
stop();
});
stop();
});
test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(5);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.fetch(2).then(function(record) {
start();
record.set('name', 'Estefan');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches");
});
stop();
});
stop();
});
test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(8);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
record.set('name', 'Ekris');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches");
record.set('name', 'Eskil');
equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches");
equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches");
});
stop();
});
stop();
}); |
var fs = require('fs')
, child_process = require('child_process')
, _glob = require('glob')
, bunch = require('./bunch')
;
exports.loadEnv = function loadEnv(env, cb) {
var loaders = []
function load(name, cb) {
fs.readFile(env[name], function(error, data) {
env[name] = env[name].match(/.*\.json$/) ? JSON.parse(data) : data;
cb(error, data)
})
}
for (var name in env) {
loaders.push([load, name])
}
bunch(loaders, cb)
}
exports.commandActor = function command(executable) {
return function command(args, opts, cb) {
if (!cb) {
cb = opts;
opts = {}
}
var cmd = child_process.spawn(executable, args, opts);
function log(b) { console.log(b.toString()) }
cmd.stdout.on('data', log);
cmd.stderr.on('data', log);
cmd.on('exit', function(code) {
if (code) {
cb(new Error(executable + ' exited with status ' + code));
} else {
cb();
}
});
return cmd;
}
}
exports.jsonParse = function(str, cb) {
try {
cb(null, JSON.parse(str));
} catch (ex) {
cb(ex);
}
}
exports.jsonStringify = function(obj, cb) {
try {
cb(null, JSON.stringify(obj));
} catch (ex) {
cb(ex);
}
}
exports.glob = function glob(pattern, cb) {
console.log('pattern', pattern);
_glob(pattern, function(error, files) {
cb(error, [files]);
});
}
|
Function.prototype.bind = Function.prototype.bind || function (target) {
var self = this;
return function (args) {
if (!(args instanceof Array)) {
args = [args];
}
self.apply(target, args);
};
};
|
// DATA_TEMPLATE: js_data
oTest.fnStart( "oLanguage.oPaginate" );
/* Note that the paging language information only has relevence in full numbers */
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable( {
"aaData": gaaData,
"sPaginationType": "full_numbers"
} );
var oSettings = oTable.fnSettings();
oTest.fnTest(
"oLanguage.oPaginate defaults",
null,
function () {
var bReturn =
oSettings.oLanguage.oPaginate.sFirst == "First" &&
oSettings.oLanguage.oPaginate.sPrevious == "Previous" &&
oSettings.oLanguage.oPaginate.sNext == "Next" &&
oSettings.oLanguage.oPaginate.sLast == "Last";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate defaults are in the DOM",
null,
function () {
var bReturn =
$('#example_paginate .first').html() == "First" &&
$('#example_paginate .previous').html() == "Previous" &&
$('#example_paginate .next').html() == "Next" &&
$('#example_paginate .last').html() == "Last";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate can be defined",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"aaData": gaaData,
"sPaginationType": "full_numbers",
"oLanguage": {
"oPaginate": {
"sFirst": "unit1",
"sPrevious": "test2",
"sNext": "unit3",
"sLast": "test4"
}
}
} );
oSettings = oTable.fnSettings();
},
function () {
var bReturn =
oSettings.oLanguage.oPaginate.sFirst == "unit1" &&
oSettings.oLanguage.oPaginate.sPrevious == "test2" &&
oSettings.oLanguage.oPaginate.sNext == "unit3" &&
oSettings.oLanguage.oPaginate.sLast == "test4";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate definitions are in the DOM",
null,
function () {
var bReturn =
$('#example_paginate .first').html() == "unit1" &&
$('#example_paginate .previous').html() == "test2" &&
$('#example_paginate .next').html() == "unit3" &&
$('#example_paginate .last').html() == "test4";
return bReturn;
}
);
oTest.fnComplete();
} ); |
module.exports={title:"Google Hangouts",hex:"0C9D58",source:"https://material.google.com/resources/sticker-sheets-icons.html#sticker-sheets-icons-components",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Hangouts icon</title><path d="M12 0C6.2 0 1.5 4.7 1.5 10.5c0 5.5 5 10 10.5 10V24c6.35-3.1 10.5-8.2 10.5-13.5C22.5 4.7 17.8 0 12 0zm-.5 12c0 1.4-.9 2.5-2 2.5V12H7V7.5h4.5V12zm6 0c0 1.4-.9 2.5-2 2.5V12H13V7.5h4.5V12z"/></svg>'}; |
var utils = require('../../lib/utils');
// if they agree to the ULA, notify hubspot, create a trial and send verification link
module.exports = function trialSignup(request, reply) {
var postToHubspot = request.server.methods.npme.sendData,
getCustomer = request.server.methods.npme.getCustomer;
var opts = {};
var data = {
hs_context: {
pageName: "enterprise-trial-signup",
ipAddress: utils.getUserIP(request)
},
// we can trust the email is fine because we've verified it in the show-ula handler
email: request.payload.customer_email,
};
postToHubspot(process.env.HUBSPOT_FORM_NPME_AGREED_ULA, data, function(er) {
if (er) {
request.logger.error('Could not hit ULA notification form on Hubspot');
request.logger.error(er);
reply.view('errors/internal', opts).code(500);
return;
}
getCustomer(data.email, function(err, customer) {
if (err) {
request.logger.error('Unknown problem with customer record');
request.logger.error(err);
reply.view('errors/internal', opts).code(500);
return;
}
if (!customer) {
request.logger.error('Unable to locate customer error ' + data.email);
reply.view('errors/internal', opts).code(500);
return;
}
if (customer && customer.id + '' === request.payload.customer_id + '') {
return createTrialAccount(request, reply, customer);
}
request.logger.error('Unable to verify customer record ', data.email);
reply.view('errors/internal', opts).code(500);
});
});
};
function createTrialAccount(request, reply, customer) {
var createTrial = request.server.methods.npme.createTrial;
var opts = {};
createTrial(customer, function(er, trial) {
if (er) {
request.logger.error('There was an error with creating a trial for ', customer.id);
request.logger.error(er);
reply.view('errors/internal', opts).code(500);
return;
}
return sendVerificationEmail(request, reply, customer, trial);
});
}
function sendVerificationEmail(request, reply, customer, trial) {
var opts = {};
var sendEmail = request.server.methods.email.send;
var user = {
name: customer.name,
email: customer.email,
verification_key: trial.verification_key
};
sendEmail('npme-trial-verification', user, request.redis)
.catch(function(er) {
request.logger.error('Unable to send verification email to ', customer);
request.logger.error(er);
reply.view('errors/internal', opts).code(500);
return;
})
.then(function() {
return reply.view('enterprise/thanks', opts);
});
}
|
var insert = require('./insert')
var concat = require('concat-stream')
insert('aggregate', [{
name: 'Squirtle', type: 'water'
}, {
name: 'Starmie', type: 'water'
}, {
name: 'Charmander', type: 'fire'
}, {
name: 'Lapras', type: 'water'
}], function (db, t, done) {
db.a.aggregate([{$group: {_id: '$type'}}, {$project: { _id: 0, foo: '$_id' }}], function (err, types) {
console.log(err, types)
var arr = types.map(function (x) {return x.foo})
console.log('arr', arr)
t.equal(types.length, 2)
console.log('here')
t.notEqual(arr.indexOf('fire'), -1)
console.log('there')
t.notEqual(arr.indexOf('water'), -1)
console.log('where')
// test as a stream
var strm = db.a.aggregate([{$group: {_id: '$type'}}, {$project: {_id: 0, foo: '$_id'}}])
strm.pipe(concat(function (types) {
var arr = types.map(function (x) {return x.foo})
t.equal(types.length, 2)
t.notEqual(arr.indexOf('fire'), -1)
t.notEqual(arr.indexOf('water'), -1)
t.end()
}))
strm.on('error', function (err) {
// Aggregation cursors are only supported on mongodb 2.6+
// this shouldn't fail the tests for other versions of mongodb
if (err.message === 'unrecognized field "cursor') t.ok(1)
else t.fail(err)
t.end()
})
})
})
|
import {addClass, hasClass, empty} from './../helpers/dom/element';
import {eventManager as eventManagerObject} from './../eventManager';
import {getRenderer, registerRenderer} from './../renderers';
import {WalkontableCellCoords} from './../3rdparty/walkontable/src/cell/coords';
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
// workaround for https://github.com/handsontable/handsontable/issues/1946
// this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660)));
var wrapTdContentWithWrapper = function(TD, WRAPPER) {
WRAPPER.innerHTML = TD.innerHTML;
empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer
*
* @private
* @renderer AutocompleteRenderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
getRenderer('text')(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode(String.fromCharCode(160))); // workaround for https://github.com/handsontable/handsontable/issues/1946
//this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
var eventManager = eventManagerObject(instance);
//not very elegant but easy and fast
instance.acArrowListener = function(event) {
if (hasClass(event.target, 'htAutocompleteArrow')) {
instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD);
}
};
eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener);
//We need to unbind the listener after the table has been destroyed
instance.addHookOnce('afterDestroy', function() {
eventManager.destroy();
});
}
}
export {autocompleteRenderer};
registerRenderer('autocomplete', autocompleteRenderer);
|
var one = {
name: 'one'
};
|
var crypto = require('crypto');
var scmp = require('scmp');
var utils = require('keystone-utils');
// The DISABLE_CSRF environment variable is available to automatically pass
// CSRF validation. This is useful in development scenarios where you want to
// restart the node process and aren't using a persistent session store, but
// should NEVER be set in production environments!!
var DISABLE_CSRF = process.env.DISABLE_CSRF === 'true';
exports.TOKEN_KEY = '_csrf';
exports.LOCAL_KEY = 'csrf_token_key';
exports.LOCAL_VALUE = 'csrf_token_value';
exports.SECRET_KEY = exports.TOKEN_KEY + '_secret';
exports.SECRET_LENGTH = 10;
exports.CSRF_HEADER_KEY = 'x-csrf-token';
exports.XSRF_HEADER_KEY = 'x-xsrf-token';
exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN';
function tokenize (salt, secret) {
return salt + crypto.createHash('sha1').update(salt + secret).digest('hex');
}
exports.createSecret = function () {
return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64');
};
exports.getSecret = function (req) {
return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret());
};
exports.createToken = function (req) {
return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req));
};
exports.getToken = function (req, res) {
res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req);
res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]);
return res.locals[exports.LOCAL_VALUE];
};
exports.requestToken = function (req) {
if (req.body && req.body[exports.TOKEN_KEY]) {
return req.body[exports.TOKEN_KEY];
} else if (req.query && req.query[exports.TOKEN_KEY]) {
return req.query[exports.TOKEN_KEY];
} else if (req.headers && req.headers[exports.XSRF_HEADER_KEY]) {
return req.headers[exports.XSRF_HEADER_KEY];
} else if (req.headers && req.headers[exports.CSRF_HEADER_KEY]) {
return req.headers[exports.CSRF_HEADER_KEY];
}
return '';
};
exports.validate = function (req, token) {
// Allow environment variable to disable check
if (DISABLE_CSRF) return true;
if (arguments.length === 1) {
token = exports.requestToken(req);
}
if (typeof token !== 'string') {
return false;
}
return scmp(token, tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY]));
};
exports.middleware = {
init: function (req, res, next) {
res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE;
exports.getToken(req, res);
next();
},
validate: function (req, res, next) {
// Allow environment variable to disable check
if (DISABLE_CSRF) return next();
// Bail on safe methods
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
return next();
}
// Validate token
if (exports.validate(req)) {
next();
} else {
res.statusCode = 403;
next(new Error('CSRF token mismatch'));
}
},
};
|
#!/usr/bin/env node
/* global cat:true, cd:true, echo:true, exec:true, exit:true */
// Usage:
// stable release: node release.js
// pre-release: node release.js --pre-release {version}
// test run: node release.js --remote={repo}
// - repo: "/tmp/repo" (filesystem), "user/repo" (github), "http://mydomain/repo.git" (another domain)
"use strict";
var baseDir, downloadBuilder, repoDir, prevVersion, newVersion, nextVersion, tagTime, preRelease, repo,
fs = require( "fs" ),
path = require( "path" ),
rnewline = /\r?\n/,
branch = "master";
walk([
bootstrap,
section( "setting up repo" ),
cloneRepo,
checkState,
section( "calculating versions" ),
getVersions,
confirm,
section( "building release" ),
buildReleaseBranch,
buildPackage,
section( "pushing tag" ),
confirmReview,
pushRelease,
section( "updating branch version" ),
updateBranchVersion,
section( "pushing " + branch ),
confirmReview,
pushBranch,
section( "generating changelog" ),
generateChangelog,
section( "gathering contributors" ),
gatherContributors,
section( "updating trac" ),
updateTrac,
confirm
]);
function cloneRepo() {
echo( "Cloning " + repo.cyan + "..." );
git( "clone " + repo + " " + repoDir, "Error cloning repo." );
cd( repoDir );
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out branch." );
echo();
echo( "Installing dependencies..." );
if ( exec( "npm install" ).code !== 0 ) {
abort( "Error installing dependencies." );
}
echo();
}
function checkState() {
echo( "Checking AUTHORS.txt..." );
var result, lastActualAuthor,
lastListedAuthor = cat( "AUTHORS.txt" ).trim().split( rnewline ).pop();
result = exec( "grunt authors", { silent: true });
if ( result.code !== 0 ) {
abort( "Error getting list of authors." );
}
lastActualAuthor = result.output.split( rnewline ).splice( -4, 1 )[ 0 ];
if ( lastListedAuthor !== lastActualAuthor ) {
echo( "Last listed author is " + lastListedAuthor.red + "." );
echo( "Last actual author is " + lastActualAuthor.green + "." );
abort( "Please update AUTHORS.txt." );
}
echo( "Last listed author (" + lastListedAuthor.cyan + ") is correct." );
}
function getVersions() {
// prevVersion, newVersion, nextVersion are defined in the parent scope
var parts, major, minor, patch,
currentVersion = readPackage().version;
echo( "Validating current version..." );
if ( currentVersion.substr( -3, 3 ) !== "pre" ) {
echo( "The current version is " + currentVersion.red + "." );
abort( "The version must be a pre version." );
}
if ( preRelease ) {
newVersion = preRelease;
// Note: prevVersion is not currently used for pre-releases.
prevVersion = nextVersion = currentVersion;
} else {
newVersion = currentVersion.substr( 0, currentVersion.length - 3 );
parts = newVersion.split( "." );
major = parseInt( parts[ 0 ], 10 );
minor = parseInt( parts[ 1 ], 10 );
patch = parseInt( parts[ 2 ], 10 );
if ( minor === 0 && patch === 0 ) {
abort( "This script is not smart enough to handle major release (eg. 2.0.0)." );
} else if ( patch === 0 ) {
prevVersion = git( "for-each-ref --count=1 --sort=-authordate --format='%(refname:short)' refs/tags/" + [ major, minor - 1 ].join( "." ) + "*" ).trim();
} else {
prevVersion = [ major, minor, patch - 1 ].join( "." );
}
nextVersion = [ major, minor, patch + 1 ].join( "." ) + "pre";
}
echo( "We are going from " + prevVersion.cyan + " to " + newVersion.cyan + "." );
echo( "After the release, the version will be " + nextVersion.cyan + "." );
}
function buildReleaseBranch() {
var pkg;
echo( "Creating " + "release".cyan + " branch..." );
git( "checkout -b release", "Error creating release branch." );
echo();
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = newVersion;
pkg.author.url = pkg.author.url.replace( "master", newVersion );
pkg.licenses.forEach(function( license ) {
license.url = license.url.replace( "master", newVersion );
});
writePackage( pkg );
echo( "Generating manifest files..." );
if ( exec( "grunt manifest" ).code !== 0 ) {
abort( "Error generating manifest files." );
}
echo();
echo( "Committing release artifacts..." );
git( "add *.jquery.json", "Error adding manifest files to git." );
git( "commit -am 'Tagging the " + newVersion + " release.'",
"Error committing release changes." );
echo();
echo( "Tagging release..." );
git( "tag " + newVersion, "Error tagging " + newVersion + "." );
tagTime = git( "log -1 --format='%ad'", "Error getting tag timestamp." ).trim();
}
function buildPackage( callback ) {
if( preRelease ) {
return buildPreReleasePackage( callback );
} else {
return buildCDNPackage( callback );
}
}
function buildPreReleasePackage( callback ) {
var build, files, jqueryUi, packer, target, targetZip;
echo( "Build pre-release Package" );
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
packer = new downloadBuilder.Packer( build, null, {
addTests: true,
bundleSuffix: "",
skipDocs: true,
skipTheme: true
});
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version;
targetZip = target + ".zip";
return walk([
function( callback ) {
echo( "Building release files" );
packer.pack(function( error, _files ) {
if( error ) {
abort( error.stack );
}
files = _files.map(function( file ) {
// Strip first path
file.path = file.path.replace( /^[^\/]*\//, "" );
return file;
}).filter(function( file ) {
// Filter development-bundle content only
return (/^development-bundle/).test( file.path );
}).map(function( file ) {
// Strip development-bundle
file.path = file.path.replace( /^development-bundle\//, "" );
return file;
});
return callback();
});
},
function() {
downloadBuilder.util.createZip( files, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}
]);
}
function buildCDNPackage( callback ) {
var build, output, target, targetZip,
add = function( file ) {
output.push( file );
},
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ),
themeGallery = downloadBuilder.themeGallery( jqueryUi );
echo( "Build CDN Package" );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
output = [];
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version + "-cdn";
targetZip = target + ".zip";
[ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ].map(function( name ) {
return build.get( name );
}).forEach( add );
// "ui/*.js"
build.componentFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "ui/*.min.js"
build.componentMinFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "i18n/*.js"
build.i18nFiles.rename( /^ui\//, "" ).forEach( add );
build.i18nMinFiles.rename( /^ui\//, "" ).forEach( add );
build.bundleI18n.into( "i18n/" ).forEach( add );
build.bundleI18nMin.into( "i18n/" ).forEach( add );
build.bundleJs.forEach( add );
build.bundleJsMin.forEach( add );
walk( themeGallery.map(function( theme ) {
return function( callback ) {
var themeCssOnlyRe, themeDirRe,
folderName = theme.folderName(),
packer = new downloadBuilder.Packer( build, theme, {
skipDocs: true
});
// TODO improve code by using custom packer instead of download packer (Packer)
themeCssOnlyRe = new RegExp( "development-bundle/themes/" + folderName + "/jquery.ui.theme.css" );
themeDirRe = new RegExp( "css/" + folderName );
packer.pack(function( error, files ) {
if ( error ) {
abort( error.stack );
}
// Add theme files.
files
// Pick only theme files we need on the bundle.
.filter(function( file ) {
if ( themeCssOnlyRe.test( file.path ) || themeDirRe.test( file.path ) ) {
return true;
}
return false;
})
// Convert paths the way bundle needs
.map(function( file ) {
file.path = file.path
// Remove initial package name eg. "jquery-ui-1.10.0.custom"
.split( "/" ).slice( 1 ).join( "/" )
.replace( /development-bundle\/themes/, "css" )
.replace( /css/, "themes" )
// Make jquery-ui-1.10.0.custom.css into jquery-ui.css, or jquery-ui-1.10.0.custom.min.css into jquery-ui.min.css
.replace( /jquery-ui-.*?(\.min)*\.css/, "jquery-ui$1.css" );
return file;
}).forEach( add );
return callback();
});
};
}).concat([function() {
var crypto = require( "crypto" );
// Create MD5 manifest
output.push({
path: "MANIFEST",
data: output.sort(function( a, b ) {
return a.path.localeCompare( b.path );
}).map(function( file ) {
var md5 = crypto.createHash( "md5" );
md5.update( file.data );
return file.path + " " + md5.digest( "hex" );
}).join( "\n" )
});
downloadBuilder.util.createZip( output, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip CDN package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}]));
}
function pushRelease() {
echo( "Pushing release to GitHub..." );
git( "push --tags", "Error pushing tags to GitHub." );
}
function updateBranchVersion() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
var pkg;
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out " + branch + " branch." );
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = nextVersion;
writePackage( pkg );
echo( "Committing version update..." );
git( "commit -am 'Updating the " + branch + " version to " + nextVersion + ".'",
"Error committing package.json." );
}
function pushBranch() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
echo( "Pushing " + branch.cyan + " to GitHub..." );
git( "push", "Error pushing to GitHub." );
}
function generateChangelog() {
if ( preRelease ) {
return;
}
var commits,
changelogPath = baseDir + "/changelog",
changelog = cat( "build/release/changelog-shell" ) + "\n",
fullFormat = "* %s (TICKETREF, [%h](http://github.com/jquery/jquery-ui/commit/%H))";
changelog = changelog.replace( "{title}", "jQuery UI " + newVersion + " Changelog" );
echo ( "Adding commits..." );
commits = gitLog( fullFormat );
echo( "Adding links to tickets..." );
changelog += commits
// Add ticket references
.map(function( commit ) {
var tickets = [];
commit.replace( /Fixe[sd] #(\d+)/g, function( match, ticket ) {
tickets.push( ticket );
});
return tickets.length ?
commit.replace( "TICKETREF", tickets.map(function( ticket ) {
return "[#" + ticket + "](http://bugs.jqueryui.com/ticket/" + ticket + ")";
}).join( ", " ) ) :
// Leave TICKETREF token in place so it's easy to find commits without tickets
commit;
})
// Sort commits so that they're grouped by component
.sort()
.join( "\n" ) + "\n";
echo( "Adding Trac tickets..." );
changelog += trac( "/query?milestone=" + newVersion + "&resolution=fixed" +
"&col=id&col=component&col=summary&order=component" ) + "\n";
fs.writeFileSync( changelogPath, changelog );
echo( "Stored changelog in " + changelogPath.cyan + "." );
}
function gatherContributors() {
if ( preRelease ) {
return;
}
var contributors,
contributorsPath = baseDir + "/contributors";
echo( "Adding committers and authors..." );
contributors = gitLog( "%aN%n%cN" );
echo( "Adding reporters and commenters from Trac..." );
contributors = contributors.concat(
trac( "/report/22?V=" + newVersion + "&max=-1" )
.split( rnewline )
// Remove header and trailing newline
.slice( 1, -1 ) );
echo( "Sorting contributors..." );
contributors = unique( contributors ).sort(function( a, b ) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
echo ( "Adding people thanked in commits..." );
contributors = contributors.concat(
gitLog( "%b%n%s" ).filter(function( line ) {
return (/thank/i).test( line );
}));
fs.writeFileSync( contributorsPath, contributors.join( "\n" ) );
echo( "Stored contributors in " + contributorsPath.cyan + "." );
}
function updateTrac() {
echo( newVersion.cyan + " was tagged at " + tagTime.cyan + "." );
if ( !preRelease ) {
echo( "Close the " + newVersion.cyan + " Milestone." );
}
echo( "Create the " + newVersion.cyan + " Version." );
echo( "When Trac asks for date and time, match the above. Should only change minutes and seconds." );
echo( "Create a Milestone for the next minor release." );
}
// ===== HELPER FUNCTIONS ======================================================
function git( command, errorMessage ) {
var result = exec( "git " + command );
if ( result.code !== 0 ) {
abort( errorMessage );
}
return result.output;
}
function gitLog( format ) {
var result = exec( "git log " + prevVersion + ".." + newVersion + " " +
"--format='" + format + "'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting git log." );
}
result = result.output.split( rnewline );
if ( result[ result.length - 1 ] === "" ) {
result.pop();
}
return result;
}
function trac( path ) {
var result = exec( "curl -s 'http://bugs.jqueryui.com" + path + "&format=tab'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting Trac data." );
}
return result.output;
}
function unique( arr ) {
var obj = {};
arr.forEach(function( item ) {
obj[ item ] = 1;
});
return Object.keys( obj );
}
function readPackage() {
return JSON.parse( fs.readFileSync( repoDir + "/package.json" ) );
}
function writePackage( pkg ) {
fs.writeFileSync( repoDir + "/package.json",
JSON.stringify( pkg, null, "\t" ) + "\n" );
}
function bootstrap( fn ) {
getRemote(function( remote ) {
if ( (/:/).test( remote ) || fs.existsSync( remote ) ) {
repo = remote;
} else {
repo = "[email protected]:" + remote + ".git";
}
_bootstrap( fn );
});
}
function getRemote( fn ) {
var matches, remote;
console.log( "Determining remote repo..." );
process.argv.forEach(function( arg ) {
matches = /--remote=(.+)/.exec( arg );
if ( matches ) {
remote = matches[ 1 ];
}
});
if ( remote ) {
fn( remote );
return;
}
console.log();
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !! !!" );
console.log( " !! Using jquery/jquery-ui !!" );
console.log( " !! !!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log();
console.log( "Press enter to continue, or ctrl+c to cancel." );
prompt(function() {
fn( "jquery/jquery-ui" );
});
}
function _bootstrap( fn ) {
console.log( "Determining release type..." );
preRelease = process.argv.indexOf( "--pre-release" );
if ( preRelease !== -1 ) {
preRelease = process.argv[ preRelease + 1 ];
console.log( "pre-release" );
} else {
preRelease = null;
console.log( "stable release" );
}
console.log( "Determining directories..." );
baseDir = process.cwd() + "/__release";
repoDir = baseDir + "/repo";
if ( fs.existsSync( baseDir ) ) {
console.log( "The directory '" + baseDir + "' already exists." );
console.log( "Aborting." );
process.exit( 1 );
}
console.log( "Creating directory..." );
fs.mkdirSync( baseDir );
console.log( "Installing dependencies..." );
require( "child_process" ).exec( "npm install shelljs colors [email protected]", function( error ) {
if ( error ) {
console.log( error );
return process.exit( 1 );
}
require( "shelljs/global" );
require( "colors" );
downloadBuilder = require( "download.jqueryui.com" );
fn();
});
}
function section( name ) {
return function() {
echo();
echo( "##" );
echo( "## " + name.toUpperCase().magenta );
echo( "##" );
echo();
};
}
function prompt( fn ) {
process.stdin.once( "data", function( chunk ) {
process.stdin.pause();
fn( chunk.toString().trim() );
});
process.stdin.resume();
}
function confirm( fn ) {
echo( "Press enter to continue, or ctrl+c to cancel.".yellow );
prompt( fn );
}
function confirmReview( fn ) {
echo( "Please review the output and generated files as a sanity check.".yellow );
confirm( fn );
}
function abort( msg ) {
echo( msg.red );
echo( "Aborting.".red );
exit( 1 );
}
function walk( methods ) {
var method = methods.shift();
function next() {
if ( methods.length ) {
walk( methods );
}
}
if ( !method.length ) {
method();
next();
} else {
method( next );
}
}
|
(function ($) {
$.Redactor.opts.langs['el'] = {
html: 'HTML',
video: 'Εισαγωγή βίντεο...',
image: 'Εισαγωγή εικόνας...',
table: 'Πίνακας',
link: 'Σύνδεσμος',
link_insert: 'Εισαγωγή συνδέσμου...',
link_edit: 'Edit link',
unlink: 'Ακύρωση συνδέσμου',
formatting: 'Μορφοποίηση',
paragraph: 'Παράγραφος',
quote: 'Παράθεση',
code: 'Κώδικας',
header1: 'Κεφαλίδα 1',
header2: 'Κεφαλίδα 2',
header3: 'Κεφαλίδα 3',
header4: 'Κεφαλίδα 4',
bold: 'Έντονα',
italic: 'Πλάγια',
fontcolor: 'Χρώμα γραμματοσειράς',
backcolor: 'Χρώμα επισήμανσης κειμένου',
unorderedlist: 'Κουκκίδες',
orderedlist: 'Αρίθμηση',
outdent: 'Μείωση εσοχής',
indent: 'Αύξηση εσοχής',
cancel: 'Ακύρωση',
insert: 'Εισαγωγή',
save: 'Αποθήκευση',
_delete: 'Διαγραφή',
insert_table: 'Εισαγωγή πίνακα...',
insert_row_above: 'Προσθήκη σειράς επάνω',
insert_row_below: 'Προσθήκη σειράς κάτω',
insert_column_left: 'Προσθήκη στήλης αριστερά',
insert_column_right: 'Προσθήκη στήλης δεξιά',
delete_column: 'Διαγραφή στήλης',
delete_row: 'Διαγραφή σειράς',
delete_table: 'Διαγραφή πίνακα',
rows: 'Γραμμές',
columns: 'Στήλες',
add_head: 'Προσθήκη κεφαλίδας',
delete_head: 'Διαγραφή κεφαλίδας',
title: 'Τίτλος',
image_position: 'Θέση',
none: 'Καμία',
left: 'Αριστερά',
right: 'Δεξιά',
image_web_link: 'Υπερσύνδεσμος εικόνας',
text: 'Κείμενο',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video Embed Code',
file: 'Εισαγωγή αρχείου...',
upload: 'Upload',
download: 'Download',
choose: 'Επέλεξε',
or_choose: 'ή επέλεξε',
drop_file_here: 'Σύρατε αρχεία εδώ',
align_left: 'Στοίχιση αριστερά',
align_center: 'Στοίχιση στο κέντρο',
align_right: 'Στοίχιση δεξιά',
align_justify: 'Πλήρησ στοίχηση',
horizontalrule: 'Εισαγωγή οριζόντιας γραμμής',
deleted: 'Διαγράφτηκε',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit'
};
})( jQuery );
|
import Ember from 'ember-metal/core';
import { get } from 'ember-metal/property_get';
import { internal } from 'htmlbars-runtime';
import { read } from 'ember-metal/streams/utils';
export default {
setupState(state, env, scope, params, hash) {
var controller = hash.controller;
if (controller) {
if (!state.controller) {
var context = params[0];
var controllerFactory = env.container.lookupFactory('controller:' + controller);
var parentController = null;
if (scope.locals.controller) {
parentController = read(scope.locals.controller);
} else if (scope.locals.view) {
parentController = get(read(scope.locals.view), 'context');
}
var controllerInstance = controllerFactory.create({
model: env.hooks.getValue(context),
parentController: parentController,
target: parentController
});
params[0] = controllerInstance;
return { controller: controllerInstance };
}
return state;
}
return { controller: null };
},
isStable() {
return true;
},
isEmpty(state) {
return false;
},
render(morph, env, scope, params, hash, template, inverse, visitor) {
if (morph.state.controller) {
morph.addDestruction(morph.state.controller);
hash.controller = morph.state.controller;
}
Ember.assert(
'{{#with foo}} must be called with a single argument or the use the ' +
'{{#with foo as |bar|}} syntax',
params.length === 1
);
Ember.assert(
'The {{#with}} helper must be called with a block',
!!template
);
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
},
rerender(morph, env, scope, params, hash, template, inverse, visitor) {
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
}
};
|
/*
LumX v1.5.14
(c) 2014-2017 LumApps http://ui.lumapps.com
License: MIT
*/
(function()
{
'use strict';
angular.module('lumx.utils.depth', []);
angular.module('lumx.utils.event-scheduler', []);
angular.module('lumx.utils.transclude-replace', []);
angular.module('lumx.utils.utils', []);
angular.module('lumx.utils', [
'lumx.utils.depth',
'lumx.utils.event-scheduler',
'lumx.utils.transclude-replace',
'lumx.utils.utils'
]);
angular.module('lumx.button', []);
angular.module('lumx.checkbox', []);
angular.module('lumx.data-table', []);
angular.module('lumx.date-picker', []);
angular.module('lumx.dialog', ['lumx.utils.event-scheduler']);
angular.module('lumx.dropdown', ['lumx.utils.event-scheduler']);
angular.module('lumx.fab', []);
angular.module('lumx.file-input', []);
angular.module('lumx.icon', []);
angular.module('lumx.notification', ['lumx.utils.event-scheduler']);
angular.module('lumx.progress', []);
angular.module('lumx.radio-button', []);
angular.module('lumx.ripple', []);
angular.module('lumx.search-filter', []);
angular.module('lumx.select', []);
angular.module('lumx.stepper', []);
angular.module('lumx.switch', []);
angular.module('lumx.tabs', []);
angular.module('lumx.text-field', []);
angular.module('lumx.tooltip', []);
angular.module('lumx', [
'lumx.button',
'lumx.checkbox',
'lumx.data-table',
'lumx.date-picker',
'lumx.dialog',
'lumx.dropdown',
'lumx.fab',
'lumx.file-input',
'lumx.icon',
'lumx.notification',
'lumx.progress',
'lumx.radio-button',
'lumx.ripple',
'lumx.search-filter',
'lumx.select',
'lumx.stepper',
'lumx.switch',
'lumx.tabs',
'lumx.text-field',
'lumx.tooltip',
'lumx.utils'
]);
})();
(function()
{
'use strict';
angular
.module('lumx.utils.depth')
.service('LxDepthService', LxDepthService);
function LxDepthService()
{
var service = this;
var depth = 1000;
service.getDepth = getDepth;
service.register = register;
////////////
function getDepth()
{
return depth;
}
function register()
{
depth++;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.event-scheduler')
.service('LxEventSchedulerService', LxEventSchedulerService);
LxEventSchedulerService.$inject = ['$document', 'LxUtils'];
function LxEventSchedulerService($document, LxUtils)
{
var service = this;
var handlers = {};
var schedule = {};
service.register = register;
service.unregister = unregister;
////////////
function handle(event)
{
var scheduler = schedule[event.type];
if (angular.isDefined(scheduler))
{
for (var i = 0, length = scheduler.length; i < length; i++)
{
var handler = scheduler[i];
if (angular.isDefined(handler) && angular.isDefined(handler.callback) && angular.isFunction(handler.callback))
{
handler.callback(event);
if (event.isPropagationStopped())
{
break;
}
}
}
}
}
function register(eventName, callback)
{
var handler = {
eventName: eventName,
callback: callback
};
var id = LxUtils.generateUUID();
handlers[id] = handler;
if (angular.isUndefined(schedule[eventName]))
{
schedule[eventName] = [];
$document.on(eventName, handle);
}
schedule[eventName].unshift(handlers[id]);
return id;
}
function unregister(id)
{
var found = false;
var handler = handlers[id];
if (angular.isDefined(handler) && angular.isDefined(schedule[handler.eventName]))
{
var index = schedule[handler.eventName].indexOf(handler);
if (angular.isDefined(index) && index > -1)
{
schedule[handler.eventName].splice(index, 1);
delete handlers[id];
found = true;
}
if (schedule[handler.eventName].length === 0)
{
delete schedule[handler.eventName];
$document.off(handler.eventName, handle);
}
}
return found;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.transclude-replace')
.directive('ngTranscludeReplace', ngTranscludeReplace);
ngTranscludeReplace.$inject = ['$log'];
function ngTranscludeReplace($log)
{
return {
terminal: true,
restrict: 'EA',
link: link
};
function link(scope, element, attrs, ctrl, transclude)
{
if (!transclude)
{
$log.error('orphan',
'Illegal use of ngTranscludeReplace directive in the template! ' +
'No parent directive that requires a transclusion found. ');
return;
}
transclude(function(clone)
{
if (clone.length)
{
element.replaceWith(clone);
}
else
{
element.remove();
}
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.utils')
.service('LxUtils', LxUtils);
function LxUtils()
{
var service = this;
service.debounce = debounce;
service.generateUUID = generateUUID;
service.disableBodyScroll = disableBodyScroll;
////////////
// http://underscorejs.org/#debounce (1.8.3)
function debounce(func, wait, immediate)
{
var timeout, args, context, timestamp, result;
wait = wait || 500;
var later = function()
{
var last = Date.now() - timestamp;
if (last < wait && last >= 0)
{
timeout = setTimeout(later, wait - last);
}
else
{
timeout = null;
if (!immediate)
{
result = func.apply(context, args);
if (!timeout)
{
context = args = null;
}
}
}
};
var debounced = function()
{
context = this;
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout)
{
timeout = setTimeout(later, wait);
}
if (callNow)
{
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function()
{
clearTimeout(timeout);
timeout = context = args = null;
};
return debounced;
}
function generateUUID()
{
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8))
.toString(16);
});
return uuid.toUpperCase();
}
function disableBodyScroll()
{
var body = document.body;
var documentElement = document.documentElement;
var prevDocumentStyle = documentElement.style.cssText || '';
var prevBodyStyle = body.style.cssText || '';
var viewportTop = window.scrollY || window.pageYOffset || 0;
var clientWidth = body.clientWidth;
var hasVerticalScrollbar = body.scrollHeight > window.innerHeight + 1;
if (hasVerticalScrollbar)
{
angular.element('body').css({
position: 'fixed',
width: '100%',
top: -viewportTop + 'px'
});
}
if (body.clientWidth < clientWidth)
{
body.style.overflow = 'hidden';
}
// This should be applied after the manipulation to the body, because
// adding a scrollbar can potentially resize it, causing the measurement
// to change.
if (hasVerticalScrollbar)
{
documentElement.style.overflowY = 'scroll';
}
return function restoreScroll()
{
// Reset the inline style CSS to the previous.
body.style.cssText = prevBodyStyle;
documentElement.style.cssText = prevDocumentStyle;
// The body loses its scroll position while being fixed.
body.scrollTop = viewportTop;
};
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.button')
.directive('lxButton', lxButton);
function lxButton()
{
var buttonClass;
return {
restrict: 'E',
templateUrl: getTemplateUrl,
compile: compile,
replace: true,
transclude: true
};
function compile(element, attrs)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, attrs.lxType);
return function(scope, element, attrs)
{
attrs.$observe('lxSize', function(lxSize)
{
setButtonStyle(element, lxSize, attrs.lxColor, attrs.lxType);
});
attrs.$observe('lxColor', function(lxColor)
{
setButtonStyle(element, attrs.lxSize, lxColor, attrs.lxType);
});
attrs.$observe('lxType', function(lxType)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, lxType);
});
element.on('click', function(event)
{
if (attrs.disabled === true)
{
event.preventDefault();
event.stopImmediatePropagation();
}
});
};
}
function getTemplateUrl(element, attrs)
{
return isAnchor(attrs) ? 'link.html' : 'button.html';
}
function isAnchor(attrs)
{
return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) || angular.isDefined(attrs.ngLink) || angular.isDefined(attrs.uiSref);
}
function setButtonStyle(element, size, color, type)
{
var buttonBase = 'btn';
var buttonSize = angular.isDefined(size) ? size : 'm';
var buttonColor = angular.isDefined(color) ? color : 'primary';
var buttonType = angular.isDefined(type) ? type : 'raised';
element.removeClass(buttonClass);
buttonClass = buttonBase + ' btn--' + buttonSize + ' btn--' + buttonColor + ' btn--' + buttonType;
element.addClass(buttonClass);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.checkbox')
.directive('lxCheckbox', lxCheckbox)
.directive('lxCheckboxLabel', lxCheckboxLabel)
.directive('lxCheckboxHelp', lxCheckboxHelp);
function lxCheckbox()
{
return {
restrict: 'E',
templateUrl: 'checkbox.html',
scope:
{
lxColor: '@?',
name: '@?',
ngChange: '&?',
ngDisabled: '=?',
ngFalseValue: '@?',
ngModel: '=',
ngTrueValue: '@?',
theme: '@?lxTheme'
},
controller: LxCheckboxController,
controllerAs: 'lxCheckbox',
bindToController: true,
transclude: true,
replace: true
};
}
LxCheckboxController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxCheckboxController($scope, $timeout, LxUtils)
{
var lxCheckbox = this;
var checkboxId;
var checkboxHasChildren;
var timer;
lxCheckbox.getCheckboxId = getCheckboxId;
lxCheckbox.getCheckboxHasChildren = getCheckboxHasChildren;
lxCheckbox.setCheckboxId = setCheckboxId;
lxCheckbox.setCheckboxHasChildren = setCheckboxHasChildren;
lxCheckbox.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getCheckboxId()
{
return checkboxId;
}
function getCheckboxHasChildren()
{
return checkboxHasChildren;
}
function init()
{
setCheckboxId(LxUtils.generateUUID());
setCheckboxHasChildren(false);
lxCheckbox.ngTrueValue = angular.isUndefined(lxCheckbox.ngTrueValue) ? true : lxCheckbox.ngTrueValue;
lxCheckbox.ngFalseValue = angular.isUndefined(lxCheckbox.ngFalseValue) ? false : lxCheckbox.ngFalseValue;
lxCheckbox.lxColor = angular.isUndefined(lxCheckbox.lxColor) ? 'accent' : lxCheckbox.lxColor;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
function setCheckboxHasChildren(_checkboxHasChildren)
{
checkboxHasChildren = _checkboxHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxCheckbox.ngChange);
}
}
function lxCheckboxLabel()
{
return {
restrict: 'AE',
require: ['^lxCheckbox', '^lxCheckboxLabel'],
templateUrl: 'checkbox-label.html',
link: link,
controller: LxCheckboxLabelController,
controllerAs: 'lxCheckboxLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setCheckboxHasChildren(true);
ctrls[1].setCheckboxId(ctrls[0].getCheckboxId());
}
}
function LxCheckboxLabelController()
{
var lxCheckboxLabel = this;
var checkboxId;
lxCheckboxLabel.getCheckboxId = getCheckboxId;
lxCheckboxLabel.setCheckboxId = setCheckboxId;
////////////
function getCheckboxId()
{
return checkboxId;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
}
function lxCheckboxHelp()
{
return {
restrict: 'AE',
require: '^lxCheckbox',
templateUrl: 'checkbox-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.directive('lxDataTable', lxDataTable);
function lxDataTable()
{
return {
restrict: 'E',
templateUrl: 'data-table.html',
scope:
{
border: '=?lxBorder',
selectable: '=?lxSelectable',
thumbnail: '=?lxThumbnail',
tbody: '=lxTbody',
thead: '=lxThead'
},
link: link,
controller: LxDataTableController,
controllerAs: 'lxDataTable',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDataTableController.$inject = ['$rootScope', '$sce', '$scope'];
function LxDataTableController($rootScope, $sce, $scope)
{
var lxDataTable = this;
lxDataTable.areAllRowsSelected = areAllRowsSelected;
lxDataTable.border = angular.isUndefined(lxDataTable.border) ? true : lxDataTable.border;
lxDataTable.sort = sort;
lxDataTable.toggle = toggle;
lxDataTable.toggleAllSelected = toggleAllSelected;
lxDataTable.$sce = $sce;
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows = [];
$scope.$on('lx-data-table__select', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_select(row);
}
});
$scope.$on('lx-data-table__select-all', function(event, id)
{
if (id === lxDataTable.id)
{
_selectAll();
}
});
$scope.$on('lx-data-table__unselect', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_unselect(row);
}
});
$scope.$on('lx-data-table__unselect-all', function(event, id)
{
if (id === lxDataTable.id)
{
_unselectAll();
}
});
////////////
function _selectAll()
{
lxDataTable.selectedRows.length = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = true;
lxDataTable.selectedRows.push(lxDataTable.tbody[i]);
}
}
lxDataTable.allRowsSelected = true;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
function _select(row)
{
toggle(row, true);
}
function _unselectAll()
{
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = false;
}
}
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows.length = 0;
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
function _unselect(row)
{
toggle(row, false);
}
////////////
function areAllRowsSelected()
{
var displayedRows = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
displayedRows++;
}
}
if (displayedRows === lxDataTable.selectedRows.length)
{
lxDataTable.allRowsSelected = true;
}
else
{
lxDataTable.allRowsSelected = false;
}
}
function sort(_column)
{
if (!_column.sortable)
{
return;
}
for (var i = 0, len = lxDataTable.thead.length; i < len; i++)
{
if (lxDataTable.thead[i].sortable && lxDataTable.thead[i].name !== _column.name)
{
lxDataTable.thead[i].sort = undefined;
}
}
if (!_column.sort || _column.sort === 'desc')
{
_column.sort = 'asc';
}
else
{
_column.sort = 'desc';
}
$rootScope.$broadcast('lx-data-table__sorted', lxDataTable.id, _column);
}
function toggle(_row, _newSelectedStatus)
{
if (_row.lxDataTableDisabled || !lxDataTable.selectable)
{
return;
}
_row.lxDataTableSelected = angular.isDefined(_newSelectedStatus) ? _newSelectedStatus : !_row.lxDataTableSelected;
if (_row.lxDataTableSelected)
{
// Make sure it's not already in.
if (lxDataTable.selectedRows.length === 0 || (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) === -1))
{
lxDataTable.selectedRows.push(_row);
lxDataTable.areAllRowsSelected();
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
}
else
{
if (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) > -1)
{
lxDataTable.selectedRows.splice(lxDataTable.selectedRows.indexOf(_row), 1);
lxDataTable.allRowsSelected = false;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
}
}
function toggleAllSelected()
{
if (lxDataTable.allRowsSelected)
{
_unselectAll();
}
else
{
_selectAll();
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.service('LxDataTableService', LxDataTableService);
LxDataTableService.$inject = ['$rootScope'];
function LxDataTableService($rootScope)
{
var service = this;
service.select = select;
service.selectAll = selectAll;
service.unselect = unselect;
service.unselectAll = unselectAll;
////////////
function select(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__select', _dataTableId, row);
}
function selectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__select-all', _dataTableId);
}
function unselect(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__unselect', _dataTableId, row);
}
function unselectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__unselect-all', _dataTableId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.directive('lxDatePicker', lxDatePicker);
lxDatePicker.$inject = ['LxDatePickerService', 'LxUtils'];
function lxDatePicker(LxDatePickerService, LxUtils)
{
return {
restrict: 'AE',
templateUrl: 'date-picker.html',
scope:
{
autoClose: '=?lxAutoClose',
callback: '&?lxCallback',
color: '@?lxColor',
escapeClose: '=?lxEscapeClose',
inputFormat: '@?lxInputFormat',
maxDate: '=?lxMaxDate',
ngModel: '=',
minDate: '=?lxMinDate',
locale: '@lxLocale'
},
link: link,
controller: LxDatePickerController,
controllerAs: 'lxDatePicker',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
if (angular.isDefined(attrs.id))
{
attrs.$observe('id', function(_newId)
{
scope.lxDatePicker.pickerId = _newId;
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
});
}
else
{
scope.lxDatePicker.pickerId = LxUtils.generateUUID();
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
}
}
}
LxDatePickerController.$inject = ['$element', '$scope', '$timeout', '$transclude', 'LxDatePickerService', 'LxUtils'];
function LxDatePickerController($element, $scope, $timeout, $transclude, LxDatePickerService, LxUtils)
{
var lxDatePicker = this;
var input;
var modelController;
var timer1;
var timer2;
var watcher1;
var watcher2;
lxDatePicker.closeDatePicker = closeDatePicker;
lxDatePicker.displayYearSelection = displayYearSelection;
lxDatePicker.hideYearSelection = hideYearSelection;
lxDatePicker.getDateFormatted = getDateFormatted;
lxDatePicker.nextMonth = nextMonth;
lxDatePicker.openDatePicker = openDatePicker;
lxDatePicker.previousMonth = previousMonth;
lxDatePicker.select = select;
lxDatePicker.selectYear = selectYear;
lxDatePicker.autoClose = angular.isDefined(lxDatePicker.autoClose) ? lxDatePicker.autoClose : true;
lxDatePicker.color = angular.isDefined(lxDatePicker.color) ? lxDatePicker.color : 'primary';
lxDatePicker.element = $element.find('.lx-date-picker');
lxDatePicker.escapeClose = angular.isDefined(lxDatePicker.escapeClose) ? lxDatePicker.escapeClose : true;
lxDatePicker.isOpen = false;
lxDatePicker.moment = moment;
lxDatePicker.yearSelection = false;
lxDatePicker.uuid = LxUtils.generateUUID();
$transclude(function(clone)
{
if (clone.length)
{
lxDatePicker.hasInput = true;
timer1 = $timeout(function()
{
input = $element.find('.lx-date-input input');
modelController = input.data('$ngModelController');
watcher2 = $scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isUndefined(newValue))
{
lxDatePicker.ngModel = undefined;
}
});
});
}
});
watcher1 = $scope.$watch(function()
{
return lxDatePicker.ngModel;
}, init);
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
if (angular.isFunction(watcher1))
{
watcher1();
}
if (angular.isFunction(watcher2))
{
watcher2();
}
});
////////////
function closeDatePicker()
{
LxDatePickerService.close(lxDatePicker.pickerId);
}
function displayYearSelection()
{
lxDatePicker.yearSelection = true;
timer2 = $timeout(function()
{
var yearSelector = angular.element('.lx-date-picker__year-selector');
var activeYear = yearSelector.find('.lx-date-picker__year--is-active');
yearSelector.scrollTop(yearSelector.scrollTop() + activeYear.position().top - yearSelector.height() / 2 + activeYear.height() / 2);
});
}
function hideYearSelection()
{
lxDatePicker.yearSelection = false;
}
function generateCalendar()
{
lxDatePicker.days = [];
var previousDay = angular.copy(lxDatePicker.ngModelMoment).date(0);
var firstDayOfMonth = angular.copy(lxDatePicker.ngModelMoment).date(1);
var lastDayOfMonth = firstDayOfMonth.clone().endOf('month');
var maxDays = lastDayOfMonth.date();
lxDatePicker.emptyFirstDays = [];
for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
{
lxDatePicker.emptyFirstDays.push(
{});
}
for (var j = 0; j < maxDays; j++)
{
var date = angular.copy(previousDay.add(1, 'days'));
date.selected = angular.isDefined(lxDatePicker.ngModel) && date.isSame(lxDatePicker.ngModel, 'day');
date.today = date.isSame(moment(), 'day');
if (angular.isDefined(lxDatePicker.minDate) && date.toDate() < lxDatePicker.minDate)
{
date.disabled = true;
}
if (angular.isDefined(lxDatePicker.maxDate) && date.toDate() > lxDatePicker.maxDate)
{
date.disabled = true;
}
lxDatePicker.days.push(date);
}
lxDatePicker.emptyLastDays = [];
for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
{
lxDatePicker.emptyLastDays.push(
{});
}
}
function getDateFormatted()
{
var dateFormatted = lxDatePicker.ngModelMoment.format('llll').replace(lxDatePicker.ngModelMoment.format('LT'), '').trim().replace(lxDatePicker.ngModelMoment.format('YYYY'), '').trim();
var dateFormattedLastChar = dateFormatted.slice(-1);
if (dateFormattedLastChar === ',')
{
dateFormatted = dateFormatted.slice(0, -1);
}
return dateFormatted;
}
function init()
{
moment.locale(lxDatePicker.locale);
lxDatePicker.ngModelMoment = angular.isDefined(lxDatePicker.ngModel) ? moment(angular.copy(lxDatePicker.ngModel)) : moment();
lxDatePicker.days = [];
lxDatePicker.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];
lxDatePicker.years = [];
for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
{
lxDatePicker.years.push(y);
}
generateCalendar();
}
function nextMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.add(1, 'month');
generateCalendar();
}
function openDatePicker()
{
LxDatePickerService.open(lxDatePicker.pickerId);
}
function previousMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.subtract(1, 'month');
generateCalendar();
}
function select(_day)
{
if (!_day.disabled)
{
lxDatePicker.ngModel = _day.toDate();
lxDatePicker.ngModelMoment = angular.copy(_day);
if (angular.isDefined(lxDatePicker.callback))
{
lxDatePicker.callback(
{
newDate: lxDatePicker.ngModel
});
}
if (angular.isDefined(modelController) && lxDatePicker.inputFormat)
{
modelController.$setViewValue(angular.copy(_day).format(lxDatePicker.inputFormat));
modelController.$render();
}
generateCalendar();
}
}
function selectYear(_year)
{
lxDatePicker.yearSelection = false;
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.year(_year);
generateCalendar();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.service('LxDatePickerService', LxDatePickerService);
LxDatePickerService.$inject = ['$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxDatePickerService($rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var activeDatePickerId;
var datePickerFilter;
var idEventScheduler;
var scopeMap = {};
service.close = closeDatePicker;
service.open = openDatePicker;
service.registerScope = registerScope;
////////////
function closeDatePicker(_datePickerId)
{
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
activeDatePickerId = undefined;
$rootScope.$broadcast('lx-date-picker__close-start', _datePickerId);
datePickerFilter.removeClass('lx-date-picker-filter--is-shown');
scopeMap[_datePickerId].element.removeClass('lx-date-picker--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter.remove();
scopeMap[_datePickerId].element
.hide()
.appendTo(scopeMap[_datePickerId].elementParent);
scopeMap[_datePickerId].isOpen = false;
$rootScope.$broadcast('lx-date-picker__close-end', _datePickerId);
}, 600);
}
function onKeyUp(_event)
{
if (_event.keyCode == 27 && angular.isDefined(activeDatePickerId))
{
closeDatePicker(activeDatePickerId);
}
_event.stopPropagation();
}
function openDatePicker(_datePickerId)
{
LxDepthService.register();
activeDatePickerId = _datePickerId;
angular.element('body').addClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter = angular.element('<div/>',
{
class: 'lx-date-picker-filter'
});
datePickerFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (scopeMap[activeDatePickerId].autoClose)
{
datePickerFilter.on('click', function()
{
closeDatePicker(activeDatePickerId);
});
}
if (scopeMap[activeDatePickerId].escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
scopeMap[activeDatePickerId].element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-start', activeDatePickerId);
scopeMap[activeDatePickerId].isOpen = true;
datePickerFilter.addClass('lx-date-picker-filter--is-shown');
scopeMap[activeDatePickerId].element.addClass('lx-date-picker--is-shown');
}, 100);
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-end', activeDatePickerId);
}, 700);
}
function registerScope(_datePickerId, _datePickerScope)
{
scopeMap[_datePickerId] = _datePickerScope.lxDatePicker;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.directive('lxDialog', lxDialog)
.directive('lxDialogHeader', lxDialogHeader)
.directive('lxDialogContent', lxDialogContent)
.directive('lxDialogFooter', lxDialogFooter)
.directive('lxDialogClose', lxDialogClose);
function lxDialog()
{
return {
restrict: 'E',
template: '<div class="dialog" ng-class="{ \'dialog--l\': !lxDialog.size || lxDialog.size === \'l\', \'dialog--s\': lxDialog.size === \'s\', \'dialog--m\': lxDialog.size === \'m\' }"><div ng-if="lxDialog.isOpen" ng-transclude></div></div>',
scope:
{
autoClose: '=?lxAutoClose',
escapeClose: '=?lxEscapeClose',
size: '@?lxSize'
},
link: link,
controller: LxDialogController,
controllerAs: 'lxDialog',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDialogController.$inject = ['$element', '$interval', '$rootScope', '$scope', '$timeout', '$window', 'LxDepthService', 'LxEventSchedulerService', 'LxUtils'];
function LxDialogController($element, $interval, $rootScope, $scope, $timeout, $window, LxDepthService, LxEventSchedulerService, LxUtils)
{
var lxDialog = this;
var dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
var dialogHeight;
var dialogInterval;
var dialogScrollable;
var elementParent = $element.parent();
var idEventScheduler;
var resizeDebounce;
var windowHeight;
lxDialog.autoClose = angular.isDefined(lxDialog.autoClose) ? lxDialog.autoClose : true;
lxDialog.escapeClose = angular.isDefined(lxDialog.escapeClose) ? lxDialog.escapeClose : true;
lxDialog.isOpen = false;
lxDialog.uuid = LxUtils.generateUUID();
$scope.$on('lx-dialog__open', function(event, id)
{
if (id === lxDialog.id)
{
open();
}
});
$scope.$on('lx-dialog__close', function(event, id)
{
if (id === lxDialog.id)
{
close();
}
});
$scope.$on('$destroy', function()
{
close();
});
////////////
function checkDialogHeight()
{
var dialog = $element;
var dialogHeader = dialog.find('.dialog__header');
var dialogContent = dialog.find('.dialog__content');
var dialogFooter = dialog.find('.dialog__footer');
if (!dialogFooter.length)
{
dialogFooter = dialog.find('.dialog__actions');
}
if (angular.isUndefined(dialogHeader))
{
return;
}
var heightToCheck = 60 + dialogHeader.outerHeight() + dialogContent.outerHeight() + dialogFooter.outerHeight();
if (dialogHeight === heightToCheck && windowHeight === $window.innerHeight)
{
return;
}
dialogHeight = heightToCheck;
windowHeight = $window.innerHeight;
if (heightToCheck >= $window.innerHeight)
{
dialog.addClass('dialog--is-fixed');
dialogScrollable
.css(
{
top: dialogHeader.outerHeight(),
bottom: dialogFooter.outerHeight()
})
.off('scroll', checkScrollEnd)
.on('scroll', checkScrollEnd);
}
else
{
dialog.removeClass('dialog--is-fixed');
dialogScrollable
.removeAttr('style')
.off('scroll', checkScrollEnd);
}
}
function checkDialogHeightOnResize()
{
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
resizeDebounce = $timeout(function()
{
checkDialogHeight();
}, 200);
}
function checkScrollEnd()
{
if (dialogScrollable.scrollTop() + dialogScrollable.innerHeight() >= dialogScrollable[0].scrollHeight)
{
$rootScope.$broadcast('lx-dialog__scroll-end', lxDialog.id);
dialogScrollable.off('scroll', checkScrollEnd);
$timeout(function()
{
dialogScrollable.on('scroll', checkScrollEnd);
}, 500);
}
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
close();
}
_event.stopPropagation();
}
function open()
{
if (lxDialog.isOpen)
{
return;
}
LxDepthService.register();
angular.element('body').addClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (lxDialog.autoClose)
{
dialogFilter.on('click', function()
{
close();
});
}
if (lxDialog.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
$element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-start', lxDialog.id);
lxDialog.isOpen = true;
dialogFilter.addClass('dialog-filter--is-shown');
$element.addClass('dialog--is-shown');
}, 100);
$timeout(function()
{
if ($element.find('.dialog__scrollable').length === 0)
{
$element.find('.dialog__content').wrap(angular.element('<div/>',
{
class: 'dialog__scrollable'
}));
}
dialogScrollable = $element.find('.dialog__scrollable');
}, 200);
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-end', lxDialog.id);
}, 700);
dialogInterval = $interval(function()
{
checkDialogHeight();
}, 500);
angular.element($window).on('resize', checkDialogHeightOnResize);
}
function close()
{
if (!lxDialog.isOpen)
{
return;
}
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
angular.element($window).off('resize', checkDialogHeightOnResize);
$element.find('.dialog__scrollable').off('scroll', checkScrollEnd);
$rootScope.$broadcast('lx-dialog__close-start', lxDialog.id);
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
$interval.cancel(dialogInterval);
dialogFilter.removeClass('dialog-filter--is-shown');
$element.removeClass('dialog--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter.remove();
$element
.hide()
.removeClass('dialog--is-fixed')
.appendTo(elementParent);
lxDialog.isOpen = false;
dialogHeight = undefined;
$rootScope.$broadcast('lx-dialog__close-end', lxDialog.id);
}, 600);
}
}
function lxDialogHeader()
{
return {
restrict: 'E',
template: '<div class="dialog__header" ng-transclude></div>',
replace: true,
transclude: true
};
}
function lxDialogContent()
{
return {
restrict: 'E',
template: '<div class="dialog__scrollable"><div class="dialog__content" ng-transclude></div></div>',
replace: true,
transclude: true
};
}
function lxDialogFooter()
{
return {
restrict: 'E',
template: '<div class="dialog__footer" ng-transclude></div>',
replace: true,
transclude: true
};
}
lxDialogClose.$inject = ['LxDialogService'];
function lxDialogClose(LxDialogService)
{
return {
restrict: 'A',
link: function(scope, element)
{
element.on('click', function()
{
LxDialogService.close(element.parents('.dialog').attr('id'));
});
scope.$on('$destroy', function()
{
element.off();
});
}
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.service('LxDialogService', LxDialogService);
LxDialogService.$inject = ['$rootScope'];
function LxDialogService($rootScope)
{
var service = this;
service.open = open;
service.close = close;
////////////
function open(_dialogId)
{
$rootScope.$broadcast('lx-dialog__open', _dialogId);
}
function close(_dialogId)
{
$rootScope.$broadcast('lx-dialog__close', _dialogId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.directive('lxDropdown', lxDropdown)
.directive('lxDropdownToggle', lxDropdownToggle)
.directive('lxDropdownMenu', lxDropdownMenu)
.directive('lxDropdownFilter', lxDropdownFilter);
function lxDropdown()
{
return {
restrict: 'E',
templateUrl: 'dropdown.html',
scope:
{
depth: '@?lxDepth',
effect: '@?lxEffect',
escapeClose: '=?lxEscapeClose',
hover: '=?lxHover',
hoverDelay: '=?lxHoverDelay',
offset: '@?lxOffset',
overToggle: '=?lxOverToggle',
position: '@?lxPosition',
width: '@?lxWidth'
},
link: link,
controller: LxDropdownController,
controllerAs: 'lxDropdown',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var backwardOneWay = ['position', 'width'];
var backwardTwoWay = ['escapeClose', 'overToggle'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
attrs.$observe('id', function(_newId)
{
ctrl.uuid = _newId;
});
scope.$on('$destroy', function()
{
if (ctrl.isOpen)
{
ctrl.closeDropdownMenu();
}
});
}
}
LxDropdownController.$inject = ['$element', '$interval', '$scope', '$timeout', '$window', 'LxDepthService',
'LxDropdownService', 'LxEventSchedulerService', 'LxUtils'
];
function LxDropdownController($element, $interval, $scope, $timeout, $window, LxDepthService,
LxDropdownService, LxEventSchedulerService, LxUtils)
{
var lxDropdown = this;
var dropdownInterval;
var dropdownMenu;
var dropdownToggle;
var idEventScheduler;
var openTimeout;
var positionTarget;
var scrollMask = angular.element('<div/>',
{
class: 'scroll-mask'
});
var enableBodyScroll;
lxDropdown.closeDropdownMenu = closeDropdownMenu;
lxDropdown.openDropdownMenu = openDropdownMenu;
lxDropdown.registerDropdownMenu = registerDropdownMenu;
lxDropdown.registerDropdownToggle = registerDropdownToggle;
lxDropdown.toggle = toggle;
lxDropdown.uuid = LxUtils.generateUUID();
lxDropdown.effect = angular.isDefined(lxDropdown.effect) ? lxDropdown.effect : 'expand';
lxDropdown.escapeClose = angular.isDefined(lxDropdown.escapeClose) ? lxDropdown.escapeClose : true;
lxDropdown.hasToggle = false;
lxDropdown.isOpen = false;
lxDropdown.overToggle = angular.isDefined(lxDropdown.overToggle) ? lxDropdown.overToggle : false;
lxDropdown.position = angular.isDefined(lxDropdown.position) ? lxDropdown.position : 'left';
$scope.$on('lx-dropdown__open', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && !lxDropdown.isOpen)
{
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(lxDropdown.uuid);
positionTarget = _params.target;
registerDropdownToggle(angular.element(positionTarget));
openDropdownMenu();
}
});
$scope.$on('lx-dropdown__close', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && lxDropdown.isOpen)
{
closeDropdownMenu();
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(openTimeout);
});
////////////
function closeDropdownMenu()
{
$interval.cancel(dropdownInterval);
LxDropdownService.resetActiveDropdownUuid();
var velocityProperties;
var velocityEasing;
scrollMask.remove();
if (angular.isFunction(enableBodyScroll)) {
enableBodyScroll();
}
enableBodyScroll = undefined;
if (lxDropdown.hasToggle)
{
dropdownToggle
.off('wheel')
.css('z-index', '');
}
dropdownMenu
.off('wheel')
.css(
{
overflow: 'hidden'
});
if (lxDropdown.effect === 'expand')
{
velocityProperties = {
width: 0,
height: 0
};
velocityEasing = 'easeOutQuint';
}
else if (lxDropdown.effect === 'fade')
{
velocityProperties = {
opacity: 0
};
velocityEasing = 'linear';
}
if (lxDropdown.effect === 'expand' || lxDropdown.effect === 'fade')
{
dropdownMenu.velocity(velocityProperties,
{
duration: 200,
easing: velocityEasing,
complete: function()
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
$scope.$apply(function()
{
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
});
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
}
}
function getAvailableHeight()
{
var availableHeightOnTop;
var availableHeightOnBottom;
var direction;
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowHeight = $window.innerHeight;
if (lxDropdown.overToggle)
{
availableHeightOnTop = dropdownToggleTop + dropdownToggleHeight;
availableHeightOnBottom = windowHeight - dropdownToggleTop;
}
else
{
availableHeightOnTop = dropdownToggleTop;
availableHeightOnBottom = windowHeight - (dropdownToggleTop + dropdownToggleHeight);
}
if (availableHeightOnTop > availableHeightOnBottom)
{
direction = 'top';
}
else
{
direction = 'bottom';
}
return {
top: availableHeightOnTop,
bottom: availableHeightOnBottom,
direction: direction
};
}
function initDropdownPosition()
{
var availableHeight = getAvailableHeight();
var dropdownMenuWidth;
var dropdownMenuLeft;
var dropdownMenuRight;
var dropdownToggleWidth = dropdownToggle.outerWidth();
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowWidth = $window.innerWidth;
var windowHeight = $window.innerHeight;
if (angular.isDefined(lxDropdown.width))
{
if (lxDropdown.width.indexOf('%') > -1)
{
dropdownMenuWidth = dropdownToggleWidth * (lxDropdown.width.slice(0, -1) / 100);
}
else
{
dropdownMenuWidth = lxDropdown.width;
}
}
else
{
dropdownMenuWidth = 'auto';
}
if (lxDropdown.position === 'left')
{
dropdownMenuLeft = dropdownToggle.offset().left;
dropdownMenuRight = 'auto';
}
else if (lxDropdown.position === 'right')
{
dropdownMenuLeft = 'auto';
dropdownMenuRight = windowWidth - dropdownToggle.offset().left - dropdownToggleWidth;
}
else if (lxDropdown.position === 'center')
{
dropdownMenuLeft = (dropdownToggle.offset().left + (dropdownToggleWidth / 2)) - (dropdownMenuWidth / 2);
dropdownMenuRight = 'auto';
}
dropdownMenu.css(
{
left: dropdownMenuLeft,
right: dropdownMenuRight,
width: dropdownMenuWidth
});
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
bottom: lxDropdown.overToggle ? (windowHeight - dropdownToggleTop - dropdownToggleHeight) : (windowHeight - dropdownToggleTop + ~~lxDropdown.offset)
});
return availableHeight.top;
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
top: lxDropdown.overToggle ? dropdownToggleTop : (dropdownToggleTop + dropdownToggleHeight + ~~lxDropdown.offset)
});
return availableHeight.bottom;
}
}
function openDropdownMenu()
{
lxDropdown.isOpen = true;
LxDepthService.register();
scrollMask
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
scrollMask.on('wheel', function preventDefault(e) {
e.preventDefault();
});
enableBodyScroll = LxUtils.disableBodyScroll();
if (lxDropdown.hasToggle)
{
dropdownToggle
.css('z-index', LxDepthService.getDepth() + 1)
.on('wheel', function preventDefault(e) {
e.preventDefault();
});
}
dropdownMenu
.addClass('dropdown-menu--is-open')
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body');
dropdownMenu.on('wheel', function preventDefault(e) {
var d = e.originalEvent.deltaY;
if (d < 0 && dropdownMenu.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d > 0 && (dropdownMenu.scrollTop() == dropdownMenu.get(0).scrollHeight - dropdownMenu.innerHeight())) {
e.preventDefault();
}
}
});
if (lxDropdown.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
openTimeout = $timeout(function()
{
var availableHeight = initDropdownPosition() - ~~lxDropdown.offset;
var dropdownMenuHeight = dropdownMenu.outerHeight();
var dropdownMenuWidth = dropdownMenu.outerWidth();
var enoughHeight = true;
if (availableHeight < dropdownMenuHeight)
{
enoughHeight = false;
dropdownMenuHeight = availableHeight;
}
if (lxDropdown.effect === 'expand')
{
dropdownMenu.css(
{
width: 0,
height: 0,
opacity: 1,
overflow: 'hidden'
});
dropdownMenu.find('.dropdown-menu__content').css(
{
width: dropdownMenuWidth,
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
width: dropdownMenuWidth
},
{
duration: 200,
easing: 'easeOutQuint',
queue: false
});
dropdownMenu.velocity(
{
height: dropdownMenuHeight
},
{
duration: 500,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
dropdownMenu.css(
{
overflow: 'auto'
});
if (angular.isUndefined(lxDropdown.width))
{
dropdownMenu.css(
{
width: 'auto'
});
}
$timeout(updateDropdownMenuHeight);
dropdownMenu.find('.dropdown-menu__content').removeAttr('style');
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'fade')
{
dropdownMenu.css(
{
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
opacity: 1,
},
{
duration: 200,
easing: 'linear',
queue: false,
complete: function()
{
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu.css(
{
opacity: 1
});
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
closeDropdownMenu();
}
_event.stopPropagation();
}
function registerDropdownMenu(_dropdownMenu)
{
dropdownMenu = _dropdownMenu;
}
function registerDropdownToggle(_dropdownToggle)
{
if (!positionTarget)
{
lxDropdown.hasToggle = true;
}
dropdownToggle = _dropdownToggle;
}
function toggle()
{
if (!lxDropdown.isOpen)
{
openDropdownMenu();
}
else
{
closeDropdownMenu();
}
}
function updateDropdownMenuHeight()
{
if (positionTarget)
{
registerDropdownToggle(angular.element(positionTarget));
}
var availableHeight = getAvailableHeight();
var dropdownMenuHeight = dropdownMenu.find('.dropdown-menu__content').outerHeight();
dropdownMenu.css(
{
height: 'auto'
});
if ((availableHeight[availableHeight.direction] - ~~lxDropdown.offset) < dropdownMenuHeight)
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 0
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 0
});
}
}
else
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 'auto'
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 'auto'
});
}
}
}
}
lxDropdownToggle.$inject = ['$timeout', 'LxDropdownService'];
function lxDropdownToggle($timeout, LxDropdownService)
{
return {
restrict: 'AE',
templateUrl: 'dropdown-toggle.html',
require: '^lxDropdown',
scope: true,
link: link,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var hoverTimeout = [];
var mouseEvent = ctrl.hover ? 'mouseenter' : 'click';
ctrl.registerDropdownToggle(element);
element.on(mouseEvent, function(_event)
{
if (mouseEvent === 'mouseenter' && 'ontouchstart' in window) {
return;
}
if (!ctrl.hover)
{
_event.stopPropagation();
}
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(ctrl.uuid);
if (ctrl.hover)
{
ctrl.mouseOnToggle = true;
if (!ctrl.isOpen)
{
hoverTimeout[0] = $timeout(function()
{
scope.$apply(function()
{
ctrl.openDropdownMenu();
});
}, ctrl.hoverDelay);
}
}
else
{
scope.$apply(function()
{
ctrl.toggle();
});
}
});
if (ctrl.hover)
{
element.on('mouseleave', function()
{
ctrl.mouseOnToggle = false;
$timeout.cancel(hoverTimeout[0]);
hoverTimeout[1] = $timeout(function()
{
if (!ctrl.mouseOnMenu)
{
scope.$apply(function()
{
ctrl.closeDropdownMenu();
});
}
}, ctrl.hoverDelay);
});
}
scope.$on('$destroy', function()
{
element.off();
if (ctrl.hover)
{
$timeout.cancel(hoverTimeout[0]);
$timeout.cancel(hoverTimeout[1]);
}
});
}
}
lxDropdownMenu.$inject = ['$timeout'];
function lxDropdownMenu($timeout)
{
return {
restrict: 'E',
templateUrl: 'dropdown-menu.html',
require: ['lxDropdownMenu', '^lxDropdown'],
scope: true,
link: link,
controller: LxDropdownMenuController,
controllerAs: 'lxDropdownMenu',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
var hoverTimeout;
ctrls[1].registerDropdownMenu(element);
ctrls[0].setParentController(ctrls[1]);
if (ctrls[1].hover)
{
element.on('mouseenter', function()
{
ctrls[1].mouseOnMenu = true;
});
element.on('mouseleave', function()
{
ctrls[1].mouseOnMenu = false;
hoverTimeout = $timeout(function()
{
if (!ctrls[1].mouseOnToggle)
{
scope.$apply(function()
{
ctrls[1].closeDropdownMenu();
});
}
}, ctrls[1].hoverDelay);
});
}
scope.$on('$destroy', function()
{
if (ctrls[1].hover)
{
element.off();
$timeout.cancel(hoverTimeout);
}
});
}
}
LxDropdownMenuController.$inject = ['$element'];
function LxDropdownMenuController($element)
{
var lxDropdownMenu = this;
lxDropdownMenu.setParentController = setParentController;
////////////
function addDropdownDepth()
{
if (lxDropdownMenu.parentCtrl.depth)
{
$element.addClass('dropdown-menu--depth-' + lxDropdownMenu.parentCtrl.depth);
}
else
{
$element.addClass('dropdown-menu--depth-1');
}
}
function setParentController(_parentCtrl)
{
lxDropdownMenu.parentCtrl = _parentCtrl;
addDropdownDepth();
}
}
lxDropdownFilter.$inject = ['$timeout'];
function lxDropdownFilter($timeout)
{
return {
restrict: 'A',
link: link
};
function link(scope, element)
{
var focusTimeout;
element.on('click', function(_event)
{
_event.stopPropagation();
});
focusTimeout = $timeout(function()
{
element.find('input').focus();
}, 200);
scope.$on('$destroy', function()
{
$timeout.cancel(focusTimeout);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.service('LxDropdownService', LxDropdownService);
LxDropdownService.$inject = ['$document', '$rootScope', '$timeout'];
function LxDropdownService($document, $rootScope, $timeout)
{
var service = this;
var activeDropdownUuid;
service.close = close;
service.closeActiveDropdown = closeActiveDropdown;
service.open = open;
service.isOpen = isOpen;
service.registerActiveDropdownUuid = registerActiveDropdownUuid;
service.resetActiveDropdownUuid = resetActiveDropdownUuid;
$document.on('click', closeActiveDropdown);
////////////
function close(_uuid)
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: _uuid
});
}
function closeActiveDropdown()
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: activeDropdownUuid
});
}
function open(_uuid, _target)
{
$rootScope.$broadcast('lx-dropdown__open',
{
uuid: _uuid,
target: _target
});
}
function isOpen(_uuid)
{
return activeDropdownUuid === _uuid;
}
function registerActiveDropdownUuid(_uuid)
{
activeDropdownUuid = _uuid;
}
function resetActiveDropdownUuid()
{
activeDropdownUuid = undefined;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.fab')
.directive('lxFab', lxFab)
.directive('lxFabTrigger', lxFabTrigger)
.directive('lxFabActions', lxFabActions);
function lxFab()
{
return {
restrict: 'E',
templateUrl: 'fab.html',
scope: true,
link: link,
controller: LxFabController,
controllerAs: 'lxFab',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('lxDirection', function(newDirection)
{
ctrl.setFabDirection(newDirection);
});
}
}
function LxFabController()
{
var lxFab = this;
lxFab.setFabDirection = setFabDirection;
////////////
function setFabDirection(_direction)
{
lxFab.lxDirection = _direction;
}
}
function lxFabTrigger()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-trigger.html',
transclude: true,
replace: true
};
}
function lxFabActions()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-actions.html',
link: link,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
scope.parentCtrl = ctrl;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.file-input')
.directive('lxFileInput', lxFileInput);
function lxFileInput()
{
return {
restrict: 'E',
templateUrl: 'file-input.html',
scope:
{
label: '@lxLabel',
callback: '&?lxCallback'
},
link: link,
controller: LxFileInputController,
controllerAs: 'lxFileInput',
bindToController: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
var input = element.find('input');
input
.on('change', ctrl.updateModel)
.on('blur', function()
{
element.removeClass('input-file--is-focus');
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxFileInputController.$inject = ['$element', '$scope', '$timeout'];
function LxFileInputController($element, $scope, $timeout)
{
var lxFileInput = this;
var input = $element.find('input');
var timer;
lxFileInput.updateModel = updateModel;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function setFileName()
{
if (input.val())
{
lxFileInput.fileName = input.val().replace(/C:\\fakepath\\/i, '');
$element.addClass('input-file--is-focus');
$element.addClass('input-file--is-active');
}
else
{
lxFileInput.fileName = undefined;
$element.removeClass('input-file--is-active');
}
input.val(undefined);
}
function updateModel()
{
if (angular.isDefined(lxFileInput.callback))
{
lxFileInput.callback(
{
newFile: input[0].files[0]
});
}
timer = $timeout(setFileName);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.icon')
.directive('lxIcon', lxIcon);
function lxIcon()
{
return {
restrict: 'E',
templateUrl: 'icon.html',
scope:
{
color: '@?lxColor',
id: '@lxId',
size: '@?lxSize',
type: '@?lxType'
},
controller: LxIconController,
controllerAs: 'lxIcon',
bindToController: true,
replace: true
};
}
function LxIconController()
{
var lxIcon = this;
lxIcon.getClass = getClass;
////////////
function getClass()
{
var iconClass = [];
iconClass.push('mdi-' + lxIcon.id);
if (angular.isDefined(lxIcon.size))
{
iconClass.push('icon--' + lxIcon.size);
}
if (angular.isDefined(lxIcon.color))
{
iconClass.push('icon--' + lxIcon.color);
}
if (angular.isDefined(lxIcon.type))
{
iconClass.push('icon--' + lxIcon.type);
}
return iconClass;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.notification')
.service('LxNotificationService', LxNotificationService);
LxNotificationService.$inject = ['$injector', '$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxNotificationService($injector, $rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var dialogFilter;
var dialog;
var idEventScheduler;
var notificationList = [];
var actionClicked = false;
service.alert = showAlertDialog;
service.confirm = showConfirmDialog;
service.error = notifyError;
service.info = notifyInfo;
service.notify = notify;
service.success = notifySuccess;
service.warning = notifyWarning;
////////////
//
// NOTIFICATION
//
function deleteNotification(_notification, _callback)
{
_callback = (!angular.isFunction(_callback)) ? angular.noop : _callback;
var notifIndex = notificationList.indexOf(_notification);
var dnOffset = angular.isDefined(notificationList[notifIndex]) ? 24 + notificationList[notifIndex].height : 24;
for (var idx = 0; idx < notifIndex; idx++)
{
if (notificationList.length > 1)
{
notificationList[idx].margin -= dnOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
_notification.elem.removeClass('notification--is-shown');
$timeout(function()
{
_notification.elem.remove();
// Find index again because notificationList may have changed
notifIndex = notificationList.indexOf(_notification);
if (notifIndex != -1)
{
notificationList.splice(notifIndex, 1);
}
_callback(actionClicked);
actionClicked = false
}, 400);
}
function getElementHeight(_elem)
{
return parseFloat(window.getComputedStyle(_elem, null).height);
}
function moveNotificationUp()
{
var newNotifIndex = notificationList.length - 1;
notificationList[newNotifIndex].height = getElementHeight(notificationList[newNotifIndex].elem[0]);
var upOffset = 0;
for (var idx = newNotifIndex; idx >= 0; idx--)
{
if (notificationList.length > 1 && idx !== newNotifIndex)
{
upOffset = 24 + notificationList[newNotifIndex].height;
notificationList[idx].margin += upOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
}
function notify(_text, _icon, _sticky, _color, _action, _callback, _delay)
{
var $compile = $injector.get('$compile');
LxDepthService.register();
var notification = angular.element('<div/>',
{
class: 'notification'
});
var notificationText = angular.element('<span/>',
{
class: 'notification__content',
html: _text
});
var notificationTimeout;
var notificationDelay = _delay || 6000;
if (angular.isDefined(_icon))
{
var notificationIcon = angular.element('<i/>',
{
class: 'notification__icon mdi mdi-' + _icon
});
notification
.addClass('notification--has-icon')
.append(notificationIcon);
}
if (angular.isDefined(_color))
{
notification.addClass('notification--' + _color);
}
notification.append(notificationText);
if (angular.isDefined(_action))
{
var notificationAction = angular.element('<button/>',
{
class: 'notification__action btn btn--m btn--flat',
html: _action
});
if (angular.isDefined(_color))
{
notificationAction.addClass('btn--' + _color);
}
else
{
notificationAction.addClass('btn--white');
}
notificationAction.attr('lx-ripple', '');
$compile(notificationAction)($rootScope);
notificationAction.bind('click', function()
{
actionClicked = true;
});
notification
.addClass('notification--has-action')
.append(notificationAction);
}
notification
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
$timeout(function()
{
notification.addClass('notification--is-shown');
}, 100);
var data = {
elem: notification,
margin: 0
};
notificationList.push(data);
moveNotificationUp();
notification.bind('click', function()
{
deleteNotification(data, _callback);
if (angular.isDefined(notificationTimeout))
{
$timeout.cancel(notificationTimeout);
}
});
if (angular.isUndefined(_sticky) || !_sticky)
{
notificationTimeout = $timeout(function()
{
deleteNotification(data, _callback);
}, notificationDelay);
}
}
function notifyError(_text, _sticky)
{
notify(_text, 'alert-circle', _sticky, 'red');
}
function notifyInfo(_text, _sticky)
{
notify(_text, 'information-outline', _sticky, 'blue');
}
function notifySuccess(_text, _sticky)
{
notify(_text, 'check', _sticky, 'green');
}
function notifyWarning(_text, _sticky)
{
notify(_text, 'alert', _sticky, 'orange');
}
//
// ALERT & CONFIRM
//
function buildDialogActions(_buttons, _callback, _unbind)
{
var $compile = $injector.get('$compile');
var dialogActions = angular.element('<div/>',
{
class: 'dialog__actions'
});
var dialogLastBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--blue btn--flat',
text: _buttons.ok
});
if (angular.isDefined(_buttons.cancel))
{
var dialogFirstBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--red btn--flat',
text: _buttons.cancel
});
dialogFirstBtn.attr('lx-ripple', '');
$compile(dialogFirstBtn)($rootScope);
dialogActions.append(dialogFirstBtn);
dialogFirstBtn.bind('click', function()
{
_callback(false);
closeDialog();
});
}
dialogLastBtn.attr('lx-ripple', '');
$compile(dialogLastBtn)($rootScope);
dialogActions.append(dialogLastBtn);
dialogLastBtn.bind('click', function()
{
_callback(true);
closeDialog();
});
if (!_unbind)
{
idEventScheduler = LxEventSchedulerService.register('keyup', function(event)
{
if (event.keyCode == 13)
{
_callback(true);
closeDialog();
}
else if (event.keyCode == 27)
{
_callback(angular.isUndefined(_buttons.cancel));
closeDialog();
}
event.stopPropagation();
});
}
return dialogActions;
}
function buildDialogContent(_text)
{
var dialogContent = angular.element('<div/>',
{
class: 'dialog__content p++ pt0 tc-black-2',
text: _text
});
return dialogContent;
}
function buildDialogHeader(_title)
{
var dialogHeader = angular.element('<div/>',
{
class: 'dialog__header p++ fs-title',
text: _title
});
return dialogHeader;
}
function closeDialog()
{
if (angular.isDefined(idEventScheduler))
{
$timeout(function()
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}, 1);
}
dialogFilter.removeClass('dialog-filter--is-shown');
dialog.removeClass('dialog--is-shown');
$timeout(function()
{
dialogFilter.remove();
dialog.remove();
}, 600);
}
function showAlertDialog(_title, _text, _button, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(
{
ok: _button
}, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
function showConfirmDialog(_title, _text, _buttons, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(_buttons, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.progress')
.directive('lxProgress', lxProgress);
function lxProgress()
{
return {
restrict: 'E',
templateUrl: 'progress.html',
scope:
{
lxColor: '@?',
lxDiameter: '@?',
lxType: '@',
lxValue: '@'
},
controller: LxProgressController,
controllerAs: 'lxProgress',
bindToController: true,
replace: true
};
}
function LxProgressController()
{
var lxProgress = this;
lxProgress.getCircularProgressValue = getCircularProgressValue;
lxProgress.getLinearProgressValue = getLinearProgressValue;
lxProgress.getProgressDiameter = getProgressDiameter;
init();
////////////
function getCircularProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'stroke-dasharray': lxProgress.lxValue * 1.26 + ',200'
};
}
}
function getLinearProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'transform': 'scale(' + lxProgress.lxValue / 100 + ', 1)'
};
}
}
function getProgressDiameter()
{
if (lxProgress.lxType === 'circular')
{
return {
'transform': 'scale(' + parseInt(lxProgress.lxDiameter) / 100 + ')'
};
}
return;
}
function init()
{
lxProgress.lxDiameter = angular.isDefined(lxProgress.lxDiameter) ? lxProgress.lxDiameter : 100;
lxProgress.lxColor = angular.isDefined(lxProgress.lxColor) ? lxProgress.lxColor : 'primary';
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.radio-button')
.directive('lxRadioGroup', lxRadioGroup)
.directive('lxRadioButton', lxRadioButton)
.directive('lxRadioButtonLabel', lxRadioButtonLabel)
.directive('lxRadioButtonHelp', lxRadioButtonHelp);
function lxRadioGroup()
{
return {
restrict: 'E',
templateUrl: 'radio-group.html',
transclude: true,
replace: true
};
}
function lxRadioButton()
{
return {
restrict: 'E',
templateUrl: 'radio-button.html',
scope:
{
lxColor: '@?',
name: '@',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
ngValue: '=?',
value: '@?'
},
controller: LxRadioButtonController,
controllerAs: 'lxRadioButton',
bindToController: true,
transclude: true,
replace: true
};
}
LxRadioButtonController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxRadioButtonController($scope, $timeout, LxUtils)
{
var lxRadioButton = this;
var radioButtonId;
var radioButtonHasChildren;
var timer;
lxRadioButton.getRadioButtonId = getRadioButtonId;
lxRadioButton.getRadioButtonHasChildren = getRadioButtonHasChildren;
lxRadioButton.setRadioButtonId = setRadioButtonId;
lxRadioButton.setRadioButtonHasChildren = setRadioButtonHasChildren;
lxRadioButton.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function getRadioButtonHasChildren()
{
return radioButtonHasChildren;
}
function init()
{
setRadioButtonId(LxUtils.generateUUID());
setRadioButtonHasChildren(false);
if (angular.isDefined(lxRadioButton.value) && angular.isUndefined(lxRadioButton.ngValue))
{
lxRadioButton.ngValue = lxRadioButton.value;
}
lxRadioButton.lxColor = angular.isUndefined(lxRadioButton.lxColor) ? 'accent' : lxRadioButton.lxColor;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
function setRadioButtonHasChildren(_radioButtonHasChildren)
{
radioButtonHasChildren = _radioButtonHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxRadioButton.ngChange);
}
}
function lxRadioButtonLabel()
{
return {
restrict: 'AE',
require: ['^lxRadioButton', '^lxRadioButtonLabel'],
templateUrl: 'radio-button-label.html',
link: link,
controller: LxRadioButtonLabelController,
controllerAs: 'lxRadioButtonLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setRadioButtonHasChildren(true);
ctrls[1].setRadioButtonId(ctrls[0].getRadioButtonId());
}
}
function LxRadioButtonLabelController()
{
var lxRadioButtonLabel = this;
var radioButtonId;
lxRadioButtonLabel.getRadioButtonId = getRadioButtonId;
lxRadioButtonLabel.setRadioButtonId = setRadioButtonId;
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
}
function lxRadioButtonHelp()
{
return {
restrict: 'AE',
require: '^lxRadioButton',
templateUrl: 'radio-button-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.ripple')
.directive('lxRipple', lxRipple);
lxRipple.$inject = ['$timeout'];
function lxRipple($timeout)
{
return {
restrict: 'A',
link: link,
};
function link(scope, element, attrs)
{
var timer;
element
.css(
{
position: 'relative',
overflow: 'hidden'
})
.on('mousedown', function(e)
{
var ripple;
if (element.find('.ripple').length === 0)
{
ripple = angular.element('<span/>',
{
class: 'ripple'
});
if (attrs.lxRipple)
{
ripple.addClass('bgc-' + attrs.lxRipple);
}
element.prepend(ripple);
}
else
{
ripple = element.find('.ripple');
}
ripple.removeClass('ripple--is-animated');
if (!ripple.height() && !ripple.width())
{
var diameter = Math.max(element.outerWidth(), element.outerHeight());
ripple.css(
{
height: diameter,
width: diameter
});
}
var x = e.pageX - element.offset().left - ripple.width() / 2;
var y = e.pageY - element.offset().top - ripple.height() / 2;
ripple.css(
{
top: y + 'px',
left: x + 'px'
}).addClass('ripple--is-animated');
timer = $timeout(function()
{
ripple.removeClass('ripple--is-animated');
}, 651);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.search-filter')
.filter('lxSearchHighlight', lxSearchHighlight)
.directive('lxSearchFilter', lxSearchFilter);
lxSearchHighlight.$inject = ['$sce'];
function lxSearchHighlight($sce)
{
function escapeRegexp(queryToEscape)
{
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function (matchItem, query, icon)
{
var string = '';
if (icon)
{
string += '<i class="mdi mdi-' + icon + '"></i>';
}
string += query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
return $sce.trustAsHtml(string);
};
}
function lxSearchFilter()
{
return {
restrict: 'E',
templateUrl: 'search-filter.html',
scope:
{
autocomplete: '&?lxAutocomplete',
closed: '=?lxClosed',
color: '@?lxColor',
icon: '@?lxIcon',
onSelect: '=?lxOnSelect',
searchOnFocus: '=?lxSearchOnFocus',
theme: '@?lxTheme',
width: '@?lxWidth'
},
link: link,
controller: LxSearchFilterController,
controllerAs: 'lxSearchFilter',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var input;
attrs.$observe('lxWidth', function(newWidth)
{
if (angular.isDefined(scope.lxSearchFilter.closed) && scope.lxSearchFilter.closed)
{
element.find('.search-filter__container').css('width', newWidth);
}
});
transclude(function()
{
input = element.find('input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', ctrl.focusInput);
input.on('blur', ctrl.blurInput);
input.on('keydown', ctrl.keyEvent);
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxSearchFilterController.$inject = ['$element', '$scope', 'LxDropdownService', 'LxNotificationService', 'LxUtils'];
function LxSearchFilterController($element, $scope, LxDropdownService, LxNotificationService, LxUtils)
{
var lxSearchFilter = this;
var debouncedAutocomplete;
var input;
var itemSelected = false;
lxSearchFilter.blurInput = blurInput;
lxSearchFilter.clearInput = clearInput;
lxSearchFilter.focusInput = focusInput;
lxSearchFilter.getClass = getClass;
lxSearchFilter.keyEvent = keyEvent;
lxSearchFilter.openInput = openInput;
lxSearchFilter.selectItem = selectItem;
lxSearchFilter.setInput = setInput;
lxSearchFilter.setModel = setModel;
lxSearchFilter.activeChoiceIndex = -1;
lxSearchFilter.color = angular.isDefined(lxSearchFilter.color) ? lxSearchFilter.color : 'black';
lxSearchFilter.dropdownId = LxUtils.generateUUID();
lxSearchFilter.theme = angular.isDefined(lxSearchFilter.theme) ? lxSearchFilter.theme : 'light';
////////////
function blurInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed && !input.val())
{
$element.velocity(
{
width: 40
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false
});
}
if (!input.val())
{
lxSearchFilter.modelController.$setViewValue(undefined);
}
}
function clearInput()
{
lxSearchFilter.modelController.$setViewValue(undefined);
lxSearchFilter.modelController.$render();
// Temporarily disabling search on focus since we never want to trigger it when clearing the input.
var searchOnFocus = lxSearchFilter.searchOnFocus;
lxSearchFilter.searchOnFocus = false;
input.focus();
lxSearchFilter.searchOnFocus = searchOnFocus;
}
function focusInput()
{
if (!lxSearchFilter.searchOnFocus)
{
return;
}
updateAutocomplete(lxSearchFilter.modelController.$viewValue, true);
}
function getClass()
{
var searchFilterClass = [];
if (angular.isUndefined(lxSearchFilter.closed) || !lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--opened-mode');
}
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--closed-mode');
}
if (input.val())
{
searchFilterClass.push('search-filter--has-clear-button');
}
if (angular.isDefined(lxSearchFilter.color))
{
searchFilterClass.push('search-filter--' + lxSearchFilter.color);
}
if (angular.isDefined(lxSearchFilter.theme))
{
searchFilterClass.push('search-filter--theme-' + lxSearchFilter.theme);
}
if (angular.isFunction(lxSearchFilter.autocomplete))
{
searchFilterClass.push('search-filter--autocomplete');
}
if (LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
searchFilterClass.push('search-filter--is-open');
}
return searchFilterClass;
}
function keyEvent(_event)
{
if (!angular.isFunction(lxSearchFilter.autocomplete))
{
return;
}
if (!LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
lxSearchFilter.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 13:
keySelect();
if (lxSearchFilter.activeChoiceIndex > -1)
{
_event.preventDefault();
}
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
$scope.$apply();
}
function keyDown()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex += 1;
if (lxSearchFilter.activeChoiceIndex >= lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex = 0;
}
}
}
function keySelect()
{
if (!lxSearchFilter.autocompleteList || lxSearchFilter.activeChoiceIndex === -1)
{
return;
}
selectItem(lxSearchFilter.autocompleteList[lxSearchFilter.activeChoiceIndex]);
}
function keyUp()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex -= 1;
if (lxSearchFilter.activeChoiceIndex < 0)
{
lxSearchFilter.activeChoiceIndex = lxSearchFilter.autocompleteList.length - 1;
}
}
}
function onAutocompleteSuccess(autocompleteList)
{
lxSearchFilter.autocompleteList = autocompleteList;
if (lxSearchFilter.autocompleteList.length)
{
LxDropdownService.open(lxSearchFilter.dropdownId, $element);
}
else
{
LxDropdownService.close(lxSearchFilter.dropdownId);
}
lxSearchFilter.isLoading = false;
}
function onAutocompleteError(error)
{
LxNotificationService.error(error);
lxSearchFilter.isLoading = false;
}
function openInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
$element.velocity(
{
width: angular.isDefined(lxSearchFilter.width) ? parseInt(lxSearchFilter.width) : 240
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
input.focus();
}
});
}
else
{
input.focus();
}
}
function selectItem(_item)
{
itemSelected = true;
LxDropdownService.close(lxSearchFilter.dropdownId);
lxSearchFilter.modelController.$setViewValue(_item);
lxSearchFilter.modelController.$render();
if (angular.isFunction(lxSearchFilter.onSelect))
{
lxSearchFilter.onSelect(_item);
}
}
function setInput(_input)
{
input = _input;
}
function setModel(_modelController)
{
lxSearchFilter.modelController = _modelController;
if (angular.isFunction(lxSearchFilter.autocomplete) && angular.isFunction(lxSearchFilter.autocomplete()))
{
debouncedAutocomplete = LxUtils.debounce(function()
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete()).apply(this, arguments);
}, 500);
lxSearchFilter.modelController.$parsers.push(updateAutocomplete);
}
}
function updateAutocomplete(_newValue, _immediate)
{
if ((_newValue || (angular.isUndefined(_newValue) && lxSearchFilter.searchOnFocus)) && !itemSelected)
{
if (_immediate)
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete())(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
else
{
debouncedAutocomplete(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
}
else
{
debouncedAutocomplete.clear();
LxDropdownService.close(lxSearchFilter.dropdownId);
}
itemSelected = false;
return _newValue;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.select')
.filter('filterChoices', filterChoices)
.directive('lxSelect', lxSelect)
.directive('lxSelectSelected', lxSelectSelected)
.directive('lxSelectChoices', lxSelectChoices);
filterChoices.$inject = ['$filter'];
function filterChoices($filter)
{
return function(choices, externalFilter, textFilter)
{
if (externalFilter)
{
return choices;
}
var toFilter = [];
if (!angular.isArray(choices))
{
if (angular.isObject(choices))
{
for (var idx in choices)
{
if (angular.isArray(choices[idx]))
{
toFilter = toFilter.concat(choices[idx]);
}
}
}
}
else
{
toFilter = choices;
}
return $filter('filter')(toFilter, textFilter);
};
}
function lxSelect()
{
return {
restrict: 'E',
templateUrl: 'select.html',
scope:
{
allowClear: '=?lxAllowClear',
allowNewValue: '=?lxAllowNewValue',
autocomplete: '=?lxAutocomplete',
newValueTransform: '=?lxNewValueTransform',
choices: '=?lxChoices',
choicesCustomStyle: '=?lxChoicesCustomStyle',
customStyle: '=?lxCustomStyle',
displayFilter: '=?lxDisplayFilter',
error: '=?lxError',
filter: '&?lxFilter',
fixedLabel: '=?lxFixedLabel',
helper: '=?lxHelper',
helperMessage: '@?lxHelperMessage',
label: '@?lxLabel',
loading: '=?lxLoading',
modelToSelection: '&?lxModelToSelection',
multiple: '=?lxMultiple',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
selectionToModel: '&?lxSelectionToModel',
theme: '@?lxTheme',
valid: '=?lxValid',
viewMode: '@?lxViewMode'
},
link: link,
controller: LxSelectController,
controllerAs: 'lxSelect',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
var backwardOneWay = ['customStyle'];
var backwardTwoWay = ['allowClear', 'choices', 'error', 'loading', 'multiple', 'valid'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxSelect[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
if (attribute === 'multiple' && angular.isUndefined(newValue))
{
scope.lxSelect[attribute] = true;
}
else
{
scope.lxSelect[attribute] = newValue;
}
});
}
});
attrs.$observe('placeholder', function(newValue)
{
scope.lxSelect.label = newValue;
});
attrs.$observe('change', function(newValue)
{
scope.lxSelect.ngChange = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('filter', function(newValue)
{
scope.lxSelect.filter = function(data)
{
return scope.$parent.$eval(newValue, data);
};
scope.lxSelect.displayFilter = true;
});
attrs.$observe('modelToSelection', function(newValue)
{
scope.lxSelect.modelToSelection = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('selectionToModel', function(newValue)
{
scope.lxSelect.selectionToModel = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
}
}
LxSelectController.$inject = ['$interpolate', '$element', '$filter', '$sce', 'LxDropdownService', 'LxUtils'];
function LxSelectController($interpolate, $element, $filter, $sce, LxDropdownService, LxUtils)
{
var lxSelect = this;
var choiceTemplate;
var selectedTemplate;
lxSelect.displayChoice = displayChoice;
lxSelect.displaySelected = displaySelected;
lxSelect.displaySubheader = displaySubheader;
lxSelect.getFilteredChoices = getFilteredChoices;
lxSelect.getSelectedModel = getSelectedModel;
lxSelect.isSelected = isSelected;
lxSelect.keyEvent = keyEvent;
lxSelect.registerChoiceTemplate = registerChoiceTemplate;
lxSelect.registerSelectedTemplate = registerSelectedTemplate;
lxSelect.select = select;
lxSelect.toggleChoice = toggleChoice;
lxSelect.unselect = unselect;
lxSelect.updateFilter = updateFilter;
lxSelect.helperDisplayable = helperDisplayable;
lxSelect.activeChoiceIndex = -1;
lxSelect.activeSelectedIndex = -1;
lxSelect.uuid = LxUtils.generateUUID();
lxSelect.filterModel = undefined;
lxSelect.ngModel = angular.isUndefined(lxSelect.ngModel) && lxSelect.multiple ? [] : lxSelect.ngModel;
lxSelect.unconvertedModel = lxSelect.multiple ? [] : undefined;
lxSelect.viewMode = angular.isUndefined(lxSelect.viewMode) ? 'field' : 'chips';
////////////
function arrayObjectIndexOf(arr, obj)
{
for (var i = 0; i < arr.length; i++)
{
if (angular.equals(arr[i], obj))
{
return i;
}
}
return -1;
}
function displayChoice(_choice)
{
var choiceScope = {
$choice: _choice
};
return $sce.trustAsHtml($interpolate(choiceTemplate)(choiceScope));
}
function displaySelected(_selected)
{
var selectedScope = {};
if (!angular.isArray(lxSelect.choices))
{
var found = false;
for (var header in lxSelect.choices)
{
if (found)
{
break;
}
if (lxSelect.choices.hasOwnProperty(header))
{
for (var idx = 0, len = lxSelect.choices[header].length; idx < len; idx++)
{
if (angular.equals(_selected, lxSelect.choices[header][idx]))
{
selectedScope.$selectedSubheader = header;
found = true;
break;
}
}
}
}
}
if (angular.isDefined(_selected))
{
selectedScope.$selected = _selected;
}
else
{
selectedScope.$selected = getSelectedModel();
}
return $sce.trustAsHtml($interpolate(selectedTemplate)(selectedScope));
}
function displaySubheader(_subheader)
{
return $sce.trustAsHtml(_subheader);
}
function getFilteredChoices()
{
return $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
}
function getSelectedModel()
{
if (angular.isDefined(lxSelect.modelToSelection) || angular.isDefined(lxSelect.selectionToModel))
{
return lxSelect.unconvertedModel;
}
else
{
return lxSelect.ngModel;
}
}
function isSelected(_choice)
{
if (lxSelect.multiple && angular.isDefined(getSelectedModel()))
{
return arrayObjectIndexOf(getSelectedModel(), _choice) !== -1;
}
else if (angular.isDefined(getSelectedModel()))
{
return angular.equals(getSelectedModel(), _choice);
}
}
function keyEvent(_event)
{
if (_event.keyCode !== 8)
{
lxSelect.activeSelectedIndex = -1;
}
if (!LxDropdownService.isOpen('dropdown-' + lxSelect.uuid))
{
lxSelect.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 8:
keyRemove();
break;
case 13:
keySelect();
_event.preventDefault();
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
}
function keyDown()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex += 1;
if (lxSelect.activeChoiceIndex >= filteredChoices.length)
{
lxSelect.activeChoiceIndex = 0;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function keyRemove()
{
if (lxSelect.filterModel || !lxSelect.getSelectedModel().length)
{
return;
}
if (lxSelect.activeSelectedIndex === -1)
{
lxSelect.activeSelectedIndex = lxSelect.getSelectedModel().length - 1;
}
else
{
unselect(lxSelect.getSelectedModel()[lxSelect.activeSelectedIndex]);
}
}
function keySelect()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length && filteredChoices[lxSelect.activeChoiceIndex])
{
toggleChoice(filteredChoices[lxSelect.activeChoiceIndex]);
}
else if (lxSelect.filterModel && lxSelect.allowNewValue)
{
if (angular.isArray(getSelectedModel()))
{
var value = angular.isFunction(lxSelect.newValueTransform) ? lxSelect.newValueTransform(lxSelect.filterModel) : lxSelect.filterModel;
var identical = getSelectedModel().some(function (item) {
return angular.equals(item, value);
});
if (!identical)
{
getSelectedModel().push(value);
}
}
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function keyUp()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex -= 1;
if (lxSelect.activeChoiceIndex < 0)
{
lxSelect.activeChoiceIndex = filteredChoices.length - 1;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function registerChoiceTemplate(_choiceTemplate)
{
choiceTemplate = _choiceTemplate;
}
function registerSelectedTemplate(_selectedTemplate)
{
selectedTemplate = _selectedTemplate;
}
function select(_choice)
{
if (lxSelect.multiple && angular.isUndefined(lxSelect.ngModel))
{
lxSelect.ngModel = [];
}
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(resp);
}
else
{
lxSelect.ngModel = resp;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
});
}
else
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(_choice);
}
else
{
lxSelect.ngModel = _choice;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
}
function toggleChoice(_choice, _event)
{
if (lxSelect.multiple && !lxSelect.autocomplete)
{
_event.stopPropagation();
}
if (lxSelect.multiple && isSelected(_choice))
{
unselect(_choice);
}
else
{
select(_choice);
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function unselect(_choice)
{
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
removeElement(lxSelect.ngModel, resp);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
});
removeElement(lxSelect.unconvertedModel, _choice);
}
else
{
removeElement(lxSelect.ngModel, _choice);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
}
function updateFilter()
{
if (angular.isDefined(lxSelect.filter))
{
lxSelect.filter(
{
newValue: lxSelect.filterModel
});
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
if (lxSelect.filterModel)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
else
{
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
}
function helperDisplayable() {
// If helper message is not defined, message is not displayed...
if (angular.isUndefined(lxSelect.helperMessage))
{
return false;
}
// If helper is defined return it's state.
if (angular.isDefined(lxSelect.helper))
{
return lxSelect.helper;
}
// Else check if there's choices.
var choices = lxSelect.getFilteredChoices();
if (angular.isArray(choices))
{
return !choices.length;
}
else if (angular.isObject(choices))
{
return !Object.keys(choices).length;
}
return true;
}
function removeElement(model, element)
{
var index = -1;
for (var i = 0, len = model.length; i < len; i++)
{
if (angular.equals(element, model[i]))
{
index = i;
break;
}
}
if (index > -1)
{
model.splice(index, 1);
}
}
}
function lxSelectSelected()
{
return {
restrict: 'E',
require: ['lxSelectSelected', '^lxSelect'],
templateUrl: 'select-selected.html',
link: link,
controller: LxSelectSelectedController,
controllerAs: 'lxSelectSelected',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerSelectedTemplate(template);
});
}
}
function LxSelectSelectedController()
{
var lxSelectSelected = this;
lxSelectSelected.clearModel = clearModel;
lxSelectSelected.setParentController = setParentController;
lxSelectSelected.removeSelected = removeSelected;
////////////
function clearModel(_event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.ngModel = undefined;
lxSelectSelected.parentCtrl.unconvertedModel = undefined;
}
function setParentController(_parentCtrl)
{
lxSelectSelected.parentCtrl = _parentCtrl;
}
function removeSelected(_selected, _event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.unselect(_selected);
}
}
function lxSelectChoices()
{
return {
restrict: 'E',
require: ['lxSelectChoices', '^lxSelect'],
templateUrl: 'select-choices.html',
link: link,
controller: LxSelectChoicesController,
controllerAs: 'lxSelectChoices',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerChoiceTemplate(template);
});
}
}
LxSelectChoicesController.$inject = ['$scope', '$timeout'];
function LxSelectChoicesController($scope, $timeout)
{
var lxSelectChoices = this;
var timer;
lxSelectChoices.isArray = isArray;
lxSelectChoices.setParentController = setParentController;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function isArray()
{
return angular.isArray(lxSelectChoices.parentCtrl.choices);
}
function setParentController(_parentCtrl)
{
lxSelectChoices.parentCtrl = _parentCtrl;
$scope.$watch(function()
{
return lxSelectChoices.parentCtrl.ngModel;
}, function(newModel, oldModel)
{
timer = $timeout(function()
{
if (newModel !== oldModel && angular.isDefined(lxSelectChoices.parentCtrl.ngChange))
{
lxSelectChoices.parentCtrl.ngChange(
{
newValue: newModel,
oldValue: oldModel
});
}
if (angular.isDefined(lxSelectChoices.parentCtrl.modelToSelection) || angular.isDefined(lxSelectChoices.parentCtrl.selectionToModel))
{
toSelection();
}
});
}, true);
}
function toSelection()
{
if (lxSelectChoices.parentCtrl.multiple)
{
lxSelectChoices.parentCtrl.unconvertedModel = [];
angular.forEach(lxSelectChoices.parentCtrl.ngModel, function(item)
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: item,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel.push(resp);
}
});
});
}
else
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: lxSelectChoices.parentCtrl.ngModel,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel = resp;
}
});
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.stepper')
.directive('lxStepper', lxStepper)
.directive('lxStep', lxStep)
.directive('lxStepNav', lxStepNav);
/* Stepper */
function lxStepper()
{
return {
restrict: 'E',
templateUrl: 'stepper.html',
scope: {
cancel: '&?lxCancel',
complete: '&lxComplete',
isLinear: '=?lxIsLinear',
labels: '=?lxLabels',
layout: '@?lxLayout'
},
controller: LxStepperController,
controllerAs: 'lxStepper',
bindToController: true,
transclude: true
};
}
function LxStepperController()
{
var lxStepper = this;
var _classes = [];
var _defaultValues = {
isLinear: true,
labels: {
'back': 'Back',
'cancel': 'Cancel',
'continue': 'Continue',
'optional': 'Optional'
},
layout: 'horizontal'
};
lxStepper.addStep = addStep;
lxStepper.getClasses = getClasses;
lxStepper.goToStep = goToStep;
lxStepper.isComplete = isComplete;
lxStepper.updateStep = updateStep;
lxStepper.activeIndex = 0;
lxStepper.isLinear = angular.isDefined(lxStepper.isLinear) ? lxStepper.isLinear : _defaultValues.isLinear;
lxStepper.labels = angular.isDefined(lxStepper.labels) ? lxStepper.labels : _defaultValues.labels;
lxStepper.layout = angular.isDefined(lxStepper.layout) ? lxStepper.layout : _defaultValues.layout;
lxStepper.steps = [];
////////////
function addStep(step)
{
lxStepper.steps.push(step);
}
function getClasses()
{
_classes.length = 0;
_classes.push('lx-stepper--layout-' + lxStepper.layout);
if (lxStepper.isLinear)
{
_classes.push('lx-stepper--is-linear');
}
if (lxStepper.steps[lxStepper.activeIndex].feedback)
{
_classes.push('lx-stepper--step-has-feedback');
}
if (lxStepper.steps[lxStepper.activeIndex].isLoading)
{
_classes.push('lx-stepper--step-is-loading');
}
return _classes;
}
function goToStep(index, bypass)
{
// Check if the the wanted step previous steps are optionals. If so, check if the step before the last optional step is valid to allow going to the wanted step from the nav (only if linear stepper).
var stepBeforeLastOptionalStep;
if (!bypass && lxStepper.isLinear)
{
for (var i = index - 1; i >= 0; i--)
{
if (angular.isDefined(lxStepper.steps[i]) && !lxStepper.steps[i].isOptional)
{
stepBeforeLastOptionalStep = lxStepper.steps[i];
break;
}
}
if (angular.isDefined(stepBeforeLastOptionalStep) && stepBeforeLastOptionalStep.isValid === true)
{
bypass = true;
}
}
// Check if the wanted step previous step is not valid to disallow going to the wanted step from the nav (only if linear stepper).
if (!bypass && lxStepper.isLinear && angular.isDefined(lxStepper.steps[index - 1]) && (angular.isUndefined(lxStepper.steps[index - 1].isValid) || lxStepper.steps[index - 1].isValid === false))
{
return;
}
if (index < lxStepper.steps.length)
{
lxStepper.activeIndex = parseInt(index);
}
}
function isComplete()
{
var countMandatory = 0;
var countValid = 0;
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (!lxStepper.steps[i].isOptional)
{
countMandatory++;
if (lxStepper.steps[i].isValid === true) {
countValid++;
}
}
}
if (countValid === countMandatory)
{
lxStepper.complete();
return true;
}
}
function updateStep(step)
{
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (lxStepper.steps[i].uuid === step.uuid)
{
lxStepper.steps[i].index = step.index;
lxStepper.steps[i].label = step.label;
return;
}
}
}
}
/* Step */
function lxStep()
{
return {
restrict: 'E',
require: ['lxStep', '^lxStepper'],
templateUrl: 'step.html',
scope: {
feedback: '@?lxFeedback',
isEditable: '=?lxIsEditable',
isOptional: '=?lxIsOptional',
label: '@lxLabel',
submit: '&?lxSubmit',
validate: '&?lxValidate'
},
link: link,
controller: LxStepController,
controllerAs: 'lxStep',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxFeedback', function(feedback)
{
ctrls[0].setFeedback(feedback);
});
attrs.$observe('lxLabel', function(label)
{
ctrls[0].setLabel(label);
});
attrs.$observe('lxIsEditable', function(isEditable)
{
ctrls[0].setIsEditable(isEditable);
});
attrs.$observe('lxIsOptional', function(isOptional)
{
ctrls[0].setIsOptional(isOptional);
});
}
}
LxStepController.$inject = ['$q', 'LxNotificationService', 'LxUtils'];
function LxStepController($q, LxNotificationService, LxUtils)
{
var lxStep = this;
var _classes = [];
var _nextStepIndex;
lxStep.getClasses = getClasses;
lxStep.init = init;
lxStep.previousStep = previousStep;
lxStep.setFeedback = setFeedback;
lxStep.setLabel = setLabel;
lxStep.setIsEditable = setIsEditable;
lxStep.setIsOptional = setIsOptional;
lxStep.submitStep = submitStep;
lxStep.step = {
errorMessage: undefined,
feedback: undefined,
index: undefined,
isEditable: false,
isLoading: false,
isOptional: false,
isValid: undefined,
label: undefined,
uuid: LxUtils.generateUUID()
};
////////////
function getClasses()
{
_classes.length = 0;
if (lxStep.step.index === lxStep.parent.activeIndex)
{
_classes.push('lx-step--is-active');
}
return _classes;
}
function init(parent, index)
{
lxStep.parent = parent;
lxStep.step.index = index;
lxStep.parent.addStep(lxStep.step);
}
function previousStep()
{
if (lxStep.step.index > 0)
{
lxStep.parent.goToStep(lxStep.step.index - 1);
}
}
function setFeedback(feedback)
{
lxStep.step.feedback = feedback;
updateParentStep();
}
function setLabel(label)
{
lxStep.step.label = label;
updateParentStep();
}
function setIsEditable(isEditable)
{
lxStep.step.isEditable = isEditable;
updateParentStep();
}
function setIsOptional(isOptional)
{
lxStep.step.isOptional = isOptional;
updateParentStep();
}
function submitStep()
{
if (lxStep.step.isValid === true && !lxStep.step.isEditable)
{
lxStep.parent.goToStep(_nextStepIndex, true);
return;
}
var validateFunction = lxStep.validate;
var validity = true;
if (angular.isFunction(validateFunction))
{
validity = validateFunction();
}
if (validity === true)
{
lxStep.step.isLoading = true;
updateParentStep();
var submitFunction = lxStep.submit;
if (!angular.isFunction(submitFunction))
{
submitFunction = function()
{
return $q(function(resolve)
{
resolve();
});
};
}
var promise = submitFunction();
promise.then(function(nextStepIndex)
{
lxStep.step.isValid = true;
updateParentStep();
var isComplete = lxStep.parent.isComplete();
if (!isComplete)
{
_nextStepIndex = angular.isDefined(nextStepIndex) && nextStepIndex > lxStep.parent.activeIndex && (!lxStep.parent.isLinear || (lxStep.parent.isLinear && lxStep.parent.steps[nextStepIndex - 1].isOptional)) ? nextStepIndex : lxStep.step.index + 1;
lxStep.parent.goToStep(_nextStepIndex, true);
}
}).catch(function(error)
{
LxNotificationService.error(error);
}).finally(function()
{
lxStep.step.isLoading = false;
updateParentStep();
});
}
else
{
lxStep.step.isValid = false;
lxStep.step.errorMessage = validity;
updateParentStep();
}
}
function updateParentStep()
{
lxStep.parent.updateStep(lxStep.step);
}
}
/* Step nav */
function lxStepNav()
{
return {
restrict: 'E',
require: ['lxStepNav', '^lxStepper'],
templateUrl: 'step-nav.html',
scope: {
activeIndex: '@lxActiveIndex',
step: '=lxStep'
},
link: link,
controller: LxStepNavController,
controllerAs: 'lxStepNav',
bindToController: true,
replace: true,
transclude: false
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1]);
}
}
function LxStepNavController()
{
var lxStepNav = this;
var _classes = [];
lxStepNav.getClasses = getClasses;
lxStepNav.init = init;
////////////
function getClasses()
{
_classes.length = 0;
if (parseInt(lxStepNav.step.index) === parseInt(lxStepNav.activeIndex))
{
_classes.push('lx-step-nav--is-active');
}
if (lxStepNav.step.isValid === true)
{
_classes.push('lx-step-nav--is-valid');
}
else if (lxStepNav.step.isValid === false)
{
_classes.push('lx-step-nav--has-error');
}
if (lxStepNav.step.isEditable)
{
_classes.push('lx-step-nav--is-editable');
}
if (lxStepNav.step.isOptional)
{
_classes.push('lx-step-nav--is-optional');
}
return _classes;
}
function init(parent, index)
{
lxStepNav.parent = parent;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.switch')
.directive('lxSwitch', lxSwitch)
.directive('lxSwitchLabel', lxSwitchLabel)
.directive('lxSwitchHelp', lxSwitchHelp);
function lxSwitch()
{
return {
restrict: 'E',
templateUrl: 'switch.html',
scope:
{
ngModel: '=',
name: '@?',
ngTrueValue: '@?',
ngFalseValue: '@?',
ngChange: '&?',
ngDisabled: '=?',
lxColor: '@?',
lxPosition: '@?'
},
controller: LxSwitchController,
controllerAs: 'lxSwitch',
bindToController: true,
transclude: true,
replace: true
};
}
LxSwitchController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxSwitchController($scope, $timeout, LxUtils)
{
var lxSwitch = this;
var switchId;
var switchHasChildren;
var timer;
lxSwitch.getSwitchId = getSwitchId;
lxSwitch.getSwitchHasChildren = getSwitchHasChildren;
lxSwitch.setSwitchId = setSwitchId;
lxSwitch.setSwitchHasChildren = setSwitchHasChildren;
lxSwitch.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getSwitchId()
{
return switchId;
}
function getSwitchHasChildren()
{
return switchHasChildren;
}
function init()
{
setSwitchId(LxUtils.generateUUID());
setSwitchHasChildren(false);
lxSwitch.ngTrueValue = angular.isUndefined(lxSwitch.ngTrueValue) ? true : lxSwitch.ngTrueValue;
lxSwitch.ngFalseValue = angular.isUndefined(lxSwitch.ngFalseValue) ? false : lxSwitch.ngFalseValue;
lxSwitch.lxColor = angular.isUndefined(lxSwitch.lxColor) ? 'accent' : lxSwitch.lxColor;
lxSwitch.lxPosition = angular.isUndefined(lxSwitch.lxPosition) ? 'left' : lxSwitch.lxPosition;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
function setSwitchHasChildren(_switchHasChildren)
{
switchHasChildren = _switchHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxSwitch.ngChange);
}
}
function lxSwitchLabel()
{
return {
restrict: 'AE',
require: ['^lxSwitch', '^lxSwitchLabel'],
templateUrl: 'switch-label.html',
link: link,
controller: LxSwitchLabelController,
controllerAs: 'lxSwitchLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setSwitchHasChildren(true);
ctrls[1].setSwitchId(ctrls[0].getSwitchId());
}
}
function LxSwitchLabelController()
{
var lxSwitchLabel = this;
var switchId;
lxSwitchLabel.getSwitchId = getSwitchId;
lxSwitchLabel.setSwitchId = setSwitchId;
////////////
function getSwitchId()
{
return switchId;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
}
function lxSwitchHelp()
{
return {
restrict: 'AE',
require: '^lxSwitch',
templateUrl: 'switch-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.tabs')
.directive('lxTabs', lxTabs)
.directive('lxTab', lxTab)
.directive('lxTabsPanes', lxTabsPanes)
.directive('lxTabPane', lxTabPane);
function lxTabs()
{
return {
restrict: 'E',
templateUrl: 'tabs.html',
scope:
{
layout: '@?lxLayout',
theme: '@?lxTheme',
color: '@?lxColor',
indicator: '@?lxIndicator',
activeTab: '=?lxActiveTab',
panesId: '@?lxPanesId',
links: '=?lxLinks'
},
controller: LxTabsController,
controllerAs: 'lxTabs',
bindToController: true,
replace: true,
transclude: true
};
}
LxTabsController.$inject = ['LxUtils', '$element', '$scope', '$timeout'];
function LxTabsController(LxUtils, $element, $scope, $timeout)
{
var lxTabs = this;
var tabsLength;
var timer1;
var timer2;
var timer3;
var timer4;
lxTabs.removeTab = removeTab;
lxTabs.setActiveTab = setActiveTab;
lxTabs.setViewMode = setViewMode;
lxTabs.tabIsActive = tabIsActive;
lxTabs.updateTabs = updateTabs;
lxTabs.activeTab = angular.isDefined(lxTabs.activeTab) ? lxTabs.activeTab : 0;
lxTabs.color = angular.isDefined(lxTabs.color) ? lxTabs.color : 'primary';
lxTabs.indicator = angular.isDefined(lxTabs.indicator) ? lxTabs.indicator : 'accent';
lxTabs.layout = angular.isDefined(lxTabs.layout) ? lxTabs.layout : 'full';
lxTabs.tabs = [];
lxTabs.theme = angular.isDefined(lxTabs.theme) ? lxTabs.theme : 'light';
lxTabs.viewMode = angular.isDefined(lxTabs.links) ? 'separate' : 'gather';
$scope.$watch(function()
{
return lxTabs.activeTab;
}, function(_newActiveTab, _oldActiveTab)
{
timer1 = $timeout(function()
{
setIndicatorPosition(_oldActiveTab);
if (lxTabs.viewMode === 'separate')
{
angular.element('#' + lxTabs.panesId).find('.tabs__pane').hide();
angular.element('#' + lxTabs.panesId).find('.tabs__pane').eq(lxTabs.activeTab).show();
}
});
});
$scope.$watch(function()
{
return lxTabs.links;
}, function(_newLinks)
{
lxTabs.viewMode = angular.isDefined(_newLinks) ? 'separate' : 'gather';
angular.forEach(_newLinks, function(link, index)
{
var tab = {
uuid: (angular.isUndefined(link.uuid) || link.uuid.length === 0) ? LxUtils.generateUUID() : link.uuid,
index: index,
label: link.label,
icon: link.icon,
disabled: link.disabled
};
updateTabs(tab);
});
});
timer2 = $timeout(function()
{
tabsLength = lxTabs.tabs.length;
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
$timeout.cancel(timer3);
$timeout.cancel(timer4);
});
////////////
function removeTab(_tab)
{
lxTabs.tabs.splice(_tab.index, 1);
angular.forEach(lxTabs.tabs, function(tab, index)
{
tab.index = index;
});
if (lxTabs.activeTab === 0)
{
timer3 = $timeout(function()
{
setIndicatorPosition();
});
}
else
{
setActiveTab(lxTabs.tabs[0]);
}
}
function setActiveTab(_tab)
{
if (!_tab.disabled)
{
lxTabs.activeTab = _tab.index;
}
}
function setIndicatorPosition(_previousActiveTab)
{
var direction = lxTabs.activeTab > _previousActiveTab ? 'right' : 'left';
var indicator = $element.find('.tabs__indicator');
var activeTab = $element.find('.tabs__link').eq(lxTabs.activeTab);
var indicatorLeft = activeTab.position().left;
var indicatorRight = $element.outerWidth() - (indicatorLeft + activeTab.outerWidth());
if (angular.isUndefined(_previousActiveTab))
{
indicator.css(
{
left: indicatorLeft,
right: indicatorRight
});
}
else
{
var animationProperties = {
duration: 200,
easing: 'easeOutQuint'
};
if (direction === 'left')
{
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
}
else
{
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
}
}
}
function setViewMode(_viewMode)
{
lxTabs.viewMode = _viewMode;
}
function tabIsActive(_index)
{
return lxTabs.activeTab === _index;
}
function updateTabs(_tab)
{
var newTab = true;
angular.forEach(lxTabs.tabs, function(tab)
{
if (tab.index === _tab.index)
{
newTab = false;
tab.uuid = _tab.uuid;
tab.icon = _tab.icon;
tab.label = _tab.label;
}
});
if (newTab)
{
lxTabs.tabs.push(_tab);
if (angular.isDefined(tabsLength))
{
timer4 = $timeout(function()
{
setIndicatorPosition();
});
}
}
}
}
function lxTab()
{
return {
restrict: 'E',
require: ['lxTab', '^lxTabs'],
templateUrl: 'tab.html',
scope:
{
ngDisabled: '=?'
},
link: link,
controller: LxTabController,
controllerAs: 'lxTab',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxLabel', function(_newLabel)
{
ctrls[0].setLabel(_newLabel);
});
attrs.$observe('lxIcon', function(_newIcon)
{
ctrls[0].setIcon(_newIcon);
});
}
}
LxTabController.$inject = ['$scope', 'LxUtils'];
function LxTabController($scope, LxUtils)
{
var lxTab = this;
var parentCtrl;
var tab = {
uuid: LxUtils.generateUUID(),
index: undefined,
label: undefined,
icon: undefined,
disabled: false
};
lxTab.init = init;
lxTab.setIcon = setIcon;
lxTab.setLabel = setLabel;
lxTab.tabIsActive = tabIsActive;
$scope.$watch(function()
{
return lxTab.ngDisabled;
}, function(_isDisabled)
{
if (_isDisabled)
{
tab.disabled = true;
}
else
{
tab.disabled = false;
}
parentCtrl.updateTabs(tab);
});
$scope.$on('$destroy', function()
{
parentCtrl.removeTab(tab);
});
////////////
function init(_parentCtrl, _index)
{
parentCtrl = _parentCtrl;
tab.index = _index;
parentCtrl.updateTabs(tab);
}
function setIcon(_icon)
{
tab.icon = _icon;
parentCtrl.updateTabs(tab);
}
function setLabel(_label)
{
tab.label = _label;
parentCtrl.updateTabs(tab);
}
function tabIsActive()
{
return parentCtrl.tabIsActive(tab.index);
}
}
function lxTabsPanes()
{
return {
restrict: 'E',
templateUrl: 'tabs-panes.html',
scope: true,
replace: true,
transclude: true
};
}
function lxTabPane()
{
return {
restrict: 'E',
templateUrl: 'tab-pane.html',
scope: true,
replace: true,
transclude: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.text-field')
.directive('lxTextField', lxTextField);
lxTextField.$inject = ['$timeout'];
function lxTextField($timeout)
{
return {
restrict: 'E',
templateUrl: 'text-field.html',
scope:
{
allowClear: '=?lxAllowClear',
error: '=?lxError',
fixedLabel: '=?lxFixedLabel',
focus: '=?lxFocus',
icon: '@?lxIcon',
label: '@lxLabel',
ngDisabled: '=?',
theme: '@?lxTheme',
valid: '=?lxValid'
},
link: link,
controller: LxTextFieldController,
controllerAs: 'lxTextField',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var backwardOneWay = ['icon', 'label', 'theme'];
var backwardTwoWay = ['error', 'fixedLabel', 'valid'];
var input;
var timer;
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
transclude(function()
{
input = element.find('textarea');
if (input[0])
{
input.on('cut paste drop keydown', function()
{
timer = $timeout(ctrl.updateTextareaHeight);
});
}
else
{
input = element.find('input');
}
input.addClass('text-field__input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', function()
{
var phase = scope.$root.$$phase;
if (phase === '$apply' || phase === '$digest')
{
ctrl.focusInput();
}
else
{
scope.$apply(ctrl.focusInput);
}
});
input.on('blur', ctrl.blurInput);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
input.off();
});
}
}
LxTextFieldController.$inject = ['$scope', '$timeout'];
function LxTextFieldController($scope, $timeout)
{
var lxTextField = this;
var input;
var modelController;
var timer1;
var timer2;
lxTextField.blurInput = blurInput;
lxTextField.clearInput = clearInput;
lxTextField.focusInput = focusInput;
lxTextField.hasValue = hasValue;
lxTextField.setInput = setInput;
lxTextField.setModel = setModel;
lxTextField.updateTextareaHeight = updateTextareaHeight;
$scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
lxTextField.isActive = true;
}
else
{
lxTextField.isActive = false;
}
});
$scope.$watch(function()
{
return lxTextField.focus;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
$timeout(function()
{
input.focus();
// Reset the value so we can re-focus the field later on if we want to.
lxTextField.focus = false;
});
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function blurInput()
{
if (!hasValue())
{
$scope.$apply(function()
{
lxTextField.isActive = false;
});
}
$scope.$apply(function()
{
lxTextField.isFocus = false;
});
}
function clearInput(_event)
{
_event.stopPropagation();
modelController.$setViewValue(undefined);
modelController.$render();
}
function focusInput()
{
lxTextField.isActive = true;
lxTextField.isFocus = true;
}
function hasValue()
{
return angular.isDefined(input.val()) && input.val().length > 0;
}
function init()
{
lxTextField.isActive = hasValue();
lxTextField.focus = angular.isDefined(lxTextField.focus) ? lxTextField.focus : false;
lxTextField.isFocus = lxTextField.focus;
}
function setInput(_input)
{
input = _input;
timer1 = $timeout(init);
if (input.selector === 'textarea')
{
timer2 = $timeout(updateTextareaHeight);
}
}
function setModel(_modelControler)
{
modelController = _modelControler;
}
function updateTextareaHeight()
{
var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + input.width() + 'px;">' + input.val() + '</textarea>');
tmpTextArea.appendTo('body');
input.css(
{
height: tmpTextArea[0].scrollHeight + 'px'
});
tmpTextArea.remove();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.tooltip')
.directive('lxTooltip', lxTooltip);
function lxTooltip()
{
return {
restrict: 'A',
scope:
{
tooltip: '@lxTooltip',
position: '@?lxTooltipPosition'
},
link: link,
controller: LxTooltipController,
controllerAs: 'lxTooltip',
bindToController: true
};
function link(scope, element, attrs, ctrl)
{
if (angular.isDefined(attrs.lxTooltip))
{
attrs.$observe('lxTooltip', function(newValue)
{
ctrl.updateTooltipText(newValue);
});
}
if (angular.isDefined(attrs.lxTooltipPosition))
{
attrs.$observe('lxTooltipPosition', function(newValue)
{
scope.lxTooltip.position = newValue;
});
}
element.on('mouseenter', ctrl.showTooltip);
element.on('mouseleave', ctrl.hideTooltip);
scope.$on('$destroy', function()
{
element.off();
});
}
}
LxTooltipController.$inject = ['$element', '$scope', '$timeout', 'LxDepthService'];
function LxTooltipController($element, $scope, $timeout, LxDepthService)
{
var lxTooltip = this;
var timer1;
var timer2;
var tooltip;
var tooltipBackground;
var tooltipLabel;
lxTooltip.hideTooltip = hideTooltip;
lxTooltip.showTooltip = showTooltip;
lxTooltip.updateTooltipText = updateTooltipText;
lxTooltip.position = angular.isDefined(lxTooltip.position) ? lxTooltip.position : 'top';
$scope.$on('$destroy', function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function hideTooltip()
{
if (angular.isDefined(tooltip))
{
tooltip.removeClass('tooltip--is-active');
timer1 = $timeout(function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
}, 200);
}
}
function setTooltipPosition()
{
var width = $element.outerWidth(),
height = $element.outerHeight(),
top = $element.offset().top,
left = $element.offset().left;
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.appendTo('body');
if (lxTooltip.position === 'top')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top - tooltip.outerHeight()
});
}
else if (lxTooltip.position === 'bottom')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top + height
});
}
else if (lxTooltip.position === 'left')
{
tooltip.css(
{
left: left - tooltip.outerWidth(),
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
else if (lxTooltip.position === 'right')
{
tooltip.css(
{
left: left + width,
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
}
function showTooltip()
{
if (angular.isUndefined(tooltip))
{
LxDepthService.register();
tooltip = angular.element('<div/>',
{
class: 'tooltip tooltip--' + lxTooltip.position
});
tooltipBackground = angular.element('<div/>',
{
class: 'tooltip__background'
});
tooltipLabel = angular.element('<span/>',
{
class: 'tooltip__label',
text: lxTooltip.tooltip
});
setTooltipPosition();
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
timer2 = $timeout(function()
{
tooltip.addClass('tooltip--is-active');
});
}
}
function updateTooltipText(_newValue)
{
if (angular.isDefined(tooltipLabel))
{
tooltipLabel.text(_newValue);
}
}
}
})();
angular.module("lumx.dropdown").run(['$templateCache', function(a) { a.put('dropdown.html', '<div class="dropdown"\n' +
' ng-class="{ \'dropdown--has-toggle\': lxDropdown.hasToggle,\n' +
' \'dropdown--is-open\': lxDropdown.isOpen }"\n' +
' ng-transclude></div>\n' +
'');
a.put('dropdown-toggle.html', '<div class="dropdown-toggle" ng-transclude></div>\n' +
'');
a.put('dropdown-menu.html', '<div class="dropdown-menu">\n' +
' <div class="dropdown-menu__content" ng-transclude ng-if="lxDropdownMenu.parentCtrl.isOpen"></div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.file-input").run(['$templateCache', function(a) { a.put('file-input.html', '<div class="input-file">\n' +
' <span class="input-file__label">{{ lxFileInput.label }}</span>\n' +
' <span class="input-file__filename">{{ lxFileInput.fileName }}</span>\n' +
' <input type="file" class="input-file__input">\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.text-field").run(['$templateCache', function(a) { a.put('text-field.html', '<div class="text-field"\n' +
' ng-class="{ \'text-field--error\': lxTextField.error,\n' +
' \'text-field--fixed-label\': lxTextField.fixedLabel,\n' +
' \'text-field--has-icon\': lxTextField.icon,\n' +
' \'text-field--has-value\': lxTextField.hasValue(),\n' +
' \'text-field--is-active\': lxTextField.isActive,\n' +
' \'text-field--is-disabled\': lxTextField.ngDisabled,\n' +
' \'text-field--is-focus\': lxTextField.isFocus,\n' +
' \'text-field--theme-light\': !lxTextField.theme || lxTextField.theme === \'light\',\n' +
' \'text-field--theme-dark\': lxTextField.theme === \'dark\',\n' +
' \'text-field--valid\': lxTextField.valid }">\n' +
' <div class="text-field__icon" ng-if="lxTextField.icon">\n' +
' <i class="mdi mdi-{{ lxTextField.icon }}"></i>\n' +
' </div>\n' +
'\n' +
' <label class="text-field__label">\n' +
' {{ lxTextField.label }}\n' +
' </label>\n' +
'\n' +
' <div ng-transclude></div>\n' +
'\n' +
' <span class="text-field__clear" ng-click="lxTextField.clearInput($event)" ng-if="lxTextField.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </span>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.search-filter").run(['$templateCache', function(a) { a.put('search-filter.html', '<div class="search-filter" ng-class="lxSearchFilter.getClass()">\n' +
' <div class="search-filter__container">\n' +
' <div class="search-filter__button">\n' +
' <lx-button type="submit" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.openInput()">\n' +
' <i class="mdi mdi-magnify"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__input" ng-transclude></div>\n' +
'\n' +
' <div class="search-filter__clear">\n' +
' <lx-button type="button" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.clearInput()">\n' +
' <i class="mdi mdi-close"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__loader" ng-if="lxSearchFilter.isLoading">\n' +
' <lx-progress lx-type="linear"></lx-progress>\n' +
' </div>\n' +
'\n' +
' <lx-dropdown id="{{ lxSearchFilter.dropdownId }}" lx-effect="none" lx-width="100%" ng-if="lxSearchFilter.autocomplete">\n' +
' <lx-dropdown-menu class="search-filter__autocomplete-list">\n' +
' <ul>\n' +
' <li ng-repeat="item in lxSearchFilter.autocompleteList track by $index">\n' +
' <a class="search-filter__autocomplete-item"\n' +
' ng-class="{ \'search-filter__autocomplete-item--is-active\': lxSearchFilter.activeChoiceIndex === $index }"\n' +
' ng-click="lxSearchFilter.selectItem(item)"\n' +
' ng-bind-html="item | lxSearchHighlight:lxSearchFilter.modelController.$viewValue:lxSearchFilter.icon"></a>\n' +
' </li>\n' +
' </ul>\n' +
' </lx-dropdown-menu>\n' +
' </lx-dropdown>\n' +
'</div>');
}]);
angular.module("lumx.select").run(['$templateCache', function(a) { a.put('select.html', '<div class="lx-select"\n' +
' ng-class="{ \'lx-select--error\': lxSelect.error,\n' +
' \'lx-select--fixed-label\': lxSelect.fixedLabel && lxSelect.viewMode === \'field\',\n' +
' \'lx-select--is-active\': (!lxSelect.multiple && lxSelect.getSelectedModel()) || (lxSelect.multiple && lxSelect.getSelectedModel().length),\n' +
' \'lx-select--is-disabled\': lxSelect.ngDisabled,\n' +
' \'lx-select--is-multiple\': lxSelect.multiple,\n' +
' \'lx-select--is-unique\': !lxSelect.multiple,\n' +
' \'lx-select--theme-light\': !lxSelect.theme || lxSelect.theme === \'light\',\n' +
' \'lx-select--theme-dark\': lxSelect.theme === \'dark\',\n' +
' \'lx-select--valid\': lxSelect.valid,\n' +
' \'lx-select--custom-style\': lxSelect.customStyle,\n' +
' \'lx-select--default-style\': !lxSelect.customStyle,\n' +
' \'lx-select--view-mode-field\': !lxSelect.multiple || (lxSelect.multiple && lxSelect.viewMode === \'field\'),\n' +
' \'lx-select--view-mode-chips\': lxSelect.multiple && lxSelect.viewMode === \'chips\',\n' +
' \'lx-select--autocomplete\': lxSelect.autocomplete }">\n' +
' <span class="lx-select-label" ng-if="!lxSelect.autocomplete">\n' +
' {{ ::lxSelect.label }}\n' +
' </span>\n' +
'\n' +
' <lx-dropdown id="dropdown-{{ lxSelect.uuid }}" lx-width="100%" lx-effect="{{ lxSelect.autocomplete ? \'none\' : \'expand\' }}">\n' +
' <ng-transclude></ng-transclude>\n' +
' </lx-dropdown>\n' +
'</div>\n' +
'');
a.put('select-selected.html', '<div>\n' +
' <lx-dropdown-toggle ng-if="::!lxSelectSelected.parentCtrl.autocomplete">\n' +
' <ng-include src="\'select-selected-content.html\'"></ng-include>\n' +
' </lx-dropdown-toggle>\n' +
'\n' +
' <ng-include src="\'select-selected-content.html\'" ng-if="::lxSelectSelected.parentCtrl.autocomplete"></ng-include>\n' +
'</div>\n' +
'');
a.put('select-selected-content.html', '<div class="lx-select-selected-wrapper" id="lx-select-selected-wrapper-{{ lxSelectSelected.parentCtrl.uuid }}">\n' +
' <div class="lx-select-selected" ng-if="!lxSelectSelected.parentCtrl.multiple && lxSelectSelected.parentCtrl.getSelectedModel()">\n' +
' <span class="lx-select-selected__value"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected()"></span>\n' +
'\n' +
' <a class="lx-select-selected__clear"\n' +
' ng-click="lxSelectSelected.clearModel($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </a>\n' +
' </div>\n' +
'\n' +
' <div class="lx-select-selected" ng-if="lxSelectSelected.parentCtrl.multiple">\n' +
' <span class="lx-select-selected__tag"\n' +
' ng-class="{ \'lx-select-selected__tag--is-active\': lxSelectSelected.parentCtrl.activeSelectedIndex === $index }"\n' +
' ng-click="lxSelectSelected.removeSelected(selected, $event)"\n' +
' ng-repeat="selected in lxSelectSelected.parentCtrl.getSelectedModel()"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected(selected)"></span>\n' +
'\n' +
' <input type="text"\n' +
' placeholder="{{ ::lxSelectSelected.parentCtrl.label }}"\n' +
' class="lx-select-selected__filter"\n' +
' ng-model="lxSelectSelected.parentCtrl.filterModel"\n' +
' ng-change="lxSelectSelected.parentCtrl.updateFilter()"\n' +
' ng-keydown="lxSelectSelected.parentCtrl.keyEvent($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.autocomplete && !lxSelectSelected.parentCtrl.ngDisabled">\n' +
' </div>\n' +
'</div>');
a.put('select-choices.html', '<lx-dropdown-menu class="lx-select-choices"\n' +
' ng-class="{ \'lx-select-choices--custom-style\': lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--default-style\': !lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--is-multiple\': lxSelectChoices.parentCtrl.multiple,\n' +
' \'lx-select-choices--is-unique\': !lxSelectChoices.parentCtrl.multiple, }">\n' +
' <ul>\n' +
' <li class="lx-select-choices__filter" ng-if="::lxSelectChoices.parentCtrl.displayFilter && !lxSelectChoices.parentCtrl.autocomplete">\n' +
' <lx-search-filter lx-dropdown-filter>\n' +
' <input type="text" ng-model="lxSelectChoices.parentCtrl.filterModel" ng-change="lxSelectChoices.parentCtrl.updateFilter()">\n' +
' </lx-search-filter>\n' +
' </li>\n' +
' \n' +
' <div ng-if="::lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat="choice in lxSelectChoices.parentCtrl.choices | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <div ng-if="::!lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__subheader"\n' +
' ng-repeat-start="(subheader, children) in lxSelectChoices.parentCtrl.choices"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displaySubheader(subheader)"></li>\n' +
'\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat-end\n' +
' ng-repeat="choice in children | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <li class="lx-select-choices__subheader" ng-if="lxSelectChoices.parentCtrl.helperDisplayable()">\n' +
' {{ lxSelectChoices.parentCtrl.helperMessage }}\n' +
' </li>\n' +
'\n' +
' <li class="lx-select-choices__loader" ng-if="lxSelectChoices.parentCtrl.loading">\n' +
' <lx-progress lx-type="circular" lx-color="primary" lx-diameter="20"></lx-progress>\n' +
' </li>\n' +
' </ul>\n' +
'</lx-dropdown-menu>\n' +
'');
}]);
angular.module("lumx.tabs").run(['$templateCache', function(a) { a.put('tabs.html', '<div class="tabs tabs--layout-{{ lxTabs.layout }} tabs--theme-{{ lxTabs.theme }} tabs--color-{{ lxTabs.color }} tabs--indicator-{{ lxTabs.indicator }}">\n' +
' <div class="tabs__links">\n' +
' <a class="tabs__link"\n' +
' ng-class="{ \'tabs__link--is-active\': lxTabs.tabIsActive(tab.index),\n' +
' \'tabs__link--is-disabled\': tab.disabled }"\n' +
' ng-repeat="tab in lxTabs.tabs"\n' +
' ng-click="lxTabs.setActiveTab(tab)"\n' +
' lx-ripple>\n' +
' <i class="mdi mdi-{{ tab.icon }}" ng-if="tab.icon"></i>\n' +
' <span ng-if="tab.label">{{ tab.label }}</span>\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <div class="tabs__panes" ng-if="lxTabs.viewMode === \'gather\'" ng-transclude></div>\n' +
' <div class="tabs__indicator"></div>\n' +
'</div>\n' +
'');
a.put('tabs-panes.html', '<div class="tabs">\n' +
' <div class="tabs__panes" ng-transclude></div>\n' +
'</div>');
a.put('tab.html', '<div class="tabs__pane" ng-class="{ \'tabs__pane--is-disabled\': lxTab.ngDisabled }">\n' +
' <div ng-if="lxTab.tabIsActive()" ng-transclude></div>\n' +
'</div>\n' +
'');
a.put('tab-pane.html', '<div class="tabs__pane" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.date-picker").run(['$templateCache', function(a) { a.put('date-picker.html', '<div class="lx-date">\n' +
' <!-- Date picker input -->\n' +
' <div class="lx-date-input" ng-click="lxDatePicker.openDatePicker()" ng-if="lxDatePicker.hasInput">\n' +
' <ng-transclude></ng-transclude>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker -->\n' +
' <div class="lx-date-picker lx-date-picker--{{ lxDatePicker.color }}">\n' +
' <div ng-if="lxDatePicker.isOpen">\n' +
' <!-- Date picker: header -->\n' +
' <div class="lx-date-picker__header">\n' +
' <a class="lx-date-picker__current-year"\n' +
' ng-class="{ \'lx-date-picker__current-year--is-active\': lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.displayYearSelection()">\n' +
' {{ lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }}\n' +
' </a>\n' +
'\n' +
' <a class="lx-date-picker__current-date"\n' +
' ng-class="{ \'lx-date-picker__current-date--is-active\': !lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.hideYearSelection()">\n' +
' {{ lxDatePicker.getDateFormatted() }}\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker: content -->\n' +
' <div class="lx-date-picker__content">\n' +
' <!-- Calendar -->\n' +
' <div class="lx-date-picker__calendar" ng-if="!lxDatePicker.yearSelection">\n' +
' <div class="lx-date-picker__nav">\n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.previousMonth()">\n' +
' <i class="mdi mdi-chevron-left"></i>\n' +
' </lx-button>\n' +
'\n' +
' <span>{{ lxDatePicker.ngModelMoment.format(\'MMMM YYYY\') }}</span>\n' +
' \n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.nextMonth()">\n' +
' <i class="mdi mdi-chevron-right"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days-of-week">\n' +
' <span ng-repeat="day in lxDatePicker.daysOfWeek">{{ day }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days">\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyFirstDays"> </span>\n' +
'\n' +
' <div class="lx-date-picker__day"\n' +
' ng-class="{ \'lx-date-picker__day--is-selected\': day.selected,\n' +
' \'lx-date-picker__day--is-today\': day.today && !day.selected,\n' +
' \'lx-date-picker__day--is-disabled\': day.disabled }"\n' +
' ng-repeat="day in lxDatePicker.days">\n' +
' <a ng-click="lxDatePicker.select(day)">{{ day ? day.format(\'D\') : \'\' }}</a>\n' +
' </div>\n' +
'\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyLastDays"> </span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Year selection -->\n' +
' <div class="lx-date-picker__year-selector" ng-if="lxDatePicker.yearSelection">\n' +
' <a class="lx-date-picker__year"\n' +
' ng-class="{ \'lx-date-picker__year--is-active\': year == lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }"\n' +
' ng-repeat="year in lxDatePicker.years"\n' +
' ng-click="lxDatePicker.selectYear(year)"\n' +
' ng-if="lxDatePicker.yearSelection">\n' +
' {{ year }}\n' +
' </a>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Actions -->\n' +
' <div class="lx-date-picker__actions">\n' +
' <lx-button lx-color="{{ lxDatePicker.color }}" lx-type="flat" ng-click="lxDatePicker.closeDatePicker()">\n' +
' Ok\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.progress").run(['$templateCache', function(a) { a.put('progress.html', '<div class="progress-container progress-container--{{ lxProgress.lxType }} progress-container--{{ lxProgress.lxColor }}"\n' +
' ng-class="{ \'progress-container--determinate\': lxProgress.lxValue,\n' +
' \'progress-container--indeterminate\': !lxProgress.lxValue }">\n' +
' <div class="progress-circular"\n' +
' ng-if="lxProgress.lxType === \'circular\'"\n' +
' ng-style="lxProgress.getProgressDiameter()">\n' +
' <svg class="progress-circular__svg">\n' +
' <circle class="progress-circular__path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10" ng-style="lxProgress.getCircularProgressValue()">\n' +
' </svg>\n' +
' </div>\n' +
'\n' +
' <div class="progress-linear" ng-if="lxProgress.lxType === \'linear\'">\n' +
' <div class="progress-linear__background"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--first" ng-style="lxProgress.getLinearProgressValue()"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--second"></div>\n' +
' </div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.button").run(['$templateCache', function(a) { a.put('link.html', '<a ng-transclude lx-ripple></a>\n' +
'');
a.put('button.html', '<button ng-transclude lx-ripple></button>\n' +
'');
}]);
angular.module("lumx.checkbox").run(['$templateCache', function(a) { a.put('checkbox.html', '<div class="checkbox checkbox--{{ lxCheckbox.lxColor }}"\n' +
' ng-class="{ \'checkbox--theme-light\': !lxCheckbox.theme || lxCheckbox.theme === \'light\',\n' +
' \'checkbox--theme-dark\': lxCheckbox.theme === \'dark\' }" >\n' +
' <input id="{{ lxCheckbox.getCheckboxId() }}"\n' +
' type="checkbox"\n' +
' class="checkbox__input"\n' +
' name="{{ lxCheckbox.name }}"\n' +
' ng-model="lxCheckbox.ngModel"\n' +
' ng-true-value="{{ lxCheckbox.ngTrueValue }}"\n' +
' ng-false-value="{{ lxCheckbox.ngFalseValue }}"\n' +
' ng-change="lxCheckbox.triggerNgChange()"\n' +
' ng-disabled="lxCheckbox.ngDisabled">\n' +
'\n' +
' <label for="{{ lxCheckbox.getCheckboxId() }}" class="checkbox__label" ng-transclude ng-if="!lxCheckbox.getCheckboxHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxCheckbox.getCheckboxHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('checkbox-label.html', '<label for="{{ lxCheckboxLabel.getCheckboxId() }}" class="checkbox__label" ng-transclude></label>\n' +
'');
a.put('checkbox-help.html', '<span class="checkbox__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.radio-button").run(['$templateCache', function(a) { a.put('radio-group.html', '<div class="radio-group" ng-transclude></div>\n' +
'');
a.put('radio-button.html', '<div class="radio-button radio-button--{{ lxRadioButton.lxColor }}">\n' +
' <input id="{{ lxRadioButton.getRadioButtonId() }}"\n' +
' type="radio"\n' +
' class="radio-button__input"\n' +
' name="{{ lxRadioButton.name }}"\n' +
' ng-model="lxRadioButton.ngModel"\n' +
' ng-value="lxRadioButton.ngValue"\n' +
' ng-change="lxRadioButton.triggerNgChange()"\n' +
' ng-disabled="lxRadioButton.ngDisabled">\n' +
'\n' +
' <label for="{{ lxRadioButton.getRadioButtonId() }}" class="radio-button__label" ng-transclude ng-if="!lxRadioButton.getRadioButtonHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxRadioButton.getRadioButtonHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('radio-button-label.html', '<label for="{{ lxRadioButtonLabel.getRadioButtonId() }}" class="radio-button__label" ng-transclude></label>\n' +
'');
a.put('radio-button-help.html', '<span class="radio-button__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.stepper").run(['$templateCache', function(a) { a.put('stepper.html', '<div class="lx-stepper" ng-class="lxStepper.getClasses()">\n' +
' <div class="lx-stepper__header" ng-if="lxStepper.layout === \'horizontal\'">\n' +
' <div class="lx-stepper__nav">\n' +
' <lx-step-nav lx-active-index="{{ lxStepper.activeIndex }}" lx-step="step" ng-repeat="step in lxStepper.steps"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__feedback" ng-if="lxStepper.steps[lxStepper.activeIndex].feedback">\n' +
' <span>{{ lxStepper.steps[lxStepper.activeIndex].feedback }}</span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__steps" ng-transclude></div>\n' +
'</div>');
a.put('step.html', '<div class="lx-step" ng-class="lxStep.getClasses()">\n' +
' <div class="lx-step__nav" ng-if="lxStep.parent.layout === \'vertical\'">\n' +
' <lx-step-nav lx-active-index="{{ lxStep.parent.activeIndex }}" lx-step="lxStep.step"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__wrapper" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__content">\n' +
' <ng-transclude></ng-transclude>\n' +
'\n' +
' <div class="lx-step__progress" ng-if="lxStep.step.isLoading">\n' +
' <lx-progress lx-type="circular"></lx-progress>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__actions" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__action lx-step__action--continue">\n' +
' <lx-button ng-click="lxStep.submitStep()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.continue }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--cancel" ng-if="lxStep.parent.cancel">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.parent.cancel()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.cancel }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--back" ng-if="lxStep.parent.isLinear">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.previousStep()" ng-disabled="lxStep.isLoading || lxStep.step.index === 0">{{ lxStep.parent.labels.back }}</lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
a.put('step-nav.html', '<div class="lx-step-nav" ng-click="lxStepNav.parent.goToStep(lxStepNav.step.index)" ng-class="lxStepNav.getClasses()" lx-ripple>\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--index" ng-if="lxStepNav.step.isValid === undefined">\n' +
' <span>{{ lxStepNav.step.index + 1 }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--icon" ng-if="lxStepNav.step.isValid === true">\n' +
' <lx-icon lx-id="check" ng-if="!lxStepNav.step.isEditable"></lx-icon>\n' +
' <lx-icon lx-id="pencil" ng-if="lxStepNav.step.isEditable"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--error" ng-if="lxStepNav.step.isValid === false">\n' +
' <lx-icon lx-id="alert"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__wrapper">\n' +
' <div class="lx-step-nav__label">\n' +
' <span>{{ lxStepNav.step.label }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__state">\n' +
' <span ng-if="(lxStepNav.step.isValid === undefined || lxStepNav.step.isValid === true) && lxStepNav.step.isOptional">{{ lxStepNav.parent.labels.optional }}</span>\n' +
' <span ng-if="lxStepNav.step.isValid === false">{{ lxStepNav.step.errorMessage }}</span>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.switch").run(['$templateCache', function(a) { a.put('switch.html', '<div class="switch switch--{{ lxSwitch.lxColor }} switch--{{ lxSwitch.lxPosition }}">\n' +
' <input id="{{ lxSwitch.getSwitchId() }}"\n' +
' type="checkbox"\n' +
' class="switch__input"\n' +
' name="{{ lxSwitch.name }}"\n' +
' ng-model="lxSwitch.ngModel"\n' +
' ng-true-value="{{ lxSwitch.ngTrueValue }}"\n' +
' ng-false-value="{{ lxSwitch.ngFalseValue }}"\n' +
' ng-change="lxSwitch.triggerNgChange()"\n' +
' ng-disabled="lxSwitch.ngDisabled">\n' +
'\n' +
' <label for="{{ lxSwitch.getSwitchId() }}" class="switch__label" ng-transclude ng-if="!lxSwitch.getSwitchHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxSwitch.getSwitchHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('switch-label.html', '<label for="{{ lxSwitchLabel.getSwitchId() }}" class="switch__label" ng-transclude></label>\n' +
'');
a.put('switch-help.html', '<span class="switch__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.fab").run(['$templateCache', function(a) { a.put('fab.html', '<div class="fab">\n' +
' <ng-transclude-replace></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('fab-trigger.html', '<div class="fab__primary" ng-transclude></div>\n' +
'');
a.put('fab-actions.html', '<div class="fab__actions fab__actions--{{ parentCtrl.lxDirection }}" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.icon").run(['$templateCache', function(a) { a.put('icon.html', '<i class="icon mdi" ng-class="lxIcon.getClass()"></i>');
}]);
angular.module("lumx.data-table").run(['$templateCache', function(a) { a.put('data-table.html', '<div class="data-table-container">\n' +
' <table class="data-table"\n' +
' ng-class="{ \'data-table--no-border\': !lxDataTable.border,\n' +
' \'data-table--thumbnail\': lxDataTable.thumbnail }">\n' +
' <thead>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && lxDataTable.allRowsSelected }">\n' +
' <th ng-if="lxDataTable.thumbnail"></th>\n' +
' <th ng-click="lxDataTable.toggleAllSelected()"\n' +
' ng-if="lxDataTable.selectable"></th>\n' +
' <th ng-class=" { \'data-table__sortable-cell\': th.sortable,\n' +
' \'data-table__sortable-cell--asc\': th.sortable && th.sort === \'asc\',\n' +
' \'data-table__sortable-cell--desc\': th.sortable && th.sort === \'desc\' }"\n' +
' ng-click="lxDataTable.sort(th)"\n' +
' ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <lx-icon lx-id="{{ th.icon }}" ng-if="th.icon"></lx-icon>\n' +
' <span>{{ th.label }}</span>\n' +
' </th>\n' +
' </tr>\n' +
' </thead>\n' +
'\n' +
' <tbody>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-disabled\': lxDataTable.selectable && tr.lxDataTableDisabled,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && tr.lxDataTableSelected }"\n' +
' ng-repeat="tr in lxDataTable.tbody"\n' +
' ng-click="lxDataTable.toggle(tr)">\n' +
' <td ng-if="lxDataTable.thumbnail">\n' +
' <div ng-if="lxDataTable.thead[0].format" ng-bind-html="lxDataTable.$sce.trustAsHtml(lxDataTable.thead[0].format(tr))"></div>\n' +
' </td>\n' +
' <td ng-if="lxDataTable.selectable"></td>\n' +
' <td ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <span ng-if="!th.format">{{ tr[th.name] }}</span>\n' +
' <div ng-if="th.format" ng-bind-html="lxDataTable.$sce.trustAsHtml(th.format(tr))"></div>\n' +
' </td>\n' +
' </tr>\n' +
' </tbody>\n' +
' </table>\n' +
'</div>');
}]); |
// File: chapter14/appUnderTest/app/scripts/app.js
angular.module('fifaApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
})
.when('/team/:code', {
templateUrl: 'views/team_details.html',
controller:'TeamDetailsCtrl as teamDetailsCtrl',
resolve: {
auth: ['$q', '$location', 'UserService',
function($q, $location, UserService) {
return UserService.session().then(
function(success) {},
function(err) {
$location.path('/login');
return $q.reject(err);
});
}]
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
|
module.exports = require('./lib/socket.io'); |
var _complement = require('./internal/_complement');
var _curry2 = require('./internal/_curry2');
var filter = require('./filter');
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @see R.filter
* @example
*
* var isOdd = function(n) {
* return n % 2 === 1;
* };
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*/
module.exports = _curry2(function reject(fn, list) {
return filter(_complement(fn), list);
});
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js
*
* Copyright (c) 2013-2014 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['AsanaMathJax_Size1'] = {
directory: 'Size1/Regular',
family: 'AsanaMathJax_Size1',
testString: '\u0302\u0303\u0305\u0306\u030C\u0332\u0333\u033F\u2016\u2044\u2045\u2046\u20D6\u20D7\u220F',
0x20: [0,0,249,0,0],
0x28: [981,490,399,84,360],
0x29: [981,490,399,40,316],
0x5B: [984,492,350,84,321],
0x5D: [984,492,350,84,321],
0x7B: [981,490,362,84,328],
0x7C: [908,367,241,86,156],
0x7D: [981,490,362,84,328],
0x302: [783,-627,453,0,453],
0x303: [763,-654,700,0,701],
0x305: [587,-542,510,0,511],
0x306: [664,-506,383,0,384],
0x30C: [783,-627,736,0,737],
0x332: [-130,175,510,0,511],
0x333: [-130,283,510,0,511],
0x33F: [695,-542,510,0,511],
0x2016: [908,367,436,86,351],
0x2044: [742,463,382,-69,383],
0x2045: [943,401,353,64,303],
0x2046: [943,401,358,30,269],
0x20D6: [790,-519,807,0,807],
0x20D7: [790,-519,807,0,807],
0x220F: [901,448,1431,78,1355],
0x2210: [901,448,1431,78,1355],
0x2211: [893,446,1224,89,1135],
0x221A: [1280,0,770,63,803],
0x2229: [1039,520,1292,124,1169],
0x222B: [1310,654,1000,54,1001],
0x222C: [1310,654,1659,54,1540],
0x222D: [1310,654,2198,54,2079],
0x222E: [1310,654,1120,54,1001],
0x222F: [1310,654,1659,54,1540],
0x2230: [1310,654,2198,54,2079],
0x2231: [1310,654,1120,54,1001],
0x2232: [1310,654,1146,80,1027],
0x2233: [1310,654,1120,54,1001],
0x22C0: [1040,519,1217,85,1132],
0x22C1: [1040,519,1217,85,1132],
0x22C2: [1039,520,1292,124,1169],
0x22C3: [1039,520,1292,124,1169],
0x2308: [980,490,390,84,346],
0x2309: [980,490,390,84,346],
0x230A: [980,490,390,84,346],
0x230B: [980,490,390,84,346],
0x23B4: [755,-518,977,0,978],
0x23B5: [-238,475,977,0,978],
0x23DC: [821,-545,972,0,973],
0x23DD: [-545,821,972,0,973],
0x23DE: [789,-545,1572,51,1522],
0x23DF: [-545,789,1572,51,1522],
0x23E0: [755,-545,1359,0,1360],
0x23E1: [-545,755,1359,0,1360],
0x27C5: [781,240,450,53,397],
0x27C6: [781,240,450,53,397],
0x27E6: [684,341,502,84,473],
0x27E7: [684,341,502,84,473],
0x27E8: [681,340,422,53,371],
0x27E9: [681,340,422,53,371],
0x27EA: [681,340,605,53,554],
0x27EB: [681,340,605,53,554],
0x29FC: [915,457,518,50,469],
0x29FD: [915,457,518,49,469],
0x2A00: [1100,550,1901,124,1778],
0x2A01: [1100,550,1901,124,1778],
0x2A02: [1100,550,1901,124,1778],
0x2A03: [1039,520,1292,124,1169],
0x2A04: [1039,520,1292,124,1169],
0x2A05: [1024,513,1292,124,1169],
0x2A06: [1024,513,1292,124,1169],
0x2A07: [1039,520,1415,86,1330],
0x2A08: [1039,520,1415,86,1330],
0x2A09: [888,445,1581,124,1459],
0x2A0C: [1310,654,2736,54,2617],
0x2A0D: [1310,654,1120,54,1001],
0x2A0E: [1310,654,1120,54,1001],
0x2A0F: [1310,654,1120,54,1001],
0x2A10: [1310,654,1120,54,1001],
0x2A11: [1310,654,1182,54,1063],
0x2A12: [1310,654,1120,54,1001],
0x2A13: [1310,654,1120,54,1001],
0x2A14: [1310,654,1120,54,1001],
0x2A15: [1310,654,1120,54,1001],
0x2A16: [1310,654,1120,54,1001],
0x2A17: [1310,654,1431,54,1362],
0x2A18: [1310,654,1120,54,1001],
0x2A19: [1310,654,1120,54,1001],
0x2A1A: [1310,654,1120,54,1001],
0x2A1B: [1471,654,1130,54,1011],
0x2A1C: [1471,654,1156,80,1037]
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Size1"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Size1/Regular/Main.js"]
);
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/Variants/Regular/Main.js
*
* Copyright (c) 2013-2014 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['NeoEulerMathJax_Variants'] = {
directory: 'Variants/Regular',
family: 'NeoEulerMathJax_Variants',
testString: '\u00A0\u2032\u2033\u2034\u2035\u2036\u2037\u2057\uE200\uE201\uE202\uE203\uE204\uE205\uE206',
0x20: [0,0,333,0,0],
0xA0: [0,0,333,0,0],
0x2032: [559,-41,329,48,299],
0x2033: [559,-41,640,48,610],
0x2034: [559,-41,950,48,920],
0x2035: [559,-41,329,48,299],
0x2036: [559,-41,640,48,610],
0x2037: [559,-41,950,48,919],
0x2057: [559,-41,1260,48,1230],
0xE200: [493,13,501,41,456],
0xE201: [469,1,501,46,460],
0xE202: [474,-1,501,59,485],
0xE203: [474,182,501,38,430],
0xE204: [476,192,501,10,482],
0xE205: [458,184,501,47,441],
0xE206: [700,13,501,45,471],
0xE207: [468,181,501,37,498],
0xE208: [706,10,501,40,461],
0xE209: [470,182,501,27,468]
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_Variants"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Variants/Regular/Main.js"]
);
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v9.0.3
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("./context/context");
var LINE_SEPARATOR = '\r\n';
var XmlFactory = (function () {
function XmlFactory() {
}
XmlFactory.prototype.createXml = function (xmlElement, booleanTransformer) {
var _this = this;
var props = "";
if (xmlElement.properties) {
if (xmlElement.properties.prefixedAttributes) {
xmlElement.properties.prefixedAttributes.forEach(function (prefixedSet) {
Object.keys(prefixedSet.map).forEach(function (key) {
props += _this.returnAttributeIfPopulated(prefixedSet.prefix + key, prefixedSet.map[key], booleanTransformer);
});
});
}
if (xmlElement.properties.rawMap) {
Object.keys(xmlElement.properties.rawMap).forEach(function (key) {
props += _this.returnAttributeIfPopulated(key, xmlElement.properties.rawMap[key], booleanTransformer);
});
}
}
var result = "<" + xmlElement.name + props;
if (!xmlElement.children && !xmlElement.textNode) {
return result + "/>" + LINE_SEPARATOR;
}
if (xmlElement.textNode) {
return result + ">" + xmlElement.textNode + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
}
result += ">" + LINE_SEPARATOR;
xmlElement.children.forEach(function (it) {
result += _this.createXml(it, booleanTransformer);
});
return result + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
};
XmlFactory.prototype.returnAttributeIfPopulated = function (key, value, booleanTransformer) {
if (!value) {
return "";
}
var xmlValue = value;
if ((typeof (value) === 'boolean')) {
if (booleanTransformer) {
xmlValue = booleanTransformer(value);
}
}
xmlValue = '"' + xmlValue + '"';
return " " + key + "=" + xmlValue;
};
return XmlFactory;
}());
XmlFactory = __decorate([
context_1.Bean('xmlFactory')
], XmlFactory);
exports.XmlFactory = XmlFactory;
|
/**
* High performant way to check whether an element with a specific class name is in the given document
* Optimized for being heavily executed
* Unleashes the power of live node lists
*
* @param {Object} doc The document object of the context where to check
* @param {String} tagName Upper cased tag name
* @example
* wysihtml5.dom.hasElementWithClassName(document, "foobar");
*/
(function(wysihtml5) {
var LIVE_CACHE = {},
DOCUMENT_IDENTIFIER = 1;
function _getDocumentIdentifier(doc) {
return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
}
wysihtml5.dom.hasElementWithClassName = function(doc, className) {
// getElementsByClassName is not supported by IE<9
// but is sometimes mocked via library code (which then doesn't return live node lists)
if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) {
return !!doc.querySelector("." + className);
}
var key = _getDocumentIdentifier(doc) + ":" + className,
cacheEntry = LIVE_CACHE[key];
if (!cacheEntry) {
cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className);
}
return cacheEntry.length > 0;
};
})(wysihtml5);
|
'use strict';
angular.module('showcase', [
'showcase.angularWay',
'showcase.angularWay.withOptions',
'showcase.withAjax',
'showcase.withOptions',
'showcase.withPromise',
'showcase.angularWay.dataChange',
'showcase.bindAngularDirective',
'showcase.changeOptions',
'showcase.dataReload.withAjax',
'showcase.dataReload.withPromise',
'showcase.disableDeepWatchers',
'showcase.loadOptionsWithPromise',
'showcase.angularDirectiveInDOM',
'showcase.rerender',
'showcase.rowClickEvent',
'showcase.rowSelect',
'showcase.serverSideProcessing',
'showcase.bootstrapIntegration',
'showcase.overrideBootstrapOptions',
'showcase.withAngularTranslate',
'showcase.withColReorder',
'showcase.withColumnFilter',
'showcase.withLightColumnFilter',
'showcase.withColVis',
'showcase.withResponsive',
'showcase.withScroller',
'showcase.withTableTools',
'showcase.withFixedColumns',
'showcase.withFixedHeader',
'showcase.withButtons',
'showcase.withSelect',
'showcase.dtInstances',
'showcase.usages',
'ui.bootstrap',
'ui.router',
'hljs'
])
.config(sampleConfig)
.config(routerConfig)
.config(translateConfig)
.config(debugDisabled)
.run(initDT);
backToTop.init({
theme: 'classic', // Available themes: 'classic', 'sky', 'slate'
animation: 'fade' // Available animations: 'fade', 'slide'
});
function debugDisabled($compileProvider) {
$compileProvider.debugInfoEnabled(false);
}
function sampleConfig(hljsServiceProvider) {
hljsServiceProvider.setOptions({
// replace tab with 4 spaces
tabReplace: ' '
});
}
function routerConfig($stateProvider, $urlRouterProvider, USAGES) {
$urlRouterProvider.otherwise('/welcome');
$stateProvider
.state('welcome', {
url: '/welcome',
templateUrl: 'demo/partials/welcome.html',
controller: function($rootScope) {
$rootScope.$broadcast('event:changeView', 'welcome');
}
})
.state('gettingStarted', {
url: '/gettingStarted',
templateUrl: 'demo/partials/gettingStarted.html',
controller: function($rootScope) {
$rootScope.$broadcast('event:changeView', 'gettingStarted');
}
})
.state('api', {
url: '/api',
templateUrl: 'demo/api/api.html',
controller: function($rootScope) {
$rootScope.$broadcast('event:changeView', 'api');
}
});
angular.forEach(USAGES, function(usages, key) {
angular.forEach(usages, function(usage) {
$stateProvider.state(usage.name, {
url: '/' + usage.name,
templateUrl: 'demo/' + key + '/' + usage.name + '.html',
controller: function($rootScope) {
$rootScope.$broadcast('event:changeView', usage.name);
},
onExit: usage.onExit
});
});
});
}
function translateConfig($translateProvider) {
$translateProvider.translations('en', {
id: 'ID with angular-translate',
firstName: 'First name with angular-translate',
lastName: 'Last name with angular-translate'
});
$translateProvider.translations('fr', {
id: 'ID avec angular-translate',
firstName: 'Prénom avec angular-translate',
lastName: 'Nom avec angular-translate'
});
$translateProvider.preferredLanguage('en');
}
function initDT(DTDefaultOptions) {
DTDefaultOptions.setLoadingTemplate('<img src="/angular-datatables/images/loading.gif" />');
}
|
export default (...modifiers): Array<string> => {};
|
// Karma configuration
// Generated on Sun Apr 14 2013 18:31:17 GMT+0200 (CEST)
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'http://code.angularjs.org/1.1.4/angular.js',
'http://code.angularjs.org/1.1.4/angular-resource.js',
'http://code.angularjs.org/1.1.4/angular-mocks.js',
'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js',
'src/restangular.js',
'test/*.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];
// web server port
port = 9877;
// cli runner port
runnerPort = 9101;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['PhantomJS'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
/**
*
*/
var obj = {
num: 123,
str: 'hello',
};
obj.
|
function error_log(message, message_type, destination, extra_headers) {
// http://kevin.vanzonneveld.net
// + original by: Paul Hutchinson (http://restaurantthing.com/)
// + revised by: Brett Zamir (http://brett-zamir.me)
// % note 1: The dependencies, mail(), syslog(), and file_put_contents()
// % note 1: are either not fullly implemented or implemented at all
// - depends on: mail
// - depends on: syslog
// - depends on: file_put_contents
// * example 1: error_log('Oops!');
// * returns 1: true
var that = this,
_sapi = function() { // SAPI logging (we treat console as the "server" logging; the
// syslog option could do so potentially as well)
if (!that.window.console || !that.window.console.log) {
return false;
}
that.window.console.log(message);
return true;
};
message_type = message_type || 0;
switch (message_type) {
case 1: // Email
var subject = 'PHP error_log message'; // Apparently no way to customize the subject
return this.mail(destination, subject, message, extra_headers);
case 2: // No longer an option in PHP, but had been to send via TCP/IP to 'destination' (name or IP:port)
// use socket_create() and socket_send()?
return false;
case 0: // syslog or file depending on ini
var log = this.php_js && this.php_js.ini && this.php_js.ini.error_log && this.php_js.ini.error_log.local_value;
if (!log) {
return _sapi();
}
if (log === 'syslog') {
return this.syslog(4, message); // presumably 'LOG_ERR' (4) is correct?
}
destination = log;
// Fall-through
case 3: // File logging
var ret = this.file_put_contents(destination, message, 8); // FILE_APPEND (8)
return ret === false ? false : true;
case 4: // SAPI logging
return _sapi();
default: // Unrecognized value
return false;
}
return false; // Shouldn't get here
}
|
/**
* 404 (Not Found) Handler
*
* Usage:
* return res.notFound();
* return res.notFound(err);
* return res.notFound(err, 'some/specific/notfound/view');
*
* e.g.:
* ```
* return res.notFound();
* ```
*
* NOTE:
* If a request doesn't match any explicit routes (i.e. `config/routes.js`)
* or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()`
* automatically.
*/
module.exports = function notFound (data, options) {
// Get access to `req`, `res`, & `sails`
var req = this.req;
var res = this.res;
var sails = req._sails;
// Set status code
res.status(404);
// Log error to console
if (data !== undefined) {
sails.log.verbose('Sending 404 ("Not Found") response: \n',data);
}
else sails.log.verbose('Sending 404 ("Not Found") response');
// Only include errors in response if application environment
// is not set to 'production'. In production, we shouldn't
// send back any identifying information about errors.
if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) {
data = undefined;
}
// If the user-agent wants JSON, always respond with JSON
if (req.wantsJSON) {
return res.jsonx(data);
}
// If second argument is a string, we take that to mean it refers to a view.
// If it was omitted, use an empty object (`{}`)
options = (typeof options === 'string') ? { view: options } : options || {};
// If a view was provided in options, serve it.
// Otherwise try to guess an appropriate view, or if that doesn't
// work, just send JSON.
if (options.view) {
return res.view(options.view, { data: data });
}
// If no second argument provided, try to serve the default view,
// but fall back to sending JSON(P) if any errors occur.
else return res.view('404', { data: data }, function (err, html) {
// If a view error occured, fall back to JSON(P).
if (err) {
//
// Additionally:
// • If the view was missing, ignore the error but provide a verbose log.
if (err.code === 'E_VIEW_FAILED') {
sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err);
}
// Otherwise, if this was a more serious error, log to the console with the details.
else {
sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err);
}
return res.jsonx(data);
}
return res.send(html);
});
};
|
(function(){var e=window.AmCharts;e.AmRectangularChart=e.Class({inherits:e.AmCoordinateChart,construct:function(a){e.AmRectangularChart.base.construct.call(this,a);this.theme=a;this.createEvents("zoomed","changed");this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=20;this.depth3D=this.angle=0;this.plotAreaFillColors="#FFFFFF";this.plotAreaFillAlphas=0;this.plotAreaBorderColor="#000000";this.plotAreaBorderAlpha=0;this.maxZoomFactor=20;this.zoomOutButtonImageSize=19;this.zoomOutButtonImage=
"lens";this.zoomOutText="Show all";this.zoomOutButtonColor="#e5e5e5";this.zoomOutButtonAlpha=0;this.zoomOutButtonRollOverAlpha=1;this.zoomOutButtonPadding=8;this.trendLines=[];this.autoMargins=!0;this.marginsUpdated=!1;this.autoMarginOffset=10;e.applyTheme(this,a,"AmRectangularChart")},initChart:function(){e.AmRectangularChart.base.initChart.call(this);this.updateDxy();!this.marginsUpdated&&this.autoMargins&&(this.resetMargins(),this.drawGraphs=!1);this.processScrollbars();this.updateMargins();this.updatePlotArea();
this.updateScrollbars();this.updateTrendLines();this.updateChartCursor();this.updateValueAxes();this.scrollbarOnly||this.updateGraphs()},drawChart:function(){e.AmRectangularChart.base.drawChart.call(this);this.drawPlotArea();if(e.ifArray(this.chartData)){var a=this.chartCursor;a&&a.draw()}},resetMargins:function(){var a={},b;if("xy"==this.type){var c=this.xAxes,d=this.yAxes;for(b=0;b<c.length;b++){var g=c[b];g.ignoreAxisWidth||(g.setOrientation(!0),g.fixAxisPosition(),a[g.position]=!0)}for(b=0;b<
d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(!1),c.fixAxisPosition(),a[c.position]=!0)}else{d=this.valueAxes;for(b=0;b<d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(this.rotate),c.fixAxisPosition(),a[c.position]=!0);(b=this.categoryAxis)&&!b.ignoreAxisWidth&&(b.setOrientation(!this.rotate),b.fixAxisPosition(),b.fixAxisPosition(),a[b.position]=!0)}a.left&&(this.marginLeft=0);a.right&&(this.marginRight=0);a.top&&(this.marginTop=0);a.bottom&&(this.marginBottom=0);this.fixMargins=
a},measureMargins:function(){var a=this.valueAxes,b,c=this.autoMarginOffset,d=this.fixMargins,g=this.realWidth,e=this.realHeight,f=c,k=c,m=g;b=e;var l;for(l=0;l<a.length;l++)a[l].handleSynchronization(),b=this.getAxisBounds(a[l],f,m,k,b),f=Math.round(b.l),m=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b);if(a=this.categoryAxis)b=this.getAxisBounds(a,f,m,k,b),f=Math.round(b.l),m=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b);d.left&&f<c&&(this.marginLeft=Math.round(-f+c),!isNaN(this.minMarginLeft)&&
this.marginLeft<this.minMarginLeft&&(this.marginLeft=this.minMarginLeft));d.right&&m>=g-c&&(this.marginRight=Math.round(m-g+c),!isNaN(this.minMarginRight)&&this.marginRight<this.minMarginRight&&(this.marginRight=this.minMarginRight));d.top&&k<c+this.titleHeight&&(this.marginTop=Math.round(this.marginTop-k+c+this.titleHeight),!isNaN(this.minMarginTop)&&this.marginTop<this.minMarginTop&&(this.marginTop=this.minMarginTop));d.bottom&&b>e-c&&(this.marginBottom=Math.round(this.marginBottom+b-e+c),!isNaN(this.minMarginBottom)&&
this.marginBottom<this.minMarginBottom&&(this.marginBottom=this.minMarginBottom));this.initChart()},getAxisBounds:function(a,b,c,d,e){if(!a.ignoreAxisWidth){var h=a.labelsSet,f=a.tickLength;a.inside&&(f=0);if(h)switch(h=a.getBBox(),a.position){case "top":a=h.y;d>a&&(d=a);break;case "bottom":a=h.y+h.height;e<a&&(e=a);break;case "right":a=h.x+h.width+f+3;c<a&&(c=a);break;case "left":a=h.x-f,b>a&&(b=a)}}return{l:b,t:d,r:c,b:e}},drawZoomOutButton:function(){var a=this;if(!a.zbSet){var b=a.container.set();
a.zoomButtonSet.push(b);var c=a.color,d=a.fontSize,g=a.zoomOutButtonImageSize,h=a.zoomOutButtonImage.replace(/\.[a-z]*$/i,""),f=a.langObj.zoomOutText||a.zoomOutText,k=a.zoomOutButtonColor,m=a.zoomOutButtonAlpha,l=a.zoomOutButtonFontSize,p=a.zoomOutButtonPadding;isNaN(l)||(d=l);(l=a.zoomOutButtonFontColor)&&(c=l);var l=a.zoomOutButton,q;l&&(l.fontSize&&(d=l.fontSize),l.color&&(c=l.color),l.backgroundColor&&(k=l.backgroundColor),isNaN(l.backgroundAlpha)||(a.zoomOutButtonRollOverAlpha=l.backgroundAlpha));
var r=l=0,r=a.pathToImages;if(h){if(e.isAbsolute(h)||void 0===r)r="";q=a.container.image(r+h+a.extension,0,0,g,g);e.setCN(a,q,"zoom-out-image");b.push(q);q=q.getBBox();l=q.width+5}void 0!==f&&(c=e.text(a.container,f,c,a.fontFamily,d,"start"),e.setCN(a,c,"zoom-out-label"),d=c.getBBox(),r=q?q.height/2-3:d.height/2,c.translate(l,r),b.push(c));q=b.getBBox();c=1;e.isModern||(c=0);k=e.rect(a.container,q.width+2*p+5,q.height+2*p-2,k,1,1,k,c);k.setAttr("opacity",m);k.translate(-p,-p);e.setCN(a,k,"zoom-out-bg");
b.push(k);k.toBack();a.zbBG=k;q=k.getBBox();b.translate(a.marginLeftReal+a.plotAreaWidth-q.width+p,a.marginTopReal+p);b.hide();b.mouseover(function(){a.rollOverZB()}).mouseout(function(){a.rollOutZB()}).click(function(){a.clickZB()}).touchstart(function(){a.rollOverZB()}).touchend(function(){a.rollOutZB();a.clickZB()});for(m=0;m<b.length;m++)b[m].attr({cursor:"pointer"});void 0!==a.zoomOutButtonTabIndex&&(b.setAttr("tabindex",a.zoomOutButtonTabIndex),b.setAttr("role","menuitem"),b.keyup(function(b){13==
b.keyCode&&a.clickZB()}));a.zbSet=b}},rollOverZB:function(){this.rolledOverZB=!0;this.zbBG.setAttr("opacity",this.zoomOutButtonRollOverAlpha)},rollOutZB:function(){this.rolledOverZB=!1;this.zbBG.setAttr("opacity",this.zoomOutButtonAlpha)},clickZB:function(){this.rolledOverZB=!1;this.zoomOut()},zoomOut:function(){this.zoomOutValueAxes()},drawPlotArea:function(){var a=this.dx,b=this.dy,c=this.marginLeftReal,d=this.marginTopReal,g=this.plotAreaWidth-1,h=this.plotAreaHeight-1,f=this.plotAreaFillColors,
k=this.plotAreaFillAlphas,m=this.plotAreaBorderColor,l=this.plotAreaBorderAlpha;"object"==typeof k&&(k=k[0]);f=e.polygon(this.container,[0,g,g,0,0],[0,0,h,h,0],f,k,1,m,l,this.plotAreaGradientAngle);e.setCN(this,f,"plot-area");f.translate(c+a,d+b);this.set.push(f);0!==a&&0!==b&&(f=this.plotAreaFillColors,"object"==typeof f&&(f=f[0]),f=e.adjustLuminosity(f,-.15),g=e.polygon(this.container,[0,a,g+a,g,0],[0,b,b,0,0],f,k,1,m,l),e.setCN(this,g,"plot-area-bottom"),g.translate(c,d+h),this.set.push(g),a=e.polygon(this.container,
[0,0,a,a,0],[0,h,h+b,b,0],f,k,1,m,l),e.setCN(this,a,"plot-area-left"),a.translate(c,d),this.set.push(a));(c=this.bbset)&&this.scrollbarOnly&&c.remove()},updatePlotArea:function(){var a=this.updateWidth(),b=this.updateHeight(),c=this.container;this.realWidth=a;this.realWidth=b;c&&this.container.setSize(a,b);var c=this.marginLeftReal,d=this.marginTopReal,a=a-c-this.marginRightReal-this.dx,b=b-d-this.marginBottomReal;1>a&&(a=1);1>b&&(b=1);this.plotAreaWidth=Math.round(a);this.plotAreaHeight=Math.round(b);
this.plotBalloonsSet.translate(c,d)},updateDxy:function(){this.dx=Math.round(this.depth3D*Math.cos(this.angle*Math.PI/180));this.dy=Math.round(-this.depth3D*Math.sin(this.angle*Math.PI/180));this.d3x=Math.round(this.columnSpacing3D*Math.cos(this.angle*Math.PI/180));this.d3y=Math.round(-this.columnSpacing3D*Math.sin(this.angle*Math.PI/180))},updateMargins:function(){var a=this.getTitleHeight();this.titleHeight=a;this.marginTopReal=this.marginTop-this.dy;this.fixMargins&&!this.fixMargins.top&&(this.marginTopReal+=
a);this.marginBottomReal=this.marginBottom;this.marginLeftReal=this.marginLeft;this.marginRightReal=this.marginRight},updateValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b];this.setAxisRenderers(c);this.updateObjectSize(c)}},setAxisRenderers:function(a){a.axisRenderer=e.RecAxis;a.guideFillRenderer=e.RecFill;a.axisItemRenderer=e.RecItem;a.marginsChanged=!0},updateGraphs:function(){var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.index=b;c.rotate=this.rotate;this.updateObjectSize(c)}},
updateObjectSize:function(a){a.width=this.plotAreaWidth-1;a.height=this.plotAreaHeight-1;a.x=this.marginLeftReal;a.y=this.marginTopReal;a.dx=this.dx;a.dy=this.dy},updateChartCursor:function(){var a=this.chartCursor;a&&(a=e.processObject(a,e.ChartCursor,this.theme),this.updateObjectSize(a),this.addChartCursor(a),a.chart=this)},processScrollbars:function(){var a=this.chartScrollbar;a&&(a=e.processObject(a,e.ChartScrollbar,this.theme),this.addChartScrollbar(a))},updateScrollbars:function(){},removeChartCursor:function(){e.callMethod("destroy",
[this.chartCursor]);this.chartCursor=null},zoomTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b];c.valueAxis.recalculateToPercents?c.set&&c.set.hide():(c.x=this.marginLeftReal,c.y=this.marginTopReal,c.draw())}},handleCursorValueZoom:function(){},addTrendLine:function(a){this.trendLines.push(a)},zoomOutValueAxes:function(){for(var a=this.valueAxes,b=0;b<a.length;b++)a[b].zoomOut()},removeTrendLine:function(a){var b=this.trendLines,c;for(c=b.length-1;0<=c;c--)b[c]==a&&
b.splice(c,1)},adjustMargins:function(a,b){var c=a.position,d=a.scrollbarHeight+a.offset;a.enabled&&("top"==c?b?this.marginLeftReal+=d:this.marginTopReal+=d:b?this.marginRightReal+=d:this.marginBottomReal+=d)},getScrollbarPosition:function(a,b,c){var d="bottom",e="top";a.oppositeAxis||(e=d,d="top");a.position=b?"bottom"==c||"left"==c?d:e:"top"==c||"right"==c?d:e},updateChartScrollbar:function(a,b){if(a){a.rotate=b;var c=this.marginTopReal,d=this.marginLeftReal,e=a.scrollbarHeight,h=this.dx,f=this.dy,
k=a.offset;"top"==a.position?b?(a.y=c,a.x=d-e-k):(a.y=c-e+f-k,a.x=d+h):b?(a.y=c+f,a.x=d+this.plotAreaWidth+h+k):(a.y=c+this.plotAreaHeight+k,a.x=this.marginLeftReal)}},showZB:function(a){var b=this.zbSet;a&&(b=this.zoomOutText,""!==b&&b&&this.drawZoomOutButton());if(b=this.zbSet)this.zoomButtonSet.push(b),a?b.show():b.hide(),this.rollOutZB()},handleReleaseOutside:function(a){e.AmRectangularChart.base.handleReleaseOutside.call(this,a);(a=this.chartCursor)&&a.handleReleaseOutside&&a.handleReleaseOutside()},
handleMouseDown:function(a){e.AmRectangularChart.base.handleMouseDown.call(this,a);var b=this.chartCursor;b&&b.handleMouseDown&&!this.rolledOverZB&&b.handleMouseDown(a)},update:function(){e.AmRectangularChart.base.update.call(this);this.chartCursor&&this.chartCursor.update&&this.chartCursor.update()},handleScrollbarValueZoom:function(a){this.relativeZoomValueAxes(a.target.valueAxes,a.relativeStart,a.relativeEnd);this.zoomAxesAndGraphs()},zoomValueScrollbar:function(a){if(a&&a.enabled){var b=a.valueAxes[0],
c=b.relativeStart,d=b.relativeEnd;b.reversed&&(d=1-c,c=1-b.relativeEnd);a.percentZoom(c,d)}},zoomAxesAndGraphs:function(){if(!this.scrollbarOnly){var a=this.valueAxes,b;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);a=this.graphs;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);(b=this.chartCursor)&&b.clearSelection();this.zoomTrendLines()}},handleValueAxisZoomReal:function(a,b){var c=a.relativeStart,d=a.relativeEnd;if(c>d)var e=c,c=d,d=e;this.relativeZoomValueAxes(b,c,d);this.updateAfterValueZoom()},
updateAfterValueZoom:function(){this.zoomAxesAndGraphs();this.zoomScrollbar()},relativeZoomValueAxes:function(a,b,c){b=e.fitToBounds(b,0,1);c=e.fitToBounds(c,0,1);if(b>c){var d=b;b=c;c=d}var d=1/this.maxZoomFactor,g=e.getDecimals(d)+4;c-b<d&&(c=b+(c-b)/2,b=c-d/2,c+=d/2,1<c&&(b-=c-1,c=1));b=e.roundTo(b,g);c=e.roundTo(c,g);d=!1;if(a){for(g=0;g<a.length;g++){var h=a[g].zoomToRelativeValues(b,c,!0);h&&(d=h)}this.showZB()}return d},addChartCursor:function(a){e.callMethod("destroy",[this.chartCursor]);
a&&(this.listenTo(a,"moved",this.handleCursorMove),this.listenTo(a,"zoomed",this.handleCursorZoom),this.listenTo(a,"zoomStarted",this.handleCursorZoomStarted),this.listenTo(a,"panning",this.handleCursorPanning),this.listenTo(a,"onHideCursor",this.handleCursorHide));this.chartCursor=a},handleCursorChange:function(){},handleCursorMove:function(a){var b,c=this.valueAxes;for(b=0;b<c.length;b++)if(!a.panning){var d=c[b];d&&d.showBalloon&&d.showBalloon(a.x,a.y)}},handleCursorZoom:function(a){if(this.skipZoomed)this.skipZoomed=
!1;else{var b=this.startX0,c=this.endX0,d=this.endY0,e=this.startY0,h=a.startX,f=a.endX,k=a.startY,m=a.endY;this.startX0=this.endX0=this.startY0=this.endY0=NaN;this.handleCursorZoomReal(b+h*(c-b),b+f*(c-b),e+k*(d-e),e+m*(d-e),a)}},handleCursorHide:function(){var a,b=this.valueAxes;for(a=0;a<b.length;a++)b[a].hideBalloon();b=this.graphs;for(a=0;a<b.length;a++)b[a].hideBalloonReal()}})})();(function(){var e=window.AmCharts;e.AmXYChart=e.Class({inherits:e.AmRectangularChart,construct:function(a){this.type="xy";e.AmXYChart.base.construct.call(this,a);this.cname="AmXYChart";this.theme=a;this.createEvents("zoomed");e.applyTheme(this,a,this.cname)},initChart:function(){e.AmXYChart.base.initChart.call(this);this.dataChanged&&this.updateData();this.drawChart();!this.marginsUpdated&&this.autoMargins&&(this.marginsUpdated=!0,this.measureMargins());var a=this.marginLeftReal,b=this.marginTopReal,
c=this.plotAreaWidth,d=this.plotAreaHeight;this.graphsSet.clipRect(a,b,c,d);this.bulletSet.clipRect(a,b,c,d);this.trendLinesSet.clipRect(a,b,c,d);this.drawGraphs=!0;this.showZB()},prepareForExport:function(){var a=this.bulletSet;a.clipPath&&this.container.remove(a.clipPath)},createValueAxes:function(){var a=[],b=[];this.xAxes=a;this.yAxes=b;var c=this.valueAxes,d,g;for(g=0;g<c.length;g++){d=c[g];var h=d.position;if("top"==h||"bottom"==h)d.rotate=!0;d.setOrientation(d.rotate);h=d.orientation;"V"==
h&&b.push(d);"H"==h&&a.push(d)}0===b.length&&(d=new e.ValueAxis(this.theme),d.rotate=!1,d.setOrientation(!1),c.push(d),b.push(d));0===a.length&&(d=new e.ValueAxis(this.theme),d.rotate=!0,d.setOrientation(!0),c.push(d),a.push(d));for(g=0;g<c.length;g++)this.processValueAxis(c[g],g);a=this.graphs;for(g=0;g<a.length;g++)this.processGraph(a[g],g)},drawChart:function(){e.AmXYChart.base.drawChart.call(this);var a=this.chartData;this.legend&&(this.legend.valueText=void 0);if(0<this.realWidth&&0<this.realHeight){e.ifArray(a)?
(this.chartScrollbar&&this.updateScrollbars(),this.zoomChart()):this.cleanChart();if(a=this.scrollbarH)this.hideXScrollbar?(a&&a.destroy(),this.scrollbarH=null):a.draw();if(a=this.scrollbarV)this.hideYScrollbar?(a.destroy(),this.scrollbarV=null):a.draw();this.zoomScrollbar()}this.autoMargins&&!this.marginsUpdated||this.dispDUpd()},cleanChart:function(){e.callMethod("destroy",[this.valueAxes,this.graphs,this.scrollbarV,this.scrollbarH,this.chartCursor])},zoomChart:function(){this.zoomObjects(this.valueAxes);
this.zoomObjects(this.graphs);this.zoomTrendLines();this.prevPlotAreaWidth=this.plotAreaWidth;this.prevPlotAreaHeight=this.plotAreaHeight},validateData:function(){if(this.zoomOutOnDataUpdate)for(var a=this.valueAxes,b=0;b<a.length;b++)a[b].minZoom=NaN,a[b].maxZoom=NaN;e.AmXYChart.base.validateData.call(this)},zoomObjects:function(a){var b=a.length,c,d;for(c=0;c<b;c++)d=a[c],d.zoom(0,this.chartData.length-1)},updateData:function(){this.parseData();var a=this.chartData,b=a.length-1,c=this.graphs,d=
this.dataProvider,e=-Infinity,h=Infinity,f,k;if(d){for(f=0;f<c.length;f++)if(k=c[f],k.data=a,k.zoom(0,b),k=k.valueField){var m;for(m=0;m<d.length;m++){var l=Number(d[m][k]);null!==l&&(l>e&&(e=l),l<h&&(h=l))}}isNaN(this.minValue)||(h=this.minValue);isNaN(this.maxValue)||(e=this.maxValue);for(f=0;f<c.length;f++)k=c[f],k.maxValue=e,k.minValue=h;if(a=this.chartCursor)a.type="crosshair",a.valueBalloonsEnabled=!1;this.dataChanged=!1;this.dispatchDataUpdated=!0}},processValueAxis:function(a){a.chart=this;
a.minMaxField="H"==a.orientation?"x":"y";a.min=NaN;a.max=NaN},processGraph:function(a){e.isString(a.xAxis)&&(a.xAxis=this.getValueAxisById(a.xAxis));e.isString(a.yAxis)&&(a.yAxis=this.getValueAxisById(a.yAxis));a.xAxis||(a.xAxis=this.xAxes[0]);a.yAxis||(a.yAxis=this.yAxes[0]);a.valueAxis=a.yAxis},parseData:function(){e.AmXYChart.base.parseData.call(this);this.chartData=[];var a=this.dataProvider,b=this.valueAxes,c=this.graphs,d;if(a)for(d=0;d<a.length;d++){var g={axes:{},x:{},y:{}},h=this.dataDateFormat,
f=a[d],k;for(k=0;k<b.length;k++){var m=b[k].id;g.axes[m]={};g.axes[m].graphs={};var l;for(l=0;l<c.length;l++){var p=c[l],q=p.id;if(p.xAxis.id==m||p.yAxis.id==m){var r={};r.serialDataItem=g;r.index=d;var t={},n=f[p.valueField];null!==n&&(n=Number(n),isNaN(n)||(t.value=n));n=f[p.xField];null!==n&&("date"==p.xAxis.type&&(n=e.getDate(f[p.xField],h).getTime()),n=Number(n),isNaN(n)||(t.x=n));n=f[p.yField];null!==n&&("date"==p.yAxis.type&&(n=e.getDate(f[p.yField],h).getTime()),n=Number(n),isNaN(n)||(t.y=
n));n=f[p.errorField];null!==n&&(n=Number(n),isNaN(n)||(t.error=n));r.values=t;this.processFields(p,r,f);r.serialDataItem=g;r.graph=p;g.axes[m].graphs[q]=r}}}this.chartData[d]=g}this.start=0;this.end=this.chartData.length-1},formatString:function(a,b,c){var d=b.graph,g=d.numberFormatter;g||(g=this.nf);var h,f;"date"==b.graph.xAxis.type&&(h=e.formatDate(new Date(b.values.x),d.dateFormat,this),f=RegExp("\\[\\[x\\]\\]","g"),a=a.replace(f,h));"date"==b.graph.yAxis.type&&(h=e.formatDate(new Date(b.values.y),
d.dateFormat,this),f=RegExp("\\[\\[y\\]\\]","g"),a=a.replace(f,h));a=e.formatValue(a,b.values,["value","x","y"],g);-1!=a.indexOf("[[")&&(a=e.formatDataContextValue(a,b.dataContext));return a=e.AmXYChart.base.formatString.call(this,a,b,c)},addChartScrollbar:function(a){e.callMethod("destroy",[this.chartScrollbar,this.scrollbarH,this.scrollbarV]);if(a){this.chartScrollbar=a;this.scrollbarHeight=a.scrollbarHeight;var b="backgroundColor backgroundAlpha selectedBackgroundColor selectedBackgroundAlpha scrollDuration resizeEnabled hideResizeGrips scrollbarHeight updateOnReleaseOnly".split(" ");
if(!this.hideYScrollbar){var c=new e.ChartScrollbar(this.theme);c.skipEvent=!0;c.chart=this;this.listenTo(c,"zoomed",this.handleScrollbarValueZoom);e.copyProperties(a,c,b);c.rotate=!0;this.scrollbarV=c}this.hideXScrollbar||(c=new e.ChartScrollbar(this.theme),c.skipEvent=!0,c.chart=this,this.listenTo(c,"zoomed",this.handleScrollbarValueZoom),e.copyProperties(a,c,b),c.rotate=!1,this.scrollbarH=c)}},updateTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b],c=e.processObject(c,
e.TrendLine,this.theme);a[b]=c;c.chart=this;var d=c.valueAxis;e.isString(d)&&(c.valueAxis=this.getValueAxisById(d));d=c.valueAxisX;e.isString(d)&&(c.valueAxisX=this.getValueAxisById(d));c.id||(c.id="trendLineAuto"+b+"_"+(new Date).getTime());c.valueAxis||(c.valueAxis=this.yAxes[0]);c.valueAxisX||(c.valueAxisX=this.xAxes[0])}},updateMargins:function(){e.AmXYChart.base.updateMargins.call(this);var a=this.scrollbarV;a&&(this.getScrollbarPosition(a,!0,this.yAxes[0].position),this.adjustMargins(a,!0));
if(a=this.scrollbarH)this.getScrollbarPosition(a,!1,this.xAxes[0].position),this.adjustMargins(a,!1)},updateScrollbars:function(){e.AmXYChart.base.updateScrollbars.call(this);var a=this.scrollbarV;a&&(this.updateChartScrollbar(a,!0),a.valueAxes=this.yAxes,a.gridAxis||(a.gridAxis=this.yAxes[0]));if(a=this.scrollbarH)this.updateChartScrollbar(a,!1),a.valueAxes=this.xAxes,a.gridAxis||(a.gridAxis=this.xAxes[0])},removeChartScrollbar:function(){e.callMethod("destroy",[this.scrollbarH,this.scrollbarV]);
this.scrollbarV=this.scrollbarH=null},handleReleaseOutside:function(a){e.AmXYChart.base.handleReleaseOutside.call(this,a);e.callMethod("handleReleaseOutside",[this.scrollbarH,this.scrollbarV])},update:function(){e.AmXYChart.base.update.call(this);this.scrollbarH&&this.scrollbarH.update&&this.scrollbarH.update();this.scrollbarV&&this.scrollbarV.update&&this.scrollbarV.update()},zoomScrollbar:function(){this.zoomValueScrollbar(this.scrollbarV);this.zoomValueScrollbar(this.scrollbarH)},handleCursorZoomReal:function(a,
b,c,d){isNaN(a)||isNaN(b)||this.relativeZoomValueAxes(this.xAxes,a,b);isNaN(c)||isNaN(d)||this.relativeZoomValueAxes(this.yAxes,c,d);this.updateAfterValueZoom()},handleCursorZoomStarted:function(){if(this.xAxes){var a=this.xAxes[0];this.startX0=a.relativeStart;this.endX0=a.relativeEnd;a.reversed&&(this.startX0=1-a.relativeEnd,this.endX0=1-a.relativeStart)}this.yAxes&&(a=this.yAxes[0],this.startY0=a.relativeStart,this.endY0=a.relativeEnd,a.reversed&&(this.startY0=1-a.relativeEnd,this.endY0=1-a.relativeStart))},
updateChartCursor:function(){e.AmXYChart.base.updateChartCursor.call(this);var a=this.chartCursor;if(a){a.valueLineEnabled=!0;a.categoryLineAxis||(a.categoryLineAxis=this.xAxes[0]);var b=this.valueAxis;if(a.valueLineBalloonEnabled){var c=a.categoryBalloonAlpha,d=a.categoryBalloonColor,g=a.color;void 0===d&&(d=a.cursorColor);for(var h=0;h<this.valueAxes.length;h++){var b=this.valueAxes[h],f=b.balloon;f||(f={});f=e.extend(f,this.balloon,!0);f.fillColor=d;f.balloonColor=d;f.fillAlpha=c;f.borderColor=
d;f.color=g;b.balloon=f}}else for(c=0;c<this.valueAxes.length;c++)b=this.valueAxes[c],b.balloon&&(b.balloon=null);a.zoomable&&(this.hideYScrollbar||(a.vZoomEnabled=!0),this.hideXScrollbar||(a.hZoomEnabled=!0))}},handleCursorPanning:function(a){var b=a.deltaX,c=a.delta2X,d;isNaN(c)&&(c=b,d=!0);var g=this.endX0,h=this.startX0,f=g-h,c=g-f*c,g=f;d||(g=0);b=e.fitToBounds(h-f*b,0,1-g);c=e.fitToBounds(c,g,1);this.relativeZoomValueAxes(this.xAxes,b,c);f=a.deltaY;a=a.delta2Y;isNaN(a)&&(a=f,d=!0);c=this.endY0;
b=this.startY0;h=c-b;f=c+h*f;c=h;d||(c=0);d=e.fitToBounds(b+h*a,0,1-c);f=e.fitToBounds(f,c,1);this.relativeZoomValueAxes(this.yAxes,d,f);this.updateAfterValueZoom()},handleValueAxisZoom:function(a){this.handleValueAxisZoomReal(a,"V"==a.valueAxis.orientation?this.yAxes:this.xAxes)},showZB:function(){var a,b=this.valueAxes;if(b)for(var c=0;c<b.length;c++){var d=b[c];0!==d.relativeStart&&(a=!0);1!=d.relativeEnd&&(a=!0)}e.AmXYChart.base.showZB.call(this,a)}})})();
|
/*! asynquence-contrib
v0.13.0 (c) Kyle Simpson
MIT License: http://getify.mit-license.org
*/
(function UMD(dependency,definition){
if (typeof module !== "undefined" && module.exports) {
// make dependency injection wrapper first
module.exports = function $$inject$dependency(dep) {
// only try to `require(..)` if dependency is a string module path
if (typeof dep == "string") {
try { dep = require(dep); }
catch (err) {
// dependency not yet fulfilled, so just return
// dependency injection wrapper again
return $$inject$dependency;
}
}
return definition(dep);
};
// if possible, immediately try to resolve wrapper
// (with peer dependency)
if (typeof dependency == "string") {
module.exports = module.exports( require("path").join("..",dependency) );
}
}
else if (typeof define == "function" && define.amd) { define([dependency],definition); }
else { definition(dependency); }
})(this.ASQ || "asynquence",function DEF(ASQ){
"use strict";
var ARRAY_SLICE = Array.prototype.slice,
ø = Object.create(null),
brand = "__ASQ__",
schedule = ASQ.__schedule,
tapSequence = ASQ.__tapSequence
;
function wrapGate(api,fns,success,failure,reset) {
fns = fns.map(function $$map(v,idx){
var def;
// tap any directly-provided sequences immediately
if (ASQ.isSequence(v)) {
def = { seq: v };
tapSequence(def);
return function $$fn(next) {
def.seq.val(function $$val(){
success(next,idx,ARRAY_SLICE.call(arguments));
})
.or(function $$or(){
failure(next,idx,ARRAY_SLICE.call(arguments));
});
};
}
else {
return function $$fn(next) {
var args = ARRAY_SLICE.call(arguments);
args[0] = function $$next() {
success(next,idx,ARRAY_SLICE.call(arguments));
};
args[0].fail = function $$fail() {
failure(next,idx,ARRAY_SLICE.call(arguments));
};
args[0].abort = function $$abort() {
reset();
};
args[0].errfcb = function $$errfcb(err) {
if (err) {
failure(next,idx,[err]);
}
else {
success(next,idx,ARRAY_SLICE.call(arguments,1));
}
};
v.apply(ø,args);
};
}
});
api.then(function $$then(){
var args = ARRAY_SLICE.call(arguments);
fns.forEach(function $$each(fn){
fn.apply(ø,args);
});
});
}
function isPromise(v) {
var val_type = typeof v;
return (
v !== null &&
(
val_type == "object" ||
val_type == "function"
) &&
!ASQ.isSequence(v) &&
// NOTE: `then` duck-typing of promises is stupid
typeof v.then == "function"
);
}
// "after"
ASQ.extend("after",function $$extend(api,internals){
return function $$after(num) {
var orig_args = arguments.length > 1 ?
ARRAY_SLICE.call(arguments,1) :
void 0
;
num = +num || 0;
api.then(function $$then(done){
var args = orig_args || ARRAY_SLICE.call(arguments,1);
setTimeout(function $$set$timeout(){
done.apply(ø,args);
},num);
});
return api;
};
});
ASQ.after = function $$after() {
return ASQ().after.apply(ø,arguments);
};
// "any"
ASQ.extend("any",function $$extend(api,internals){
return function $$any() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments);
api.then(function $$then(done){
function reset() {
finished = true;
error_messages.length = 0;
success_messages.length = 0;
}
function complete(trigger) {
if (success_messages.length > 0) {
// any successful segment's message(s) sent
// to main sequence to proceed as success
success_messages.length = fns.length;
trigger.apply(ø,success_messages);
}
else {
// send errors into main sequence
error_messages.length = fns.length;
trigger.fail.apply(ø,error_messages);
}
reset();
}
function success(trigger,idx,args) {
if (!finished) {
completed++;
success_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
// all segments complete?
if (completed === fns.length) {
finished = true;
complete(trigger);
}
}
}
function failure(trigger,idx,args) {
if (!finished &&
!(idx in error_messages)
) {
completed++;
error_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
}
// all segments complete?
if (!finished &&
completed === fns.length
) {
finished = true;
complete(trigger);
}
}
var completed = 0, error_messages = [], finished = false,
success_messages = [],
sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1))
;
wrapGate(sq,fns,success,failure,reset);
sq.pipe(done);
});
return api;
};
});
// "errfcb"
ASQ.extend("errfcb",function $$extend(api,internals){
return function $$errfcb() {
// create a fake sequence to extract the callbacks
var sq = {
val: function $$then(cb){ sq.val_cb = cb; return sq; },
or: function $$or(cb){ sq.or_cb = cb; return sq; }
};
// trick `seq(..)`s checks for a sequence
sq[brand] = true;
// immediately register our fake sequence on the
// main sequence
api.seq(sq);
// provide the "error-first" callback
return function $$errorfirst$callback(err) {
if (err) {
sq.or_cb(err);
}
else {
sq.val_cb.apply(ø,ARRAY_SLICE.call(arguments,1));
}
};
};
});
// "failAfter"
ASQ.extend("failAfter",function $$extend(api,internals){
return function $$failAfter(num) {
var args = arguments.length > 1 ?
ARRAY_SLICE.call(arguments,1) :
void 0
;
num = +num || 0;
api.then(function $$then(done){
setTimeout(function $$set$timeout(){
done.fail.apply(ø,args);
},num);
});
return api;
};
});
ASQ.failAfter = function $$fail$after() {
return ASQ().failAfter.apply(ø,arguments);
};
// "first"
ASQ.extend("first",function $$extend(api,internals){
return function $$first() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments);
api.then(function $$then(done){
function reset() {
error_messages.length = 0;
}
function success(trigger,idx,args) {
if (!finished) {
finished = true;
// first successful segment triggers
// main sequence to proceed as success
trigger(
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
);
reset();
}
}
function failure(trigger,idx,args) {
if (!finished &&
!(idx in error_messages)
) {
completed++;
error_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
// all segments complete without success?
if (completed === fns.length) {
finished = true;
// send errors into main sequence
error_messages.length = fns.length;
trigger.fail.apply(ø,error_messages);
reset();
}
}
}
var completed = 0, error_messages = [], finished = false,
sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1))
;
wrapGate(sq,fns,success,failure,reset);
sq.pipe(done);
});
return api;
};
});
// "go-style CSP"
"use strict";
(function IIFE() {
// filter out already-resolved queue entries
function filterResolved(queue) {
return queue.filter(function $$filter(entry) {
return !entry.resolved;
});
}
function closeQueue(queue, finalValue) {
queue.forEach(function $$each(iter) {
if (!iter.resolved) {
iter.next();
iter.next(finalValue);
}
});
queue.length = 0;
}
function channel(bufSize) {
var ch = {
close: function $$close() {
ch.closed = true;
closeQueue(ch.put_queue, false);
closeQueue(ch.take_queue, ASQ.csp.CLOSED);
},
closed: false,
messages: [],
put_queue: [],
take_queue: [],
buffer_size: +bufSize || 0
};
return ch;
}
function unblock(iter) {
if (iter && !iter.resolved) {
iter.next(iter.next().value);
}
}
function put(channel, value) {
var ret;
if (channel.closed) {
return false;
}
// remove already-resolved entries
channel.put_queue = filterResolved(channel.put_queue);
channel.take_queue = filterResolved(channel.take_queue);
// immediate put?
if (channel.messages.length < channel.buffer_size) {
channel.messages.push(value);
unblock(channel.take_queue.shift());
return true;
}
// queued put
else {
channel.put_queue.push(
// make a notifiable iterable for 'put' blocking
ASQ.iterable().then(function $$then() {
if (!channel.closed) {
channel.messages.push(value);
return true;
} else {
return false;
}
}));
// wrap a sequence/promise around the iterable
ret = ASQ(channel.put_queue[channel.put_queue.length - 1]);
// take waiting on this queued put?
if (channel.take_queue.length > 0) {
unblock(channel.put_queue.shift());
unblock(channel.take_queue.shift());
}
return ret;
}
}
function putAsync(channel, value, cb) {
var ret = ASQ(put(channel, value));
if (cb && typeof cb == "function") {
ret.val(cb);
} else {
return ret;
}
}
function take(channel) {
var ret;
try {
ret = takem(channel);
} catch (err) {
ret = err;
}
if (ASQ.isSequence(ret)) {
ret.pCatch(function $$pcatch(err) {
return err;
});
}
return ret;
}
function takeAsync(channel, cb) {
var ret = ASQ(take(channel));
if (cb && typeof cb == "function") {
ret.val(cb);
} else {
return ret;
}
}
function takem(channel) {
var msg;
if (channel.closed) {
return ASQ.csp.CLOSED;
}
// remove already-resolved entries
channel.put_queue = filterResolved(channel.put_queue);
channel.take_queue = filterResolved(channel.take_queue);
// immediate take?
if (channel.messages.length > 0) {
msg = channel.messages.shift();
unblock(channel.put_queue.shift());
if (msg instanceof Error) {
throw msg;
}
return msg;
}
// queued take
else {
channel.take_queue.push(
// make a notifiable iterable for 'take' blocking
ASQ.iterable().then(function $$then() {
if (!channel.closed) {
var v = channel.messages.shift();
if (v instanceof Error) {
throw v;
}
return v;
} else {
return ASQ.csp.CLOSED;
}
}));
// wrap a sequence/promise around the iterable
msg = ASQ(channel.take_queue[channel.take_queue.length - 1]);
// put waiting on this take?
if (channel.put_queue.length > 0) {
unblock(channel.put_queue.shift());
unblock(channel.take_queue.shift());
}
return msg;
}
}
function takemAsync(channel, cb) {
var ret = ASQ(takem(channel));
if (cb && typeof cb == "function") {
ret.pThen(cb, cb);
} else {
return ret.val(function $$val(v) {
if (v instanceof Error) {
throw v;
}
return v;
});
}
}
function alts(actions) {
var closed,
open,
handlers,
i,
isq,
ret,
resolved = false;
// used `alts(..)` incorrectly?
if (!Array.isArray(actions) || actions.length == 0) {
throw Error("Invalid usage");
}
closed = [];
open = [];
handlers = [];
// separate actions by open/closed channel status
actions.forEach(function $$each(action) {
var channel = Array.isArray(action) ? action[0] : action;
// remove already-resolved entries
channel.put_queue = filterResolved(channel.put_queue);
channel.take_queue = filterResolved(channel.take_queue);
if (channel.closed) {
closed.push(channel);
} else {
open.push(action);
}
});
// if no channels are still open, we're done
if (open.length == 0) {
return { value: ASQ.csp.CLOSED, channel: closed };
}
// can any channel action be executed immediately?
for (i = 0; i < open.length; i++) {
// put action
if (Array.isArray(open[i])) {
// immediate put?
if (open[i][0].messages.length < open[i][0].buffer_size) {
return { value: put(open[i][0], open[i][1]), channel: open[i][0] };
}
}
// immediate take?
else if (open[i].messages.length > 0) {
return { value: take(open[i]), channel: open[i] };
}
}
isq = ASQ.iterable();
var ret = ASQ(isq);
// setup channel action handlers
for (i = 0; i < open.length; i++) {
(function iteration(action, channel, value) {
// put action?
if (Array.isArray(action)) {
channel = action[0];
value = action[1];
// define put handler
handlers.push(ASQ.iterable().then(function $$then() {
resolved = true;
// mark all handlers across this `alts(..)` as resolved now
handlers = handlers.filter(function $$filter(handler) {
return !(handler.resolved = true);
});
// channel still open?
if (!channel.closed) {
channel.messages.push(value);
isq.next({ value: true, channel: channel });
}
// channel already closed?
else {
isq.next({ value: false, channel: channel });
}
}));
// queue up put handler
channel.put_queue.push(handlers[handlers.length - 1]);
// take waiting on this queued put?
if (channel.take_queue.length > 0) {
schedule(function handleUnblocking() {
if (!resolved) {
unblock(channel.put_queue.shift());
unblock(channel.take_queue.shift());
}
}, 0);
}
}
// take action?
else {
channel = action;
// define take handler
handlers.push(ASQ.iterable().then(function $$then() {
resolved = true;
// mark all handlers across this `alts(..)` as resolved now
handlers = handlers.filter(function $$filter(handler) {
return !(handler.resolved = true);
});
// channel still open?
if (!channel.closed) {
isq.next({ value: channel.messages.shift(), channel: channel });
}
// channel already closed?
else {
isq.next({ value: ASQ.csp.CLOSED, channel: channel });
}
}));
// queue up take handler
channel.take_queue.push(handlers[handlers.length - 1]);
// put waiting on this queued take?
if (channel.put_queue.length > 0) {
schedule(function handleUnblocking() {
if (!resolved) {
unblock(channel.put_queue.shift());
unblock(channel.take_queue.shift());
}
});
}
}
})(open[i]);
}
return ret;
}
function altsAsync(chans, cb) {
var ret = ASQ(alts(channel));
if (cb && typeof cb == "function") {
ret.pThen(cb, cb);
} else {
return ret;
}
}
function timeout(delay) {
var ch = channel();
setTimeout(ch.close, delay);
return ch;
}
function go(gen, args) {
// goroutine arguments passed?
if (arguments.length > 1) {
if (!args || !Array.isArray(args)) {
args = [args];
}
} else {
args = [];
}
return regeneratorRuntime.mark(function $$go(token) {
var unblock, ret, msg, err, type, done, it;
return regeneratorRuntime.wrap(function $$go$(context$3$0) {
while (1) switch (context$3$0.prev = context$3$0.next) {
case 0:
unblock = function unblock() {
if (token.block && !token.block.marked) {
token.block.marked = true;
token.block.next();
}
};
done = false;
// keep track of how many goroutines are running
// so we can infer when we're done go'ing
token.go_count = (token.go_count || 0) + 1;
// need to initialize a set of goroutines?
if (token.go_count === 1) {
// create a default channel for these goroutines
token.channel = channel();
token.channel.messages = token.messages;
token.channel.go = function $$go() {
// unblock the goroutine handling for these
// new goroutine(s)?
unblock();
// add the goroutine(s) to the handling queue
token.add(go.apply(ø, arguments));
};
// starting out with initial channel messages?
if (token.channel.messages.length > 0) {
// fake back-pressure blocking for each
token.channel.put_queue = token.channel.messages.map(function $$map() {
// make a notifiable iterable for 'put' blocking
return ASQ.iterable().then(function $$then() {
unblock(token.channel.take_queue.shift());
return !token.channel.closed;
});
});
}
}
// initialize the generator
it = gen.apply(ø, [token.channel].concat(args));
(function iterate() {
function next() {
// keep going with next step in goroutine?
if (!done) {
iterate();
}
// unblock overall goroutine handling to
// continue with other goroutines
else {
unblock();
}
}
// has a resumption value been achieved yet?
if (!ret) {
// try to resume the goroutine
try {
// resume with injected exception?
if (err) {
ret = it["throw"](err);
err = null;
}
// resume normally
else {
ret = it.next(msg);
}
}
// resumption failed, so bail
catch (e) {
done = true;
err = e;
msg = null;
unblock();
return;
}
// keep track of the result of the resumption
done = ret.done;
ret = ret.value;
type = typeof ret;
// if this goroutine is complete, unblock the
// overall goroutine handling
if (done) {
unblock();
}
// received a thenable/promise back?
if (isPromise(ret)) {
ret = ASQ().promise(ret);
}
// wait for the value?
if (ASQ.isSequence(ret)) {
ret.val(function $$val() {
ret = null;
msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0];
next();
}).or(function $$or() {
ret = null;
msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0];
if (msg instanceof Error) {
err = msg;
msg = null;
}
next();
});
}
// immediate value, prepare it to go right back in
else {
msg = ret;
ret = null;
next();
}
}
})();
// keep this goroutine alive until completion
case 6:
if (done) {
context$3$0.next = 15;
break;
}
context$3$0.next = 9;
return token;
case 9:
if (!(!done && !token.block)) {
context$3$0.next = 13;
break;
}
context$3$0.next = 12;
return token.block = ASQ.iterable();
case 12:
token.block = false;
case 13:
context$3$0.next = 6;
break;
case 15:
// this goroutine is done now
token.go_count--;
// all goroutines done?
if (token.go_count === 0) {
// any lingering blocking need to be cleaned up?
unblock();
// capture any untaken messages
msg = ASQ.messages.apply(ø, token.messages);
// need to implicitly force-close channel?
if (token.channel && !token.channel.closed) {
token.channel.closed = true;
token.channel.put_queue.length = token.channel.take_queue.length = 0;
token.channel.close = token.channel.go = token.channel.messages = null;
}
token.channel = null;
}
// make sure leftover error or message are
// passed along
if (!err) {
context$3$0.next = 21;
break;
}
throw err;
case 21:
if (!(token.go_count === 0)) {
context$3$0.next = 25;
break;
}
return context$3$0.abrupt("return", msg);
case 25:
return context$3$0.abrupt("return", token);
case 26:
case "end":
return context$3$0.stop();
}
}, $$go, this);
});
}
ASQ.csp = {
chan: channel,
put: put,
putAsync: putAsync,
take: take,
takeAsync: takeAsync,
takem: takem,
takemAsync: takemAsync,
alts: alts,
altsAsync: altsAsync,
timeout: timeout,
go: go,
CLOSED: {}
};
})();
// unblock the overall goroutine handling
// transfer control to another goroutine
// need to block overall goroutine handling
// while idle?
// wait here while idle// "ASQ.iterable()"
"use strict";
(function IIFE() {
var template;
ASQ.iterable = function $$iterable() {
function throwSequenceErrors() {
throw sequence_errors.length === 1 ? sequence_errors[0] : sequence_errors;
}
function notifyErrors() {
var fn;
seq_tick = null;
if (seq_error) {
if (or_queue.length === 0 && !error_reported) {
error_reported = true;
throwSequenceErrors();
}
while (or_queue.length > 0) {
error_reported = true;
fn = or_queue.shift();
try {
fn.apply(ø, sequence_errors);
} catch (err) {
if (checkBranding(err)) {
sequence_errors = sequence_errors.concat(err);
} else {
sequence_errors.push(err);
}
if (or_queue.length === 0) {
throwSequenceErrors();
}
}
}
}
}
function val() {
if (seq_error || seq_aborted || arguments.length === 0) {
return sequence_api;
}
var args = ARRAY_SLICE.call(arguments).map(function mapper(arg) {
if (typeof arg != "function") return function $$val() {
return arg;
};else return arg;
});
val_queue.push.apply(val_queue, args);
return sequence_api;
}
function or() {
if (seq_aborted || arguments.length === 0) {
return sequence_api;
}
or_queue.push.apply(or_queue, arguments);
if (!seq_tick) {
seq_tick = schedule(notifyErrors);
}
return sequence_api;
}
function pipe() {
if (seq_aborted || arguments.length === 0) {
return sequence_api;
}
ARRAY_SLICE.call(arguments).forEach(function $$each(fn) {
val(fn).or(fn.fail);
});
return sequence_api;
}
function next() {
if (seq_error || seq_aborted || val_queue.length === 0) {
if (val_queue.length > 0) {
$throw$("Sequence cannot be iterated");
}
return { done: true };
}
try {
return { value: val_queue.shift().apply(ø, arguments) };
} catch (err) {
if (ASQ.isMessageWrapper(err)) {
$throw$.apply(ø, err);
} else {
$throw$(err);
}
return {};
}
}
function $throw$() {
if (seq_error || seq_aborted) {
return sequence_api;
}
sequence_errors.push.apply(sequence_errors, arguments);
seq_error = true;
if (!seq_tick) {
seq_tick = schedule(notifyErrors);
}
return sequence_api;
}
function $return$(val) {
if (seq_error || seq_aborted) {
val = void 0;
}
abort();
return { done: true, value: val };
}
function abort() {
if (seq_error || seq_aborted) {
return;
}
seq_aborted = true;
clearTimeout(seq_tick);
seq_tick = null;
val_queue.length = or_queue.length = sequence_errors.length = 0;
}
function duplicate() {
var isq;
template = {
val_queue: val_queue.slice(),
or_queue: or_queue.slice()
};
isq = ASQ.iterable();
template = null;
return isq;
}
// opt-out of global error reporting for this sequence
function defer() {
or_queue.push(function $$ignored() {});
return sequence_api;
}
// ***********************************************
// Object branding utilities
// ***********************************************
function brandIt(obj) {
Object.defineProperty(obj, brand, {
enumerable: false,
value: true
});
return obj;
}
var sequence_api,
seq_error = false,
error_reported = false,
seq_aborted = false,
seq_tick,
val_queue = [],
or_queue = [],
sequence_errors = [];
// ***********************************************
// Setup the ASQ.iterable() public API
// ***********************************************
sequence_api = brandIt({
val: val,
then: val,
or: or,
pipe: pipe,
next: next,
"throw": $throw$,
"return": $return$,
abort: abort,
duplicate: duplicate,
defer: defer
});
// useful for ES6 `for..of` loops,
// add `@@iterator` to simply hand back
// our iterable sequence itself!
sequence_api[typeof Symbol == "function" && Symbol.iterator || "@@iterator"] = function $$iter() {
return sequence_api;
};
// templating the iterable-sequence setup?
if (template) {
val_queue = template.val_queue.slice(0);
or_queue = template.or_queue.slice(0);
}
// treat ASQ.iterable() constructor parameters as having been
// passed to `val()`
sequence_api.val.apply(ø, arguments);
return sequence_api;
};
})();// "last"
ASQ.extend("last",function $$extend(api,internals){
return function $$last() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments);
api.then(function $$then(done){
function reset() {
finished = true;
error_messages.length = 0;
success_messages = null;
}
function complete(trigger) {
if (success_messages != null) {
// last successful segment's message(s) sent
// to main sequence to proceed as success
trigger(
success_messages.length > 1 ?
ASQ.messages.apply(ø,success_messages) :
success_messages[0]
);
}
else {
// send errors into main sequence
error_messages.length = fns.length;
trigger.fail.apply(ø,error_messages);
}
reset();
}
function success(trigger,idx,args) {
if (!finished) {
completed++;
success_messages = args;
// all segments complete?
if (completed === fns.length) {
finished = true;
complete(trigger);
}
}
}
function failure(trigger,idx,args) {
if (!finished &&
!(idx in error_messages)
) {
completed++;
error_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
}
// all segments complete?
if (!finished &&
completed === fns.length
) {
finished = true;
complete(trigger);
}
}
var completed = 0, error_messages = [], finished = false,
sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)),
success_messages
;
wrapGate(sq,fns,success,failure,reset);
sq.pipe(done);
});
return api;
};
});
// "map"
ASQ.extend("map",function $$extend(api,internals){
return function $$map(pArr,pEach) {
if (internals("seq_error") || internals("seq_aborted")) {
return api;
}
api.seq(function $$seq(){
var tmp, args = ARRAY_SLICE.call(arguments),
arr = pArr, each = pEach;
// if missing `map(..)` args, use value-messages (if any)
if (!each) each = args.shift();
if (!arr) arr = args.shift();
// if arg types in reverse order (each,arr), swap
if (typeof arr === "function" && Array.isArray(each)) {
tmp = arr;
arr = each;
each = tmp;
}
return ASQ.apply(ø,args)
.gate.apply(ø,arr.map(function $$map(item){
return function $$segment(){
each.apply(ø,[item].concat(ARRAY_SLICE.call(arguments)));
};
}));
})
.val(function $$val(){
// collect all gate segment output into one value-message
// Note: return a normal array here, not a message wrapper!
return ARRAY_SLICE.call(arguments);
});
return api;
};
});
// "none"
ASQ.extend("none",function $$extend(api,internals){
return function $$none() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments);
api.then(function $$then(done){
function reset() {
finished = true;
error_messages.length = 0;
success_messages.length = 0;
}
function complete(trigger) {
if (success_messages.length > 0) {
// any successful segment's message(s) sent
// to main sequence to proceed as **error**
success_messages.length = fns.length;
trigger.fail.apply(ø,success_messages);
}
else {
// send errors as **success** to main sequence
error_messages.length = fns.length;
trigger.apply(ø,error_messages);
}
reset();
}
function success(trigger,idx,args) {
if (!finished) {
completed++;
success_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
// all segments complete?
if (completed === fns.length) {
finished = true;
complete(trigger);
}
}
}
function failure(trigger,idx,args) {
if (!finished &&
!(idx in error_messages)
) {
completed++;
error_messages[idx] =
args.length > 1 ?
ASQ.messages.apply(ø,args) :
args[0]
;
}
// all segments complete?
if (!finished &&
completed === fns.length
) {
finished = true;
complete(trigger);
}
}
var completed = 0, error_messages = [], finished = false,
sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)),
success_messages = []
;
wrapGate(sq,fns,success,failure,reset);
sq.pipe(done);
});
return api;
};
});
// "pThen"
ASQ.extend("pThen",function $$extend(api,internals){
return function $$pthen(success,failure) {
if (internals("seq_aborted")) {
return api;
}
var ignore_success_handler = false, ignore_failure_handler = false;
if (typeof success === "function") {
api.then(function $$then(done){
if (!ignore_success_handler) {
var ret, msgs = ASQ.messages.apply(ø,arguments);
msgs.shift();
if (msgs.length === 1) {
msgs = msgs[0];
}
ignore_failure_handler = true;
try {
ret = success(msgs);
}
catch (err) {
if (!ASQ.isMessageWrapper(err)) {
err = [err];
}
done.fail.apply(ø,err);
return;
}
// returned a sequence?
if (ASQ.isSequence(ret)) {
ret.pipe(done);
}
// returned a message wrapper?
else if (ASQ.isMessageWrapper(ret)) {
done.apply(ø,ret);
}
// returned a promise/thenable?
else if (isPromise(ret)) {
ret.then(done,done.fail);
}
// just a normal value to pass along
else {
done(ret);
}
}
else {
done.apply(ø,ARRAY_SLICE.call(arguments,1));
}
});
}
if (typeof failure === "function") {
api.or(function $$or(){
if (!ignore_failure_handler) {
var ret, msgs = ASQ.messages.apply(ø,arguments), smgs,
or_queue = ARRAY_SLICE.call(internals("or_queue"))
;
if (msgs.length === 1) {
msgs = msgs[0];
}
ignore_success_handler = true;
// NOTE: if this call throws, that'll automatically
// be handled by core as we'd want it to be
ret = failure(msgs);
// if we get this far:
// first, inject return value (if any) as
// next step's sequence messages
smgs = internals("sequence_messages");
smgs.length = 0;
if (typeof ret !== "undefined") {
if (!ASQ.isMessageWrapper(ret)) {
ret = [ret];
}
smgs.push.apply(smgs,ret);
}
// reset internal error state, because we've exclusively
// handled any errors up to this point of the sequence
internals("sequence_errors").length = 0;
internals("seq_error",false);
internals("then_ready",true);
// temporarily empty the or-queue
internals("or_queue").length = 0;
// make sure to schedule success-procession on the chain
api.val(function $$val(){
// pass thru messages
return ASQ.messages.apply(ø,arguments);
});
// at next cycle, reinstate the or-queue (if any)
if (or_queue.length > 0) {
schedule(function $$schedule(){
api.or.apply(ø,or_queue);
});
}
}
});
}
return api;
};
});
// "pCatch"
ASQ.extend("pCatch",function $$extend(api,internals){
return function $$pcatch(failure) {
if (internals("seq_aborted")) {
return api;
}
api.pThen(void 0,failure);
return api;
};
});
// "race"
ASQ.extend("race",function $$extend(api,internals){
return function $$race() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments)
.map(function $$map(v){
var def;
// tap any directly-provided sequences immediately
if (ASQ.isSequence(v)) {
def = { seq: v };
tapSequence(def);
return function $$fn(done) {
def.seq.pipe(done);
};
}
else return v;
});
api.then(function $$then(done){
var args = ARRAY_SLICE.call(arguments);
fns.forEach(function $$each(fn){
fn.apply(ø,args);
});
});
return api;
};
});
// "react" (reactive sequences)
ASQ.react = function $$react(reactor) {
function next() {
if (template) {
var sq = template.duplicate();
sq.unpause.apply(ø,arguments);
return sq;
}
return ASQ(function $$asq(){ throw "Disabled Sequence"; });
}
function registerTeardown(fn) {
if (template && typeof fn === "function") {
teardowns.push(fn);
}
}
var template = ASQ().duplicate(),
teardowns = []
;
// add reactive sequence kill switch
template.stop = function $$stop() {
if (template) {
template = null;
teardowns.forEach(Function.call,Function.call);
teardowns.length = 0;
}
};
next.onStream = function $$onStream() {
ARRAY_SLICE.call(arguments)
.forEach(function $$each(stream){
stream.on("data",next);
stream.on("error",next);
});
};
next.unStream = function $$unStream() {
ARRAY_SLICE.call(arguments)
.forEach(function $$each(stream){
stream.removeListener("data",next);
stream.removeListener("error",next);
});
};
// make sure `reactor(..)` is called async
ASQ.__schedule(function $$schedule(){
reactor.call(template,next,registerTeardown);
});
return template;
};
// "react" helpers
(function IIFE(){
function tapSequences() {
function tapSequence(seq) {
// temporary `trigger` which, if called before being replaced
// below, creates replacement proxy sequence with the
// event message(s) re-fired
function trigger() {
var args = ARRAY_SLICE.call(arguments);
def.seq = ASQ.react(function $$react(next){
next.apply(ø,args);
});
}
if (ASQ.isSequence(seq)) {
var def = { seq: seq };
// listen for events from the sequence-stream
seq.val(function $$val(){
trigger.apply(ø,arguments);
return ASQ.messages.apply(ø,arguments);
});
// make a reactive sequence to act as a proxy to the original
// sequence
def.seq = ASQ.react(function $$react(next){
// replace the temporary trigger (created above)
// with this proxy's trigger
trigger = next;
});
return def;
}
}
return ARRAY_SLICE.call(arguments)
.map(tapSequence)
.filter(Boolean);
}
function createReactOperator(buffer) {
return function $$react$operator(){
function reactor(next,registerTeardown){
function processSequence(def) {
// sequence-stream event listener
function trigger() {
var args = ASQ.messages.apply(ø,arguments);
// still observing sequence-streams?
if (seqs && seqs.length > 0) {
// store event message(s), if any
seq_events[seq_id] = [].concat(
buffer ? seq_events[seq_id] : [],
args.length > 0 ? [args] : undefined
);
// collect event message(s) across the
// sequence-stream sources
var messages = seq_events.reduce(function reducer(msgs,eventList,idx){
if (eventList.length > 0) msgs.push(eventList[0]);
return msgs;
},[]);
// did all sequence-streams get an event?
if (messages.length == seq_events.length) {
if (messages.length == 1) messages = messages[0];
// fire off reactive sequence instance
next.apply(ø,messages);
// discard stored event message(s)
seq_events.forEach(function $$each(eventList){
eventList.shift();
});
}
}
// keep sequence going
return args;
}
var seq_id = seq_events.length;
seq_events.push([]);
def.seq.val(trigger);
}
// process all sequence-streams
seqs.forEach(processSequence);
// listen for stop() of reactive sequence
registerTeardown(function $$teardown(){
seqs = seq_events = null;
});
}
var seq_events = [],
// observe all sequence-streams
seqs = tapSequences.apply(null,arguments)
;
if (seqs.length == 0) return;
return ASQ.react(reactor);
};
}
ASQ.react.all = ASQ.react.zip = createReactOperator(/*buffer=*/true);
ASQ.react.latest = ASQ.react.combine = createReactOperator(/*buffer=false*/);
ASQ.react.any = ASQ.react.merge = function $$react$any(){
function reactor(next,registerTeardown){
function processSequence(def){
function trigger(){
var args = ASQ.messages.apply(ø,arguments);
// still observing sequence-streams?
if (seqs && seqs.length > 0) {
// fire off reactive sequence instance
next.apply(ø,args);
}
// keep sequence going
return args;
}
// sequence-stream event listener
def.seq.val(trigger);
}
// observe all sequence-streams
seqs.forEach(processSequence);
// listen for stop() of reactive sequence
registerTeardown(function $$teardown(){
seqs = null;
});
}
// observe all sequence-streams
var seqs = tapSequences.apply(null,arguments);
if (seqs.length == 0) return;
return ASQ.react(reactor);
};
ASQ.react.distinct = function $$react$distinct(seq){
function filterer() {
function isDuplicate(msgs) {
return (
msgs.length == messages.length &&
msgs.every(function $$every(val,idx){
return val === messages[idx];
})
);
}
var messages = ASQ.messages.apply(ø,arguments);
// any messages to check against?
if (messages.length > 0) {
// messages already sent before?
if (prev_messages.some(isDuplicate)) {
// bail on duplicate messages
return false;
}
// save messages for future distinct checking
prev_messages.push(messages);
}
// allow distinct non-duplicate value through
return true;
}
var prev_messages = [];
return ASQ.react.filter(seq,filterer);
};
ASQ.react.filter = function $$react$filter(seq,filterer){
function reactor(next,registerTeardown) {
function trigger(){
var messages = ASQ.messages.apply(ø,arguments);
if (filterer && filterer.apply(ø,messages)) {
// fire off reactive sequence instance
next.apply(ø,messages);
}
// keep sequence going
return messages;
}
// sequence-stream event listener
def.seq.val(trigger);
// listen for stop() of reactive sequence
registerTeardown(function $$teardown(){
def = filterer = null;
});
}
// observe sequence-stream
var def = tapSequences(seq)[0];
if (!def) return;
return ASQ.react(reactor);
};
ASQ.react.fromObservable = function $$react$from$observable(obsv){
function reactor(next,registerTeardown){
// process buffer (if any)
buffer.forEach(next);
buffer.length = 0;
// start non-buffered notifications?
if (!buffer.complete) {
notify = next;
}
registerTeardown(function $$teardown(){
obsv.dispose();
});
}
function notify(v) {
buffer.push(v);
}
var buffer = [];
obsv.subscribe(
function $$on$next(v){
notify(v);
},
function $$on$error(){},
function $$on$complete(){
buffer.complete = true;
obsv.dispose();
}
);
return ASQ.react(reactor);
};
ASQ.extend("toObservable",function $$extend(api,internals){
return function $$to$observable(){
function init(observer) {
function define(pair){
function listen(){
var args = ASQ.messages.apply(ø,arguments);
observer[pair[1]].apply(observer,
args.length == 1 ? [args[0]] : args
);
return args;
}
api[pair[0]](listen);
}
[["val","onNext"],["or","onError"]]
.forEach(define);
}
return Rx.Observable.create(init);
};
});
})();
// "runner"
ASQ.extend("runner",function $$extend(api,internals){
return function $$runner() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var args = ARRAY_SLICE.call(arguments);
api
.then(function $$then(mainDone){
function wrap(v) {
// function? expected to produce an iterator
// (like a generator) or a promise
if (typeof v === "function") {
// call function passing in the control token
// note: neutralize `this` in call to prevent
// unexpected behavior
v = v.call(ø,next_val);
// promise returned (ie, from async function)?
if (isPromise(v)) {
// wrap it in iterable sequence
v = ASQ.iterable(v);
}
}
// an iterable sequence? duplicate it (in case of multiple runs)
else if (ASQ.isSequence(v) && "next" in v) {
v = v.duplicate();
}
// wrap anything else in iterable sequence
else {
v = ASQ.iterable(v);
}
// a sequence to tap for errors?
if (ASQ.isSequence(v)) {
// listen for any sequence failures
v.or(function $$or(){
// signal iteration-error
mainDone.fail.apply(ø,arguments);
});
}
return v;
}
function addWrapped() {
iterators.push.apply(
iterators,
ARRAY_SLICE.call(arguments).map(wrap)
);
}
var iterators = args,
token = {
messages: ARRAY_SLICE.call(arguments,1),
add: addWrapped
},
iter, ret, next_val = token
;
// map co-routines to round-robin list of iterators
iterators = iterators.map(wrap);
// async iteration of round-robin list
(function iterate(){
// get next co-routine in list
iter = iterators.shift();
// process the iteration
try {
// multiple messages to send to an iterable
// sequence?
if (ASQ.isMessageWrapper(next_val) &&
ASQ.isSequence(iter)
) {
ret = iter.next.apply(iter,next_val);
}
else {
ret = iter.next(next_val);
}
}
catch (err) {
return mainDone.fail(err);
}
// bail on run in aborted sequence
if (internals("seq_aborted")) return;
// was the control token yielded?
if (ret.value === token) {
// round-robin: put co-routine back into the list
// at the end where it was so it can be processed
// again on next loop-iteration
iterators.push(iter);
next_val = token;
schedule(iterate); // async recurse
}
else {
// not a recognized ASQ instance returned?
if (!ASQ.isSequence(ret.value)) {
// received a thenable/promise back?
if (isPromise(ret.value)) {
// wrap in a sequence
ret.value = ASQ().promise(ret.value);
}
// thunk yielded?
else if (typeof ret.value === "function") {
// wrap thunk call in a sequence
var fn = ret.value;
ret.value = ASQ(function $$ASQ(done){
fn(done.errfcb);
});
}
// message wrapper returned?
else if (ASQ.isMessageWrapper(ret.value)) {
// wrap message(s) in a sequence
ret.value = ASQ.apply(ø,
// don't let `apply(..)` discard an empty message
// wrapper! instead, pass it along as its own value
// itself.
ret.value.length > 0 ? ret.value : ASQ.messages(undefined)
);
}
// non-undefined value returned?
else if (typeof ret.value !== "undefined") {
// wrap the value in a sequence
ret.value = ASQ(ret.value);
}
else {
// make an empty sequence
ret.value = ASQ();
}
}
ret.value
.val(function $$val(){
// bail on run in aborted sequence
if (internals("seq_aborted")) return;
if (arguments.length > 0) {
// save any return messages for input
// to next iteration
next_val = arguments.length > 1 ?
ASQ.messages.apply(ø,arguments) :
arguments[0]
;
}
// still more to iterate?
if (!ret.done) {
// was the control token passed along?
if (next_val === token) {
// round-robin: put co-routine back into the list
// at the end, so that the the next iterator can be
// processed on next loop-iteration
iterators.push(iter);
}
else {
// put co-routine back in where it just
// was so it can be processed again on
// next loop-iteration
iterators.unshift(iter);
}
}
// still have some co-routine runs to process?
if (iterators.length > 0) {
iterate(); // async recurse
}
// all done!
else {
// previous value message?
if (typeof next_val !== "undefined") {
// not a message wrapper array?
if (!ASQ.isMessageWrapper(next_val)) {
// wrap value for the subsequent `apply(..)`
next_val = [next_val];
}
}
else {
// nothing to affirmatively pass along
next_val = [];
}
// signal done with all co-routine runs
mainDone.apply(ø,next_val);
}
})
.or(function $$or(){
// bail on run in aborted sequence
if (internals("seq_aborted")) return;
try {
// if an error occurs in the step-continuation
// promise or sequence, throw it back into the
// generator or iterable-sequence
iter["throw"].apply(iter,arguments);
}
catch (err) {
// if an error comes back out of after the throw,
// pass it out to the main sequence, as iteration
// must now be complete
mainDone.fail(err);
}
});
}
})();
});
return api;
};
});
// "toPromise"
ASQ.extend("toPromise",function $$extend(api,internals){
return function $$to$promise() {
return new Promise(function $$executor(resolve,reject){
api
.val(function $$val(){
var args = ARRAY_SLICE.call(arguments);
resolve.call(ø,args.length > 1 ? args : args[0]);
return ASQ.messages.apply(ø,args);
})
.or(function $$or(){
var args = ARRAY_SLICE.call(arguments);
reject.call(ø,args.length > 1 ? args : args[0]);
});
});
};
});
// "try"
ASQ.extend("try",function $$extend(api,internals){
return function $$try() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments)
.map(function $$map(fn){
return function $$then(mainDone) {
var main_args = ARRAY_SLICE.call(arguments),
sq = ASQ.apply(ø,main_args.slice(1))
;
sq
.then(function $$inner$then(){
fn.apply(ø,arguments);
})
.val(function $$val(){
mainDone.apply(ø,arguments);
})
.or(function $$inner$or(){
var msgs = ASQ.messages.apply(ø,arguments);
// failed, so map error(s) as `catch`
mainDone({
"catch": msgs.length > 1 ? msgs : msgs[0]
});
});
};
});
api.then.apply(ø,fns);
return api;
};
});
// "until"
ASQ.extend("until",function $$extend(api,internals){
return function $$until() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments)
.map(function $$map(fn){
return function $$then(mainDone) {
var main_args = ARRAY_SLICE.call(arguments),
sq = ASQ.apply(ø,main_args.slice(1))
;
sq
.then(function $$inner$then(){
var args = ARRAY_SLICE.call(arguments);
args[0]["break"] = function $$break(){
mainDone.fail.apply(ø,arguments);
sq.abort();
};
fn.apply(ø,args);
})
.val(function $$val(){
mainDone.apply(ø,arguments);
})
.or(function $$inner$or(){
// failed, retry
$$then.apply(ø,main_args);
});
};
});
api.then.apply(ø,fns);
return api;
};
});
// "waterfall"
ASQ.extend("waterfall",function $$extend(api,internals){
return function $$waterfall() {
if (internals("seq_error") || internals("seq_aborted") ||
arguments.length === 0
) {
return api;
}
var fns = ARRAY_SLICE.call(arguments);
api.then(function $$then(done){
var msgs = ASQ.messages(),
sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1))
;
fns.forEach(function $$each(fn){
sq.then(fn)
.val(function $$val(){
var args = ASQ.messages.apply(ø,arguments);
msgs.push(args.length > 1 ? args : args[0]);
return msgs;
});
});
sq.pipe(done);
});
return api;
};
});
// "wrap"
ASQ.wrap = function $$wrap(fn,opts) {
function checkThis(t,o) {
return (!t ||
(typeof window != "undefined" && t === window) ||
(typeof global != "undefined" && t === global)
) ? o : t;
}
var errfcb, params_first, act, this_obj;
opts = (opts && typeof opts == "object") ? opts : {};
if (
(opts.errfcb && opts.splitcb) ||
(opts.errfcb && opts.simplecb) ||
(opts.splitcb && opts.simplecb) ||
("errfcb" in opts && !opts.errfcb && !opts.splitcb && !opts.simplecb) ||
(opts.params_first && opts.params_last)
) {
throw Error("Invalid options");
}
// initialize default flags
this_obj = (opts["this"] && typeof opts["this"] == "object") ? opts["this"] : ø;
errfcb = opts.errfcb || !(opts.splitcb || opts.simplecb);
params_first = !!opts.params_first ||
(!opts.params_last && !("params_first" in opts || opts.params_first)) ||
("params_last" in opts && !opts.params_first && !opts.params_last)
;
if (params_first) {
act = "push";
}
else {
act = "unshift";
}
if (opts.gen) {
return function $$wrapped$gen() {
return ASQ.apply(ø,arguments).runner(fn);
};
}
if (errfcb) {
return function $$wrapped$errfcb() {
var args = ARRAY_SLICE.call(arguments),
_this = checkThis(this,this_obj)
;
return ASQ(function $$asq(done){
args[act](done.errfcb);
fn.apply(_this,args);
});
};
}
if (opts.splitcb) {
return function $$wrapped$splitcb() {
var args = ARRAY_SLICE.call(arguments),
_this = checkThis(this,this_obj)
;
return ASQ(function $$asq(done){
args[act](done,done.fail);
fn.apply(_this,args);
});
};
}
if (opts.simplecb) {
return function $$wrapped$simplecb() {
var args = ARRAY_SLICE.call(arguments),
_this = checkThis(this,this_obj)
;
return ASQ(function $$asq(done){
args[act](done);
fn.apply(_this,args);
});
};
}
};
// just return `ASQ` itself for convenience sake
return ASQ;
});
|
/*before*/"use strict";
/*after*/foo();
|
(function() {
var add, crispedges, feature, flexbox, fullscreen, gradients, logicalProps, prefix, readOnly, resolution, result, sort, writingMode,
slice = [].slice;
sort = function(array) {
return array.sort(function(a, b) {
var d;
a = a.split(' ');
b = b.split(' ');
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
d = parseFloat(a[1]) - parseFloat(b[1]);
if (d > 0) {
return 1;
} else if (d < 0) {
return -1;
} else {
return 0;
}
}
});
};
feature = function(data, opts, callback) {
var browser, match, need, ref, ref1, support, version, versions;
if (!callback) {
ref = [opts, {}], callback = ref[0], opts = ref[1];
}
match = opts.match || /\sx($|\s)/;
need = [];
ref1 = data.stats;
for (browser in ref1) {
versions = ref1[browser];
for (version in versions) {
support = versions[version];
if (support.match(match)) {
need.push(browser + ' ' + version);
}
}
}
return callback(sort(need));
};
result = {};
prefix = function() {
var data, i, j, k, len, name, names, results;
names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++];
results = [];
for (k = 0, len = names.length; k < len; k++) {
name = names[k];
result[name] = {};
results.push((function() {
var results1;
results1 = [];
for (i in data) {
results1.push(result[name][i] = data[i]);
}
return results1;
})());
}
return results;
};
add = function() {
var data, j, k, len, name, names, results;
names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++];
results = [];
for (k = 0, len = names.length; k < len; k++) {
name = names[k];
results.push(result[name].browsers = sort(result[name].browsers.concat(data.browsers)));
}
return results;
};
module.exports = result;
feature(require('caniuse-db/features-json/border-radius'), function(browsers) {
return prefix('border-radius', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius', {
mistakes: ['-khtml-', '-ms-', '-o-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-boxshadow'), function(browsers) {
return prefix('box-shadow', {
mistakes: ['-khtml-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-animation'), function(browsers) {
return prefix('animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', 'animation-iteration-count', 'animation-play-state', 'animation-timing-function', '@keyframes', {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-transitions'), function(browsers) {
return prefix('transition', 'transition-property', 'transition-duration', 'transition-delay', 'transition-timing-function', {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/transforms2d'), function(browsers) {
return prefix('transform', 'transform-origin', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/transforms3d'), function(browsers) {
prefix('perspective', 'perspective-origin', {
browsers: browsers
});
return prefix('transform-style', 'backface-visibility', {
mistakes: ['-ms-', '-o-'],
browsers: browsers
});
});
gradients = require('caniuse-db/features-json/css-gradients');
feature(gradients, {
match: /y\sx/
}, function(browsers) {
return prefix('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
mistakes: ['-ms-'],
browsers: browsers
});
});
feature(gradients, {
match: /a\sx/
}, function(browsers) {
browsers = browsers.map(function(i) {
if (/op/.test(i)) {
return i;
} else {
return i + " old";
}
});
return add('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-boxsizing'), function(browsers) {
return prefix('box-sizing', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-filters'), function(browsers) {
return prefix('filter', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-filter-function'), function(browsers) {
return prefix('filter-function', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-backdrop-filter'), function(browsers) {
return prefix('backdrop-filter', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-element-function'), function(browsers) {
return prefix('element', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/multicolumn'), function(browsers) {
prefix('columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', {
browsers: browsers
});
return prefix('column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/user-select-none'), function(browsers) {
return prefix('user-select', {
mistakes: ['-khtml-'],
browsers: browsers
});
});
flexbox = require('caniuse-db/features-json/flexbox');
feature(flexbox, {
match: /a\sx/
}, function(browsers) {
browsers = browsers.map(function(i) {
if (/ie|firefox/.test(i)) {
return i;
} else {
return i + " 2009";
}
});
prefix('display-flex', 'inline-flex', {
props: ['display'],
browsers: browsers
});
prefix('flex', 'flex-grow', 'flex-shrink', 'flex-basis', {
browsers: browsers
});
return prefix('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', {
browsers: browsers
});
});
feature(flexbox, {
match: /y\sx/
}, function(browsers) {
add('display-flex', 'inline-flex', {
browsers: browsers
});
add('flex', 'flex-grow', 'flex-shrink', 'flex-basis', {
browsers: browsers
});
return add('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/calc'), function(browsers) {
return prefix('calc', {
props: ['*'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/background-img-opts'), function(browsers) {
return prefix('background-clip', 'background-origin', 'background-size', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/font-feature'), function(browsers) {
return prefix('font-feature-settings', 'font-variant-ligatures', 'font-language-override', 'font-kerning', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/border-image'), function(browsers) {
return prefix('border-image', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-selection'), function(browsers) {
return prefix('::selection', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-placeholder'), function(browsers) {
browsers = browsers.map(function(i) {
var name, ref, version;
ref = i.split(' '), name = ref[0], version = ref[1];
if (name === 'firefox' && parseFloat(version) <= 18) {
return i + ' old';
} else {
return i;
}
});
return prefix('::placeholder', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-hyphens'), function(browsers) {
return prefix('hyphens', {
browsers: browsers
});
});
fullscreen = require('caniuse-db/features-json/fullscreen');
feature(fullscreen, function(browsers) {
return prefix(':fullscreen', {
selector: true,
browsers: browsers
});
});
feature(fullscreen, {
match: /x(\s#2|$)/
}, function(browsers) {
return prefix('::backdrop', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-tabsize'), function(browsers) {
return prefix('tab-size', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/intrinsic-width'), function(browsers) {
return prefix('max-content', 'min-content', 'fit-content', 'fill-available', {
props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-cursors-newer'), function(browsers) {
return prefix('zoom-in', 'zoom-out', {
props: ['cursor'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-cursors-grab'), function(browsers) {
return prefix('grab', 'grabbing', {
props: ['cursor'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-sticky'), function(browsers) {
return prefix('sticky', {
props: ['position'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/pointer'), function(browsers) {
return prefix('touch-action', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-decoration'), function(browsers) {
return prefix('text-decoration-style', 'text-decoration-line', 'text-decoration-color', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-size-adjust'), function(browsers) {
return prefix('text-size-adjust', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-masks'), function(browsers) {
prefix('mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source', {
browsers: browsers
});
return prefix('clip-path', 'mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-boxdecorationbreak'), function(brwsrs) {
return prefix('box-decoration-break', {
browsers: brwsrs
});
});
feature(require('caniuse-db/features-json/object-fit'), function(browsers) {
return prefix('object-fit', 'object-position', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-shapes'), function(browsers) {
return prefix('shape-margin', 'shape-outside', 'shape-image-threshold', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-overflow'), function(browsers) {
return prefix('text-overflow', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-emphasis'), function(browsers) {
return prefix('text-emphasis', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-deviceadaptation'), function(browsers) {
return prefix('@viewport', {
browsers: browsers
});
});
resolution = require('caniuse-db/features-json/css-media-resolution');
feature(resolution, {
match: /( x($| )|a #3)/
}, function(browsers) {
return prefix('@resolution', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-text-align-last'), function(browsers) {
return prefix('text-align-last', {
browsers: browsers
});
});
crispedges = require('caniuse-db/features-json/css-crisp-edges');
feature(crispedges, {
match: /y x/
}, function(browsers) {
return prefix('pixelated', {
props: ['image-rendering'],
browsers: browsers
});
});
feature(crispedges, {
match: /a x #2/
}, function(browsers) {
return prefix('image-rendering', {
browsers: browsers
});
});
logicalProps = require('caniuse-db/features-json/css-logical-props');
feature(logicalProps, function(browsers) {
return prefix('border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', {
browsers: browsers
});
});
feature(logicalProps, {
match: /x\s#2/
}, function(browsers) {
return prefix('border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-appearance'), function(browsers) {
return prefix('appearance', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-snappoints'), function(browsers) {
return prefix('scroll-snap-type', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scroll-snap-points-x', 'scroll-snap-points-y', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-regions'), function(browsers) {
return prefix('flow-into', 'flow-from', 'region-fragment', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-image-set'), function(browsers) {
return prefix('image-set', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
writingMode = require('caniuse-db/features-json/css-writing-mode');
feature(writingMode, {
match: /a|x/
}, function(browsers) {
return prefix('writing-mode', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-cross-fade.json'), function(browsers) {
return prefix('cross-fade', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
readOnly = require('caniuse-db/features-json/css-read-only-write.json');
feature(readOnly, function(browsers) {
return prefix(':read-only', ':read-write', {
selector: true,
browsers: browsers
});
});
}).call(this);
|
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import PasswordTestCase from './PasswordTestCase';
const React = window.React;
function NumberInputs() {
return (
<FixtureSet title="Password inputs">
<TestCase
title="The show password icon"
description={`
Some browsers have an unmask password icon that React accidentally
prevents the display of.
`}
affectedBrowsers="IE Edge, IE 11">
<TestCase.Steps>
<li>Type any string (not an actual password)</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The field should include the "unmasking password" icon.
</TestCase.ExpectedResult>
<PasswordTestCase />
</TestCase>
</FixtureSet>
);
}
export default NumberInputs;
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("placeholder","sv",{title:"Innehållsrutans egenskaper",toolbar:"Skapa innehållsruta",name:"Innehållsrutans namn",invalidName:"Innehållsrutan får inte vara tom och får inte innehålla någon av följande tecken: [, ], \x3c, \x3e",pathName:"innehållsruta"}); |
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) {
frappe.dom.freeze();
if($.isPlainObject(arg)) arg = JSON.stringify(arg);
return $c('runserverobj',
args={'method': method, 'docs': JSON.stringify(doc), 'arg': arg },
function(r, rt) {
frappe.dom.unfreeze();
if (r.message) {
var d = locals[dt][dn];
var field_dict = r.message;
for(var key in field_dict) {
d[key] = field_dict[key];
if (table_field)
refresh_field(key, d.name, table_field);
else
refresh_field(key);
}
}
if(call_back){
doc = locals[doc.doctype][doc.name];
call_back(doc, dt, dn);
}
}
);
}
set_multiple = function (dt, dn, dict, table_field) {
var d = locals[dt][dn];
for(var key in dict) {
d[key] = dict[key];
if (table_field)
refresh_field(key, d.name, table_field);
else
refresh_field(key);
}
}
refresh_many = function (flist, dn, table_field) {
for(var i in flist) {
if (table_field)
refresh_field(flist[i], dn, table_field);
else
refresh_field(flist[i]);
}
}
set_field_tip = function(n,txt) {
var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname);
if(df)df.description = txt;
if(cur_frm && cur_frm.fields_dict) {
if(cur_frm.fields_dict[n])
cur_frm.fields_dict[n].comment_area.innerHTML = replace_newlines(txt);
else
console.log('[set_field_tip] Unable to set field tip: ' + n);
}
}
refresh_field = function(n, docname, table_field) {
// multiple
if(typeof n==typeof [])
refresh_many(n, docname, table_field);
if(table_field && cur_frm.fields_dict[table_field].grid.grid_rows_by_docname) { // for table
cur_frm.fields_dict[table_field].grid.grid_rows_by_docname[docname].refresh_field(n);
} else if(cur_frm) {
cur_frm.refresh_field(n)
}
}
set_field_options = function(n, txt) {
cur_frm.set_df_property(n, 'options', txt)
}
set_field_permlevel = function(n, level) {
cur_frm.set_df_property(n, 'permlevel', level)
}
toggle_field = function(n, hidden) {
var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname);
if(df) {
df.hidden = hidden;
refresh_field(n);
}
else {
console.log((hidden ? "hide_field" : "unhide_field") + " cannot find field " + n);
}
}
hide_field = function(n) {
if(cur_frm) {
if(n.substr) toggle_field(n, 1);
else { for(var i in n) toggle_field(n[i], 1) }
}
}
unhide_field = function(n) {
if(cur_frm) {
if(n.substr) toggle_field(n, 0);
else { for(var i in n) toggle_field(n[i], 0) }
}
}
get_field_obj = function(fn) {
return cur_frm.fields_dict[fn];
}
// set missing values in given doc
set_missing_values = function(doc, dict) {
// dict contains fieldname as key and "default value" as value
var fields_to_set = {};
$.each(dict, function(i, v) { if (!doc[i]) { fields_to_set[i] = v; } });
if (fields_to_set) { set_multiple(doc.doctype, doc.name, fields_to_set); }
}
_f.Frm.prototype.get_doc = function() {
return locals[this.doctype][this.docname];
}
_f.Frm.prototype.field_map = function(fnames, fn) {
if(typeof fnames==='string') {
if(fnames == '*') {
fnames = keys(this.fields_dict);
} else {
fnames = [fnames];
}
}
$.each(fnames, function(i,fieldname) {
//var field = cur_frm.fields_dict[f]; - much better design
var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname);
if(field) {
fn(field);
cur_frm.refresh_field(fieldname);
};
})
}
_f.Frm.prototype.set_df_property = function(fieldname, property, value) {
var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname)
if(field) {
field[property] = value;
cur_frm.refresh_field(fieldname);
};
}
_f.Frm.prototype.toggle_enable = function(fnames, enable) {
cur_frm.field_map(fnames, function(field) {
field.read_only = enable ? 0 : 1; });
}
_f.Frm.prototype.toggle_reqd = function(fnames, mandatory) {
cur_frm.field_map(fnames, function(field) { field.reqd = mandatory ? true : false; });
}
_f.Frm.prototype.toggle_display = function(fnames, show) {
cur_frm.field_map(fnames, function(field) { field.hidden = show ? 0 : 1; });
}
_f.Frm.prototype.call_server = function(method, args, callback) {
return $c_obj(cur_frm.doc, method, args, callback);
}
_f.Frm.prototype.get_files = function() {
return cur_frm.attachments
? frappe.utils.sort(cur_frm.attachments.get_attachments(), "file_name", "string")
: [] ;
}
_f.Frm.prototype.set_query = function(fieldname, opt1, opt2) {
var func = (typeof opt1=="function") ? opt1 : opt2;
if(opt2) {
this.fields_dict[opt1].grid.get_field(fieldname).get_query = func;
} else {
this.fields_dict[fieldname].get_query = func;
}
}
_f.Frm.prototype.set_value_if_missing = function(field, value) {
this.set_value(field, value, true);
}
_f.Frm.prototype.set_value = function(field, value, if_missing) {
var me = this;
var _set = function(f, v) {
var fieldobj = me.fields_dict[f];
if(fieldobj) {
if(!if_missing || !frappe.model.has_value(me.doctype, me.doc.name, f)) {
if(fieldobj.df.fieldtype==="Table" && $.isArray(v)) {
frappe.model.clear_table(me.doc, fieldobj.df.fieldname);
$.each(v, function(i, d) {
var child = frappe.model.add_child(me.doc, fieldobj.df.options,
fieldobj.df.fieldname, i+1);
$.extend(child, d);
});
me.refresh_field(f);
} else {
frappe.model.set_value(me.doctype, me.doc.name, f, v);
}
}
}
}
if(typeof field=="string") {
_set(field, value)
} else if($.isPlainObject(field)) {
$.each(field, function(f, v) {
_set(f, v);
})
}
}
_f.Frm.prototype.call = function(opts) {
var me = this;
if(!opts.doc) {
if(opts.method.indexOf(".")===-1)
opts.method = frappe.model.get_server_module_name(me.doctype) + "." + opts.method;
opts.original_callback = opts.callback;
opts.callback = function(r) {
if($.isPlainObject(r.message)) {
if(opts.child) {
// update child doc
opts.child = locals[opts.child.doctype][opts.child.name];
$.extend(opts.child, r.message);
me.fields_dict[opts.child.parentfield].refresh();
} else {
// update parent doc
me.set_value(r.message);
}
}
opts.original_callback && opts.original_callback(r);
}
} else {
opts.original_callback = opts.callback;
opts.callback = function(r) {
if(!r.exc) me.refresh_fields();
opts.original_callback && opts.original_callback(r);
}
}
return frappe.call(opts);
}
_f.Frm.prototype.get_field = function(field) {
return cur_frm.fields_dict[field];
};
_f.Frm.prototype.new_doc = function(doctype, field) {
frappe._from_link = field; frappe._from_link_scrollY = scrollY;
new_doc(doctype);
}
_f.Frm.prototype.set_read_only = function() {
var perm = [];
$.each(frappe.perm.get_perm(cur_frm.doc.doctype), function(i, p) {
perm[p.permlevel || 0] = {read:1};
});
cur_frm.perm = perm;
}
_f.Frm.prototype.get_formatted = function(fieldname) {
return frappe.format(this.doc[fieldname],
frappe.meta.get_docfield(this.doctype, fieldname, this.docname),
{no_icon:true}, this.doc);
}
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionThumbDown = (props) => (
<SvgIcon {...props}>
<path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v1.91l.01.01L1 14c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z"/>
</SvgIcon>
);
ActionThumbDown = pure(ActionThumbDown);
ActionThumbDown.displayName = 'ActionThumbDown';
ActionThumbDown.muiName = 'SvgIcon';
export default ActionThumbDown;
|
/**
* Module dependencies.
*/
var Connection = require('../../connection')
, mongo = require('mongodb')
, Server = mongo.Server
, ReplSetServers = mongo.ReplSetServers;
/**
* Connection for mongodb-native driver
*
* @api private
*/
function NativeConnection() {
Connection.apply(this, arguments);
};
/**
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = Connection.prototype;
/**
* Opens the connection.
*
* Example server options:
* auto_reconnect (default: false)
* poolSize (default: 1)
*
* Example db options:
* pk - custom primary key factory to generate `_id` values
*
* Some of these may break Mongoose. Use at your own risk. You have been warned.
*
* @param {Function} callback
* @api private
*/
NativeConnection.prototype.doOpen = function (fn) {
var server;
if (!this.db) {
server = new mongo.Server(this.host, Number(this.port), this.options.server);
this.db = new mongo.Db(this.name, server, this.options.db);
}
this.db.open(fn);
return this;
};
/**
* Opens a set connection
*
* See description of doOpen for server options. In this case options.replset
* is also passed to ReplSetServers. Some additional options there are
*
* reconnectWait (default: 1000)
* retries (default: 30)
* rs_name (default: false)
* read_secondary (default: false) Are reads allowed from secondaries?
*
* @param {Function} fn
* @api private
*/
NativeConnection.prototype.doOpenSet = function (fn) {
if (!this.db) {
var servers = []
, ports = this.port
, self = this
this.host.forEach(function (host, i) {
servers.push(new mongo.Server(host, Number(ports[i]), self.options.server));
});
var server = new ReplSetServers(servers, this.options.replset);
this.db = new mongo.Db(this.name, server, this.options.db);
}
this.db.open(fn);
return this;
};
/**
* Closes the connection
*
* @param {Function} callback
* @api private
*/
NativeConnection.prototype.doClose = function (fn) {
this.db.close();
if (fn) fn();
return this;
}
/**
* Module exports.
*/
module.exports = NativeConnection;
|
/**
* angular-strap
* @version v2.1.6 - 2015-01-11
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes ([email protected])
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"use strict";angular.module("mgcrea.ngStrap.helpers.dateFormatter",[]).service("$dateFormatter",["$locale","dateFilter",function(t,e){function r(t){return/(h+)([:\.])?(m+)[ ]?(a?)/i.exec(t).slice(1)}this.getDefaultLocale=function(){return t.id},this.getDatetimeFormat=function(e){return t.DATETIME_FORMATS[e]||e},this.weekdaysShort=function(){return t.DATETIME_FORMATS.SHORTDAY},this.hoursFormat=function(t){return r(t)[0]},this.minutesFormat=function(t){return r(t)[2]},this.timeSeparator=function(t){return r(t)[1]},this.showAM=function(t){return!!r(t)[3]},this.formatDate=function(t,r){return e(t,r)}}]);
//# sourceMappingURL=date-formatter.min.js.map |
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
*
* @class Phaser.Image
* @extends PIXI.Sprite
* @extends Phaser.Component.Core
* @extends Phaser.Component.Angle
* @extends Phaser.Component.Animation
* @extends Phaser.Component.AutoCull
* @extends Phaser.Component.Bounds
* @extends Phaser.Component.BringToTop
* @extends Phaser.Component.Crop
* @extends Phaser.Component.Destroy
* @extends Phaser.Component.FixedToCamera
* @extends Phaser.Component.InputEnabled
* @extends Phaser.Component.LifeSpan
* @extends Phaser.Component.LoadTexture
* @extends Phaser.Component.Overlap
* @extends Phaser.Component.Reset
* @extends Phaser.Component.ScaleMinMax
* @extends Phaser.Component.Smoothed
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Image = function (game, x, y, key, frame) {
x = x || 0;
y = y || 0;
key = key || null;
frame = frame || null;
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.IMAGE;
PIXI.Sprite.call(this, Phaser.Cache.DEFAULT);
Phaser.Component.Core.init.call(this, game, x, y, key, frame);
};
Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
Phaser.Image.prototype.constructor = Phaser.Image;
Phaser.Component.Core.install.call(Phaser.Image.prototype, [
'Angle',
'Animation',
'AutoCull',
'Bounds',
'BringToTop',
'Crop',
'Destroy',
'FixedToCamera',
'InputEnabled',
'LifeSpan',
'LoadTexture',
'Overlap',
'Reset',
'ScaleMinMax',
'Smoothed'
]);
Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.Image#preUpdate
* @memberof Phaser.Image
*/
Phaser.Image.prototype.preUpdate = function() {
if (!this.preUpdateInWorld())
{
return false;
}
return this.preUpdateCore();
};
|
// FIXME: Tell people that this is a manifest file, real code should go into discrete files
// FIXME: Tell people how Sprockets and CoffeeScript works
//
//= require jquery
//= require jquery_ujs
//= require_tree .
|
/*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */
(function(root) {
'use strict';
var DependencyInjection = new (function DependencyInjection() {
var _this = this,
_interfaces = {};
function _formatFactoryFunction(factoryFunction) {
if (typeof factoryFunction == 'function') {
var funcString = factoryFunction
.toString()
// remove comments
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '');
var matches = funcString.match(/^function\s*[^\(]*\s*\(\s*([^\)]*)\)/m);
if (matches === null || matches.length < 2) {
factoryFunction = [factoryFunction];
}
else {
factoryFunction = matches[1]
.replace(/\s/g, '')
.split(',')
.filter(function(arg) {
return arg.trim().length > 0;
})
.concat(factoryFunction);
}
return factoryFunction;
}
else {
var factoryArrayCopy = [];
for (var i = 0; i < factoryFunction.length; i++) {
factoryArrayCopy.push(factoryFunction[i]);
}
factoryFunction = factoryArrayCopy;
}
return factoryFunction;
}
function Injector(instanceName) {
function _getInjections(dependencies, name, customDependencies, noError) {
var interfaces = _interfaces[name].interfacesSupported,
injections = [],
i,
j;
for (i = 0; i < dependencies.length; i++) {
var factory = null;
if (customDependencies && typeof customDependencies[dependencies[i]] != 'undefined') {
factory = customDependencies[dependencies[i]];
}
else {
for (j = 0; j < interfaces.length; j++) {
if (!_interfaces[interfaces[j]]) {
if (noError) {
return false;
}
throw new Error('DependencyInjection: "' + interfaces[j] + '" interface is not registered.');
}
factory = _interfaces[interfaces[j]].factories[dependencies[i]];
if (factory) {
factory.interfaceName = interfaces[j];
break;
}
}
}
if (factory) {
if (!factory.instantiated) {
var deps = _formatFactoryFunction(factory.result);
factory.result = deps.pop();
var factoryInjections = _getInjections(deps, factory.interfaceName);
factory.result = factory.result.apply(_this, factoryInjections);
factory.instantiated = true;
}
injections.push(factory.result);
}
else {
if (noError) {
return false;
}
throw new Error('DependencyInjection: "' + dependencies[i] + '" is not registered or accessible in ' + name + '.');
}
}
return injections;
}
this.get = function(factoryName, noError) {
var injections = _getInjections([factoryName], instanceName, null, noError);
if (injections.length) {
return injections[0];
}
return false;
};
this.invoke = function(thisArg, func, customDependencies) {
var dependencies = _formatFactoryFunction(func);
func = dependencies.pop();
if (customDependencies) {
var formatcustomDependencies = {},
interfaceName,
factory;
for (interfaceName in customDependencies) {
for (factory in customDependencies[interfaceName]) {
formatcustomDependencies[factory] = {
interfaceName: interfaceName,
instantiated: false,
result: customDependencies[interfaceName][factory]
};
}
}
customDependencies = formatcustomDependencies;
}
var injections = _getInjections(dependencies, instanceName, customDependencies);
return func.apply(thisArg, injections);
};
}
this.injector = {};
this.registerInterface = function(name, canInjectInterfaces) {
if (_this[name]) {
return _this;
}
_interfaces[name] = {
interfacesSupported: (canInjectInterfaces || []).concat(name),
factories: {}
};
_this.injector[name] = new Injector(name);
_this[name] = function DependencyInjectionFactory(factoryName, factoryFunction, replaceIfExists) {
if (!replaceIfExists && _interfaces[name].factories[factoryName]) {
return _this;
}
_interfaces[name].factories[factoryName] = {
instantiated: false,
result: factoryFunction
};
return _this;
};
return _this;
};
})();
if (typeof module != 'undefined' && typeof module.exports != 'undefined') {
module.exports = DependencyInjection;
}
else {
root.DependencyInjection = DependencyInjection;
}
})(this);
|
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactContext = require("./ReactContext");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactElement = require("./ReactElement");
var ReactElementValidator = require("./ReactElementValidator");
var ReactEmptyComponent = require("./ReactEmptyComponent");
var ReactErrorUtils = require("./ReactErrorUtils");
var ReactLegacyElement = require("./ReactLegacyElement");
var ReactOwner = require("./ReactOwner");
var ReactPerf = require("./ReactPerf");
var ReactPropTransferer = require("./ReactPropTransferer");
var ReactPropTypeLocations = require("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames");
var ReactUpdates = require("./ReactUpdates");
var assign = require("./Object.assign");
var instantiateReactComponent = require("./instantiateReactComponent");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var keyOf = require("./keyOf");
var monitorCodeUse = require("./monitorCodeUse");
var mapObject = require("./mapObject");
var shouldUpdateReactComponent = require("./shouldUpdateReactComponent");
var warning = require("./warning");
var MIXINS_KEY = keyOf({mixins: null});
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base ReactCompositeComponent class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.context
);
Constructor.contextTypes = assign(
{},
Constructor.contextTypes,
contextTypes
);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = assign(
{},
Constructor.propTypes,
propTypes
);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
}
};
function getDeclarationErrorAddendum(component) {
var owner = component._owner || null;
if (owner && owner.constructor && owner.constructor.displayName) {
return ' Check the render method of `' + owner.constructor.displayName +
'`.';
}
return '';
}
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== process.env.NODE_ENV ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ?
ReactCompositeComponentInterface[name] :
null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== process.env.NODE_ENV ? invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== process.env.NODE_ENV ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== process.env.NODE_ENV ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== process.env.NODE_ENV ? invariant(
ReactCurrentOwner.current == null,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). Render methods should be a pure function ' +
'of props and state.'
) : invariant(ReactCurrentOwner.current == null));
("production" !== process.env.NODE_ENV ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
("production" !== process.env.NODE_ENV ? invariant(
!ReactLegacyElement.isValidFactory(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!ReactLegacyElement.isValidFactory(spec)));
("production" !== process.env.NODE_ENV ? invariant(
!ReactElement.isValidElement(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactElement.isValidElement(spec)));
var proto = Constructor.prototype;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above
continue;
}
var property = spec[name];
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod =
ReactCompositeComponentInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isAlreadyDefined &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactCompositeComponentInterface[name];
// These cases should already be caught by validateMethodOverride
("production" !== process.env.NODE_ENV ? invariant(
isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
),
'ReactCompositeComponent: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
) : invariant(isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
)));
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("production" !== process.env.NODE_ENV) {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
("production" !== process.env.NODE_ENV ? invariant(
!isReserved,
'ReactCompositeComponent: You are attempting to define a reserved ' +
'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
'as an instance property instead; it will still be accessible on the ' +
'constructor.',
name
) : invariant(!isReserved));
var isInherited = name in Constructor;
("production" !== process.env.NODE_ENV ? invariant(
!isInherited,
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
) : invariant(!isInherited));
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== process.env.NODE_ENV ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
mapObject(two, function(value, key) {
("production" !== process.env.NODE_ENV ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `%s`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.',
key
) : invariant(one[key] === undefined));
one[key] = value;
});
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+---------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+---------------------------------+--------+
* | ^--------+ +-------+ +--------^ |
* | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIVE|-0-| UN |--->0 |
* | | | |PROPS | |MOUNTING| |
* | | | | | | | |
* | | | | | | | |
* | +--------+ +-------+ +--------+ |
* | | | |
* +-------+---------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function(element) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
// This is the public post-processed context. The real context and pending
// context lives on the element.
this.context = null;
this._compositeLifeCycleState = null;
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.context = this._processContext(this._currentElement._context);
this.props = this._processProps(this.props);
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== process.env.NODE_ENV ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent(),
this._currentElement.type // The wrapping type
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this.componentDidMount, this);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== process.env.NODE_ENV ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== process.env.NODE_ENV){
("production" !== process.env.NODE_ENV ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
assign({}, this._pendingState || this.state, partialState),
callback
);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
// If we're in a componentWillMount handler, don't enqueue a rerender
// because ReactUpdates assumes we're in a browser context (which is wrong
// for server rendering) and we're about to do a render anyway.
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState.
ReactUpdates.enqueueUpdate(this, callback);
}
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== process.env.NODE_ENV) {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== process.env.NODE_ENV ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== process.env.NODE_ENV) {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== process.env.NODE_ENV ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function(newProps) {
if ("production" !== process.env.NODE_ENV) {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(propTypes, newProps, ReactPropTypeLocations.prop);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function(propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error =
propTypes[propName](props, propName, componentName, location);
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// renderComponent calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
("production" !== process.env.NODE_ENV ? warning(false, error.message + addendum) : null);
}
}
}
},
/**
* If any of `_pendingElement`, `_pendingState`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
if (this._pendingElement == null &&
this._pendingState == null &&
!this._pendingForceUpdate) {
return;
}
var nextContext = this.context;
var nextProps = this.props;
var nextElement = this._currentElement;
if (this._pendingElement != null) {
nextElement = this._pendingElement;
nextContext = this._processContext(nextElement._context);
nextProps = this._processProps(nextElement.props);
this._pendingElement = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = null;
var nextState = this._pendingState || this.state;
this._pendingState = null;
var shouldUpdate =
this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("production" !== process.env.NODE_ENV) {
if (typeof shouldUpdate === "undefined") {
console.warn(
(this.constructor.displayName || 'ReactCompositeComponent') +
'.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.'
);
}
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextElement,
nextProps,
nextState,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this._currentElement = nextElement;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextElement._owner;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(
nextElement,
nextProps,
nextState,
nextContext,
transaction
) {
var prevElement = this._currentElement;
var prevProps = this.props;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextElement._owner;
this.updateComponent(
transaction,
prevElement
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext),
this
);
}
},
receiveComponent: function(nextElement, transaction) {
if (nextElement === this._currentElement &&
nextElement._owner != null) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for a element created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextElement,
transaction
);
},
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevParentElement) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevParentElement
);
var prevComponentInstance = this._renderedComponent;
var prevElement = prevComponentInstance._currentElement;
var nextElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevElement, nextElement)) {
prevComponentInstance.receiveComponent(nextElement, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(
nextElement,
this._currentElement.type
);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== process.env.NODE_ENV ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== process.env.NODE_ENV ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING &&
ReactCurrentOwner.current == null,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or within a `render` function.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING &&
ReactCurrentOwner.current == null));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(
this._currentElement._context
);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
if (renderedComponent === null || renderedComponent === false) {
renderedComponent = ReactEmptyComponent.getEmptyComponent();
ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
} else {
ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
}
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== process.env.NODE_ENV ? invariant(
ReactElement.isValidElement(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactElement.isValidElement(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = method.bind(component);
if ("production" !== process.env.NODE_ENV) {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
assign(
ReactCompositeComponentBase.prototype,
ReactComponent.Mixin,
ReactOwner.Mixin,
ReactPropTransferer.Mixin,
ReactCompositeComponentMixin
);
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function(props) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted. This will later be used
// by the stand-alone class implementation.
};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, Constructor)
);
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
("production" !== process.env.NODE_ENV ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== process.env.NODE_ENV) {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.'
);
}
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
if ("production" !== process.env.NODE_ENV) {
return ReactLegacyElement.wrapFactory(
ReactElementValidator.createFactory(Constructor)
);
}
return ReactLegacyElement.wrapFactory(
ReactElement.createFactory(Constructor)
);
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
|
angular
.module('menuDemoPosition', ['ngMaterial'])
.config(function($mdIconProvider) {
$mdIconProvider
.iconSet("call", 'img/icons/sets/communication-icons.svg', 24)
.iconSet("social", 'img/icons/sets/social-icons.svg', 24);
})
.controller('PositionDemoCtrl', function DemoCtrl($mdDialog) {
var originatorEv;
this.openMenu = function($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
this.announceClick = function(index) {
$mdDialog.show(
$mdDialog.alert()
.title('You clicked!')
.textContent('You clicked the menu item at index ' + index)
.ok('Nice')
.targetEvent(originatorEv)
);
originatorEv = null;
};
});
|
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.XHRLoader = function ( manager ) {
this.cache = new THREE.Cache();
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.XHRLoader.prototype = {
constructor: THREE.XHRLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var cached = scope.cache.get( url );
if ( cached !== undefined ) {
if ( onLoad ) onLoad( cached );
return;
}
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
scope.cache.add( url, this.response );
if ( onLoad ) onLoad( this.response );
scope.manager.itemEnd( url );
}, false );
if ( onProgress !== undefined ) {
request.addEventListener( 'progress', function ( event ) {
onProgress( event );
}, false );
}
if ( onError !== undefined ) {
request.addEventListener( 'error', function ( event ) {
onError( event );
}, false );
}
if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
if ( this.responseType !== undefined ) request.responseType = this.responseType;
request.send( null );
scope.manager.itemStart( url );
},
setResponseType: function ( value ) {
this.responseType = value;
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
}
};
|
/*
* KineticJS JavaScript Framework v5.1.0
* http://www.kineticjs.com/
* Copyright 2013, Eric Rowell
* Licensed under the MIT or GPL Version 2 licenses.
* Date: 2014-03-27
*
* Copyright (C) 2011 - 2013 by Eric Rowell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @namespace Kinetic
*/
/*jshint -W079, -W020*/
var Kinetic = {};
(function(root) {
var PI_OVER_180 = Math.PI / 180;
Kinetic = {
// public
version: '5.1.0',
// private
stages: [],
idCounter: 0,
ids: {},
names: {},
shapes: {},
listenClickTap: false,
inDblClickWindow: false,
// configurations
enableTrace: false,
traceArrMax: 100,
dblClickWindow: 400,
pixelRatio: undefined,
dragDistance : 0,
angleDeg: true,
// user agent
UA: (function() {
var userAgent = (root.navigator && root.navigator.userAgent) || '';
var ua = userAgent.toLowerCase(),
// jQuery UA regex
match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[],
// adding mobile flag as well
mobile = !!(userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i));
return {
browser: match[ 1 ] || '',
version: match[ 2 ] || '0',
// adding mobile flab
mobile: mobile
};
})(),
/**
* @namespace Filters
* @memberof Kinetic
*/
Filters: {},
/**
* Node constructor. Nodes are entities that can be transformed, layered,
* and have bound events. The stage, layers, groups, and shapes all extend Node.
* @constructor
* @memberof Kinetic
* @abstract
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
*/
Node: function(config) {
this._init(config);
},
/**
* Shape constructor. Shapes are primitive objects such as rectangles,
* circles, text, lines, etc.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Node
* @param {Object} config
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var customShape = new Kinetic.Shape({<br>
* x: 5,<br>
* y: 10,<br>
* fill: 'red',<br>
* // a Kinetic.Canvas renderer is passed into the drawFunc function<br>
* drawFunc: function(context) {<br>
* context.beginPath();<br>
* context.moveTo(200, 50);<br>
* context.lineTo(420, 80);<br>
* context.quadraticCurveTo(300, 100, 260, 170);<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* }<br>
*});
*/
Shape: function(config) {
this.__init(config);
},
/**
* Container constructor. Containers are used to contain nodes or other containers
* @constructor
* @memberof Kinetic
* @augments Kinetic.Node
* @abstract
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
*/
Container: function(config) {
this.__init(config);
},
/**
* Stage constructor. A stage is used to contain multiple layers
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {String|DomElement} config.container Container id or DOM element
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var stage = new Kinetic.Stage({<br>
* width: 500,<br>
* height: 800,<br>
* container: 'containerId'<br>
* });
*/
Stage: function(config) {
this.___init(config);
},
/**
* BaseLayer constructor.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var layer = new Kinetic.Layer();
*/
BaseLayer: function(config) {
this.___init(config);
},
/**
* Layer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var layer = new Kinetic.Layer();
*/
Layer: function(config) {
this.____init(config);
},
/**
* FastLayer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @example
* var layer = new Kinetic.FastLayer();
*/
FastLayer: function(config) {
this.____init(config);
},
/**
* Group constructor. Groups are used to contain shapes or other groups.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Container
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @param {Function} [config.clipFunc] clipping function
* @example
* var group = new Kinetic.Group();
*/
Group: function(config) {
this.___init(config);
},
/**
* returns whether or not drag and drop is currently active
* @method
* @memberof Kinetic
*/
isDragging: function() {
var dd = Kinetic.DD;
// if DD is not included with the build, then
// drag and drop is not even possible
if (!dd) {
return false;
}
// if DD is included with the build
else {
return dd.isDragging;
}
},
/**
* returns whether or not a drag and drop operation is ready, but may
* not necessarily have started
* @method
* @memberof Kinetic
*/
isDragReady: function() {
var dd = Kinetic.DD;
// if DD is not included with the build, then
// drag and drop is not even possible
if (!dd) {
return false;
}
// if DD is included with the build
else {
return !!dd.node;
}
},
_addId: function(node, id) {
if(id !== undefined) {
this.ids[id] = node;
}
},
_removeId: function(id) {
if(id !== undefined) {
delete this.ids[id];
}
},
_addName: function(node, name) {
if(name !== undefined) {
if(this.names[name] === undefined) {
this.names[name] = [];
}
this.names[name].push(node);
}
},
_removeName: function(name, _id) {
if(name !== undefined) {
var nodes = this.names[name];
if(nodes !== undefined) {
for(var n = 0; n < nodes.length; n++) {
var no = nodes[n];
if(no._id === _id) {
nodes.splice(n, 1);
}
}
if(nodes.length === 0) {
delete this.names[name];
}
}
}
},
getAngle: function(angle) {
return this.angleDeg ? angle * PI_OVER_180 : angle;
}
};
})(this);
// Uses Node, AMD or browser globals to create a module.
// If you want something that will work in other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrict.js
// Defines a module "returnExports" that depends another module called "b".
// Note that the name of the module is implied by the file name. It is best
// if the file name and the exported global have matching names.
// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.
// If you do not want to support the browser global path, then you
// can remove the `root` use and the passing `this` as the first arg to
// the top function.
// if the module has no dependencies, the above pattern can be simplified to
( function(root, factory) {
if( typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
var Canvas = require('canvas');
var jsdom = require('jsdom').jsdom;
var doc = jsdom('<!DOCTYPE html><html><head></head><body></body></html>');
var KineticJS = factory();
Kinetic.document = doc;
Kinetic.window = Kinetic.document.createWindow();
Kinetic.window.Image = Canvas.Image;
Kinetic.root = root;
Kinetic._nodeCanvas = Canvas;
module.exports = KineticJS;
return;
}
else if( typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
}
Kinetic.document = document;
Kinetic.window = window;
Kinetic.root = root;
}((1, eval)('this'), function() {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return Kinetic;
}));
;(function() {
/**
* Collection constructor. Collection extends
* Array. This class is used in conjunction with {@link Kinetic.Container#get}
* @constructor
* @memberof Kinetic
*/
Kinetic.Collection = function() {
var args = [].slice.call(arguments), length = args.length, i = 0;
this.length = length;
for(; i < length; i++) {
this[i] = args[i];
}
return this;
};
Kinetic.Collection.prototype = [];
/**
* iterate through node array and run a function for each node.
* The node and index is passed into the function
* @method
* @memberof Kinetic.Collection.prototype
* @param {Function} func
* @example
* // get all nodes with name foo inside layer, and set x to 10 for each
* layer.get('.foo').each(function(shape, n) {<br>
* shape.setX(10);<br>
* });
*/
Kinetic.Collection.prototype.each = function(func) {
for(var n = 0; n < this.length; n++) {
func(this[n], n);
}
};
/**
* convert collection into an array
* @method
* @memberof Kinetic.Collection.prototype
*/
Kinetic.Collection.prototype.toArray = function() {
var arr = [],
len = this.length,
n;
for(n = 0; n < len; n++) {
arr.push(this[n]);
}
return arr;
};
/**
* convert array into a collection
* @method
* @memberof Kinetic.Collection
* @param {Array} arr
*/
Kinetic.Collection.toCollection = function(arr) {
var collection = new Kinetic.Collection(),
len = arr.length,
n;
for(n = 0; n < len; n++) {
collection.push(arr[n]);
}
return collection;
};
// map one method by it's name
Kinetic.Collection._mapMethod = function(methodName) {
Kinetic.Collection.prototype[methodName] = function() {
var len = this.length,
i;
var args = [].slice.call(arguments);
for(i = 0; i < len; i++) {
this[i][methodName].apply(this[i], args);
}
return this;
};
};
Kinetic.Collection.mapMethods = function(constructor) {
var prot = constructor.prototype;
for(var methodName in prot) {
Kinetic.Collection._mapMethod(methodName);
}
};
/*
* Last updated November 2011
* By Simon Sarris
* www.simonsarris.com
* [email protected]
*
* Free to use and distribute at will
* So long as you are nice to people, etc
*/
/*
* The usage of this class was inspired by some of the work done by a forked
* project, KineticJS-Ext by Wappworks, which is based on Simon's Transform
* class. Modified by Eric Rowell
*/
/**
* Transform constructor
* @constructor
* @param {Array} Optional six-element matrix
* @memberof Kinetic
*/
Kinetic.Transform = function(m) {
this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0];
};
Kinetic.Transform.prototype = {
/**
* Copy Kinetic.Transform object
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
*/
copy: function() {
return new Kinetic.Transform(this.m);
},
/**
* Transform point
* @method
* @memberof Kinetic.Transform.prototype
* @param {Object} 2D point(x, y)
* @returns {Object} 2D point(x, y)
*/
point: function(p) {
var m = this.m;
return {
x: m[0] * p.x + m[2] * p.y + m[4],
y: m[1] * p.x + m[3] * p.y + m[5]
};
},
/**
* Apply translation
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} x
* @param {Number} y
* @returns {Kinetic.Transform}
*/
translate: function(x, y) {
this.m[4] += this.m[0] * x + this.m[2] * y;
this.m[5] += this.m[1] * x + this.m[3] * y;
return this;
},
/**
* Apply scale
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} sx
* @param {Number} sy
* @returns {Kinetic.Transform}
*/
scale: function(sx, sy) {
this.m[0] *= sx;
this.m[1] *= sx;
this.m[2] *= sy;
this.m[3] *= sy;
return this;
},
/**
* Apply rotation
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} rad Angle in radians
* @returns {Kinetic.Transform}
*/
rotate: function(rad) {
var c = Math.cos(rad);
var s = Math.sin(rad);
var m11 = this.m[0] * c + this.m[2] * s;
var m12 = this.m[1] * c + this.m[3] * s;
var m21 = this.m[0] * -s + this.m[2] * c;
var m22 = this.m[1] * -s + this.m[3] * c;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
},
/**
* Returns the translation
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Object} 2D point(x, y)
*/
getTranslation: function() {
return {
x: this.m[4],
y: this.m[5]
};
},
/**
* Apply skew
* @method
* @memberof Kinetic.Transform.prototype
* @param {Number} sx
* @param {Number} sy
* @returns {Kinetic.Transform}
*/
skew: function(sx, sy) {
var m11 = this.m[0] + this.m[2] * sy;
var m12 = this.m[1] + this.m[3] * sy;
var m21 = this.m[2] + this.m[0] * sx;
var m22 = this.m[3] + this.m[1] * sx;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
return this;
},
/**
* Transform multiplication
* @method
* @memberof Kinetic.Transform.prototype
* @param {Kinetic.Transform} matrix
* @returns {Kinetic.Transform}
*/
multiply: function(matrix) {
var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1];
var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1];
var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3];
var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3];
var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4];
var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5];
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
this.m[4] = dx;
this.m[5] = dy;
return this;
},
/**
* Invert the matrix
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
*/
invert: function() {
var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
var m0 = this.m[3] * d;
var m1 = -this.m[1] * d;
var m2 = -this.m[2] * d;
var m3 = this.m[0] * d;
var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]);
var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]);
this.m[0] = m0;
this.m[1] = m1;
this.m[2] = m2;
this.m[3] = m3;
this.m[4] = m4;
this.m[5] = m5;
return this;
},
/**
* return matrix
* @method
* @memberof Kinetic.Transform.prototype
*/
getMatrix: function() {
return this.m;
},
/**
* set to absolute position via translation
* @method
* @memberof Kinetic.Transform.prototype
* @returns {Kinetic.Transform}
* @author ericdrowell
*/
setAbsolutePosition: function(x, y) {
var m0 = this.m[0],
m1 = this.m[1],
m2 = this.m[2],
m3 = this.m[3],
m4 = this.m[4],
m5 = this.m[5],
yt = ((m0 * (y - m5)) - (m1 * (x - m4))) / ((m0 * m3) - (m1 * m2)),
xt = (x - m4 - (m2 * yt)) / m0;
return this.translate(xt, yt);
}
};
// CONSTANTS
var CANVAS = 'canvas',
CONTEXT_2D = '2d',
OBJECT_ARRAY = '[object Array]',
OBJECT_NUMBER = '[object Number]',
OBJECT_STRING = '[object String]',
PI_OVER_DEG180 = Math.PI / 180,
DEG180_OVER_PI = 180 / Math.PI,
HASH = '#',
EMPTY_STRING = '',
ZERO = '0',
KINETIC_WARNING = 'Kinetic warning: ',
KINETIC_ERROR = 'Kinetic error: ',
RGB_PAREN = 'rgb(',
COLORS = {
aqua: [0,255,255],
lime: [0,255,0],
silver: [192,192,192],
black: [0,0,0],
maroon: [128,0,0],
teal: [0,128,128],
blue: [0,0,255],
navy: [0,0,128],
white: [255,255,255],
fuchsia: [255,0,255],
olive:[128,128,0],
yellow: [255,255,0],
orange: [255,165,0],
gray: [128,128,128],
purple: [128,0,128],
green: [0,128,0],
red: [255,0,0],
pink: [255,192,203],
cyan: [0,255,255],
transparent: [255,255,255,0]
},
RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
/**
* @namespace Util
* @memberof Kinetic
*/
Kinetic.Util = {
/*
* cherry-picked utilities from underscore.js
*/
_isElement: function(obj) {
return !!(obj && obj.nodeType == 1);
},
_isFunction: function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
},
_isObject: function(obj) {
return (!!obj && obj.constructor == Object);
},
_isArray: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_ARRAY;
},
_isNumber: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_NUMBER;
},
_isString: function(obj) {
return Object.prototype.toString.call(obj) == OBJECT_STRING;
},
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_throttle: function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = new Date().getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
/*
* other utils
*/
_hasMethods: function(obj) {
var names = [],
key;
for(key in obj) {
if(this._isFunction(obj[key])) {
names.push(key);
}
}
return names.length > 0;
},
createCanvasElement: function() {
var canvas = Kinetic.document.createElement('canvas');
canvas.style = canvas.style || {};
return canvas;
},
isBrowser: function() {
return (typeof exports !== 'object');
},
_isInDocument: function(el) {
while(el = el.parentNode) {
if(el == Kinetic.document) {
return true;
}
}
return false;
},
_simplifyArray: function(arr) {
var retArr = [],
len = arr.length,
util = Kinetic.Util,
n, val;
for (n=0; n<len; n++) {
val = arr[n];
if (util._isNumber(val)) {
val = Math.round(val * 1000) / 1000;
}
else if (!util._isString(val)) {
val = val.toString();
}
retArr.push(val);
}
return retArr;
},
/*
* arg can be an image object or image data
*/
_getImage: function(arg, callback) {
var imageObj, canvas;
// if arg is null or undefined
if(!arg) {
callback(null);
}
// if arg is already an image object
else if(this._isElement(arg)) {
callback(arg);
}
// if arg is a string, then it's a data url
else if(this._isString(arg)) {
imageObj = new Kinetic.window.Image();
imageObj.onload = function() {
callback(imageObj);
};
imageObj.src = arg;
}
//if arg is an object that contains the data property, it's an image object
else if(arg.data) {
canvas = Kinetic.Util.createCanvasElement();
canvas.width = arg.width;
canvas.height = arg.height;
var _context = canvas.getContext(CONTEXT_2D);
_context.putImageData(arg, 0, 0);
this._getImage(canvas.toDataURL(), callback);
}
else {
callback(null);
}
},
_getRGBAString: function(obj) {
var red = obj.red || 0,
green = obj.green || 0,
blue = obj.blue || 0,
alpha = obj.alpha || 1;
return [
'rgba(',
red,
',',
green,
',',
blue,
',',
alpha,
')'
].join(EMPTY_STRING);
},
_rgbToHex: function(r, g, b) {
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
},
_hexToRgb: function(hex) {
hex = hex.replace(HASH, EMPTY_STRING);
var bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255
};
},
/**
* return random hex color
* @method
* @memberof Kinetic.Util.prototype
*/
getRandomColor: function() {
var randColor = (Math.random() * 0xFFFFFF << 0).toString(16);
while (randColor.length < 6) {
randColor = ZERO + randColor;
}
return HASH + randColor;
},
/**
* return value with default fallback
* @method
* @memberof Kinetic.Util.prototype
*/
get: function(val, def) {
if (val === undefined) {
return def;
}
else {
return val;
}
},
/**
* get RGB components of a color
* @method
* @memberof Kinetic.Util.prototype
* @param {String} color
* @example
* // each of the following examples return {r:0, g:0, b:255}<br>
* var rgb = Kinetic.Util.getRGB('blue');<br>
* var rgb = Kinetic.Util.getRGB('#0000ff');<br>
* var rgb = Kinetic.Util.getRGB('rgb(0,0,255)');
*/
getRGB: function(color) {
var rgb;
// color string
if (color in COLORS) {
rgb = COLORS[color];
return {
r: rgb[0],
g: rgb[1],
b: rgb[2]
};
}
// hex
else if (color[0] === HASH) {
return this._hexToRgb(color.substring(1));
}
// rgb string
else if (color.substr(0, 4) === RGB_PAREN) {
rgb = RGB_REGEX.exec(color.replace(/ /g,''));
return {
r: parseInt(rgb[1], 10),
g: parseInt(rgb[2], 10),
b: parseInt(rgb[3], 10)
};
}
// default
else {
return {
r: 0,
g: 0,
b: 0
};
}
},
// o1 takes precedence over o2
_merge: function(o1, o2) {
var retObj = this._clone(o2);
for(var key in o1) {
if(this._isObject(o1[key])) {
retObj[key] = this._merge(o1[key], retObj[key]);
}
else {
retObj[key] = o1[key];
}
}
return retObj;
},
cloneObject: function(obj) {
var retObj = {};
for(var key in obj) {
if(this._isObject(obj[key])) {
retObj[key] = this.cloneObject(obj[key]);
}
else if (this._isArray(obj[key])) {
retObj[key] = this.cloneArray(obj[key]);
} else {
retObj[key] = obj[key];
}
}
return retObj;
},
cloneArray: function(arr) {
return arr.slice(0);
},
_degToRad: function(deg) {
return deg * PI_OVER_DEG180;
},
_radToDeg: function(rad) {
return rad * DEG180_OVER_PI;
},
_capitalize: function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
error: function(str) {
throw new Error(KINETIC_ERROR + str);
},
warn: function(str) {
/*
* IE9 on Windows7 64bit will throw a JS error
* if we don't use window.console in the conditional
*/
if(Kinetic.root.console && console.warn) {
console.warn(KINETIC_WARNING + str);
}
},
extend: function(c1, c2) {
for(var key in c2.prototype) {
if(!( key in c1.prototype)) {
c1.prototype[key] = c2.prototype[key];
}
}
},
/**
* adds methods to a constructor prototype
* @method
* @memberof Kinetic.Util.prototype
* @param {Function} constructor
* @param {Object} methods
*/
addMethods: function(constructor, methods) {
var key;
for (key in methods) {
constructor.prototype[key] = methods[key];
}
},
_getControlPoints: function(x0, y0, x1, y1, x2, y2, t) {
var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)),
d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)),
fa = t * d01 / (d01 + d12),
fb = t * d12 / (d01 + d12),
p1x = x1 - fa * (x2 - x0),
p1y = y1 - fa * (y2 - y0),
p2x = x1 + fb * (x2 - x0),
p2y = y1 + fb * (y2 - y0);
return [p1x ,p1y, p2x, p2y];
},
_expandPoints: function(p, tension) {
var len = p.length,
allPoints = [],
n, cp;
for (n=2; n<len-2; n+=2) {
cp = Kinetic.Util._getControlPoints(p[n-2], p[n-1], p[n], p[n+1], p[n+2], p[n+3], tension);
allPoints.push(cp[0]);
allPoints.push(cp[1]);
allPoints.push(p[n]);
allPoints.push(p[n+1]);
allPoints.push(cp[2]);
allPoints.push(cp[3]);
}
return allPoints;
},
_removeLastLetter: function(str) {
return str.substring(0, str.length - 1);
}
};
})();
;(function() {
// calculate pixel ratio
var canvas = Kinetic.Util.createCanvasElement(),
context = canvas.getContext('2d'),
// if using a mobile device, calculate the pixel ratio. Otherwise, just use
// 1. For desktop browsers, if the user has zoom enabled, it affects the pixel ratio
// and causes artifacts on the canvas. As of 02/26/2014, there doesn't seem to be a way
// to reliably calculate the browser zoom for modern browsers, which is why we just set
// the pixel ratio to 1 for desktops
_pixelRatio = Kinetic.UA.mobile ? (function() {
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = context.webkitBackingStorePixelRatio
|| context.mozBackingStorePixelRatio
|| context.msBackingStorePixelRatio
|| context.oBackingStorePixelRatio
|| context.backingStorePixelRatio
|| 1;
return devicePixelRatio / backingStoreRatio;
})() : 1;
/**
* Canvas Renderer constructor
* @constructor
* @abstract
* @memberof Kinetic
* @param {Number} width
* @param {Number} height
* @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings
* on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
* of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio
* of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
* ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
* specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
* ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
*/
Kinetic.Canvas = function(config) {
this.init(config);
};
Kinetic.Canvas.prototype = {
init: function(config) {
config = config || {};
var pixelRatio = config.pixelRatio || Kinetic.pixelRatio || _pixelRatio;
this.pixelRatio = pixelRatio;
this._canvas = Kinetic.Util.createCanvasElement();
// set inline styles
this._canvas.style.padding = 0;
this._canvas.style.margin = 0;
this._canvas.style.border = 0;
this._canvas.style.background = 'transparent';
this._canvas.style.position = 'absolute';
this._canvas.style.top = 0;
this._canvas.style.left = 0;
},
/**
* get canvas context
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {CanvasContext} context
*/
getContext: function() {
return this.context;
},
/**
* get pixel ratio
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} pixel ratio
*/
getPixelRatio: function() {
return this.pixelRatio;
},
/**
* get pixel ratio
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings
* on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
* of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio
* of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
* ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
* specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
* ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
*/
setPixelRatio: function(pixelRatio) {
this.pixelRatio = pixelRatio;
this.setSize(this.getWidth(), this.getHeight());
},
/**
* set width
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} width
*/
setWidth: function(width) {
// take into account pixel ratio
this.width = this._canvas.width = width * this.pixelRatio;
this._canvas.style.width = width + 'px';
},
/**
* set height
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} height
*/
setHeight: function(height) {
// take into account pixel ratio
this.height = this._canvas.height = height * this.pixelRatio;
this._canvas.style.height = height + 'px';
},
/**
* get width
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} width
*/
getWidth: function() {
return this.width;
},
/**
* get height
* @method
* @memberof Kinetic.Canvas.prototype
* @returns {Number} height
*/
getHeight: function() {
return this.height;
},
/**
* set size
* @method
* @memberof Kinetic.Canvas.prototype
* @param {Number} width
* @param {Number} height
*/
setSize: function(width, height) {
this.setWidth(width);
this.setHeight(height);
},
/**
* to data url
* @method
* @memberof Kinetic.Canvas.prototype
* @param {String} mimeType
* @param {Number} quality between 0 and 1 for jpg mime types
* @returns {String} data url string
*/
toDataURL: function(mimeType, quality) {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return this._canvas.toDataURL(mimeType, quality);
}
catch(e) {
try {
return this._canvas.toDataURL();
}
catch(err) {
Kinetic.Util.warn('Unable to get data URL. ' + err.message);
return '';
}
}
}
};
Kinetic.SceneCanvas = function(config) {
config = config || {};
var width = config.width || 0,
height = config.height || 0;
Kinetic.Canvas.call(this, config);
this.context = new Kinetic.SceneContext(this);
this.setSize(width, height);
};
Kinetic.SceneCanvas.prototype = {
setWidth: function(width) {
var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
Kinetic.Canvas.prototype.setWidth.call(this, width);
_context.scale(pixelRatio, pixelRatio);
},
setHeight: function(height) {
var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
Kinetic.Canvas.prototype.setHeight.call(this, height);
_context.scale(pixelRatio, pixelRatio);
}
};
Kinetic.Util.extend(Kinetic.SceneCanvas, Kinetic.Canvas);
Kinetic.HitCanvas = function(config) {
config = config || {};
var width = config.width || 0,
height = config.height || 0;
Kinetic.Canvas.call(this, config);
this.context = new Kinetic.HitContext(this);
this.setSize(width, height);
};
Kinetic.Util.extend(Kinetic.HitCanvas, Kinetic.Canvas);
})();
;(function() {
var COMMA = ',',
OPEN_PAREN = '(',
CLOSE_PAREN = ')',
OPEN_PAREN_BRACKET = '([',
CLOSE_BRACKET_PAREN = '])',
SEMICOLON = ';',
DOUBLE_PAREN = '()',
// EMPTY_STRING = '',
EQUALS = '=',
// SET = 'set',
CONTEXT_METHODS = [
'arc',
'arcTo',
'beginPath',
'bezierCurveTo',
'clearRect',
'clip',
'closePath',
'createLinearGradient',
'createPattern',
'createRadialGradient',
'drawImage',
'fill',
'fillText',
'getImageData',
'createImageData',
'lineTo',
'moveTo',
'putImageData',
'quadraticCurveTo',
'rect',
'restore',
'rotate',
'save',
'scale',
'setLineDash',
'setTransform',
'stroke',
'strokeText',
'transform',
'translate'
];
/**
* Canvas Context constructor
* @constructor
* @abstract
* @memberof Kinetic
*/
Kinetic.Context = function(canvas) {
this.init(canvas);
};
Kinetic.Context.prototype = {
init: function(canvas) {
this.canvas = canvas;
this._context = canvas._canvas.getContext('2d');
if (Kinetic.enableTrace) {
this.traceArr = [];
this._enableTrace();
}
},
/**
* fill shape
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
fillShape: function(shape) {
if(shape.getFillEnabled()) {
this._fill(shape);
}
},
/**
* stroke shape
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
strokeShape: function(shape) {
if(shape.getStrokeEnabled()) {
this._stroke(shape);
}
},
/**
* fill then stroke
* @method
* @memberof Kinetic.Context.prototype
* @param {Kinetic.Shape} shape
*/
fillStrokeShape: function(shape) {
var fillEnabled = shape.getFillEnabled();
if(fillEnabled) {
this._fill(shape);
}
if(shape.getStrokeEnabled()) {
this._stroke(shape);
}
},
/**
* get context trace if trace is enabled
* @method
* @memberof Kinetic.Context.prototype
* @param {Boolean} relaxed if false, return strict context trace, which includes method names, method parameters
* properties, and property values. If true, return relaxed context trace, which only returns method names and
* properites.
* @returns {String}
*/
getTrace: function(relaxed) {
var traceArr = this.traceArr,
len = traceArr.length,
str = '',
n, trace, method, args;
for (n=0; n<len; n++) {
trace = traceArr[n];
method = trace.method;
// methods
if (method) {
args = trace.args;
str += method;
if (relaxed) {
str += DOUBLE_PAREN;
}
else {
if (Kinetic.Util._isArray(args[0])) {
str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN;
}
else {
str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN;
}
}
}
// properties
else {
str += trace.property;
if (!relaxed) {
str += EQUALS + trace.val;
}
}
str += SEMICOLON;
}
return str;
},
/**
* clear trace if trace is enabled
* @method
* @memberof Kinetic.Context.prototype
*/
clearTrace: function() {
this.traceArr = [];
},
_trace: function(str) {
var traceArr = this.traceArr,
len;
traceArr.push(str);
len = traceArr.length;
if (len >= Kinetic.traceArrMax) {
traceArr.shift();
}
},
/**
* reset canvas context transform
* @method
* @memberof Kinetic.Context.prototype
*/
reset: function() {
var pixelRatio = this.getCanvas().getPixelRatio();
this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0);
},
/**
* get canvas
* @method
* @memberof Kinetic.Context.prototype
* @returns {Kinetic.Canvas}
*/
getCanvas: function() {
return this.canvas;
},
/**
* clear canvas
* @method
* @memberof Kinetic.Context.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
*/
clear: function(bounds) {
var canvas = this.getCanvas();
if (bounds) {
this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0);
}
else {
this.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
},
_applyLineCap: function(shape) {
var lineCap = shape.getLineCap();
if(lineCap) {
this.setAttr('lineCap', lineCap);
}
},
_applyOpacity: function(shape) {
var absOpacity = shape.getAbsoluteOpacity();
if(absOpacity !== 1) {
this.setAttr('globalAlpha', absOpacity);
}
},
_applyLineJoin: function(shape) {
var lineJoin = shape.getLineJoin();
if(lineJoin) {
this.setAttr('lineJoin', lineJoin);
}
},
setAttr: function(attr, val) {
this._context[attr] = val;
},
// context pass through methods
arc: function() {
var a = arguments;
this._context.arc(a[0], a[1], a[2], a[3], a[4], a[5]);
},
beginPath: function() {
this._context.beginPath();
},
bezierCurveTo: function() {
var a = arguments;
this._context.bezierCurveTo(a[0], a[1], a[2], a[3], a[4], a[5]);
},
clearRect: function() {
var a = arguments;
this._context.clearRect(a[0], a[1], a[2], a[3]);
},
clip: function() {
this._context.clip();
},
closePath: function() {
this._context.closePath();
},
createImageData: function() {
var a = arguments;
if(a.length === 2) {
return this._context.createImageData(a[0], a[1]);
}
else if(a.length === 1) {
return this._context.createImageData(a[0]);
}
},
createLinearGradient: function() {
var a = arguments;
return this._context.createLinearGradient(a[0], a[1], a[2], a[3]);
},
createPattern: function() {
var a = arguments;
return this._context.createPattern(a[0], a[1]);
},
createRadialGradient: function() {
var a = arguments;
return this._context.createRadialGradient(a[0], a[1], a[2], a[3], a[4], a[5]);
},
drawImage: function() {
var a = arguments,
_context = this._context;
if(a.length === 3) {
_context.drawImage(a[0], a[1], a[2]);
}
else if(a.length === 5) {
_context.drawImage(a[0], a[1], a[2], a[3], a[4]);
}
else if(a.length === 9) {
_context.drawImage(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
}
},
fill: function() {
this._context.fill();
},
fillText: function() {
var a = arguments;
this._context.fillText(a[0], a[1], a[2]);
},
getImageData: function() {
var a = arguments;
return this._context.getImageData(a[0], a[1], a[2], a[3]);
},
lineTo: function() {
var a = arguments;
this._context.lineTo(a[0], a[1]);
},
moveTo: function() {
var a = arguments;
this._context.moveTo(a[0], a[1]);
},
rect: function() {
var a = arguments;
this._context.rect(a[0], a[1], a[2], a[3]);
},
putImageData: function() {
var a = arguments;
this._context.putImageData(a[0], a[1], a[2]);
},
quadraticCurveTo: function() {
var a = arguments;
this._context.quadraticCurveTo(a[0], a[1], a[2], a[3]);
},
restore: function() {
this._context.restore();
},
rotate: function() {
var a = arguments;
this._context.rotate(a[0]);
},
save: function() {
this._context.save();
},
scale: function() {
var a = arguments;
this._context.scale(a[0], a[1]);
},
setLineDash: function() {
var a = arguments,
_context = this._context;
// works for Chrome and IE11
if(this._context.setLineDash) {
_context.setLineDash(a[0]);
}
// verified that this works in firefox
else if('mozDash' in _context) {
_context.mozDash = a[0];
}
// does not currently work for Safari
else if('webkitLineDash' in _context) {
_context.webkitLineDash = a[0];
}
// no support for IE9 and IE10
},
setTransform: function() {
var a = arguments;
this._context.setTransform(a[0], a[1], a[2], a[3], a[4], a[5]);
},
stroke: function() {
this._context.stroke();
},
strokeText: function() {
var a = arguments;
this._context.strokeText(a[0], a[1], a[2]);
},
transform: function() {
var a = arguments;
this._context.transform(a[0], a[1], a[2], a[3], a[4], a[5]);
},
translate: function() {
var a = arguments;
this._context.translate(a[0], a[1]);
},
_enableTrace: function() {
var that = this,
len = CONTEXT_METHODS.length,
_simplifyArray = Kinetic.Util._simplifyArray,
origSetter = this.setAttr,
n, args;
// to prevent creating scope function at each loop
var func = function(methodName) {
var origMethod = that[methodName],
ret;
that[methodName] = function() {
args = _simplifyArray(Array.prototype.slice.call(arguments, 0));
ret = origMethod.apply(that, arguments);
that._trace({
method: methodName,
args: args
});
return ret;
};
};
// methods
for (n=0; n<len; n++) {
func(CONTEXT_METHODS[n]);
}
// attrs
that.setAttr = function() {
origSetter.apply(that, arguments);
that._trace({
property: arguments[0],
val: arguments[1]
});
};
}
};
Kinetic.SceneContext = function(canvas) {
Kinetic.Context.call(this, canvas);
};
Kinetic.SceneContext.prototype = {
_fillColor: function(shape) {
var fill = shape.fill()
|| Kinetic.Util._getRGBAString({
red: shape.fillRed(),
green: shape.fillGreen(),
blue: shape.fillBlue(),
alpha: shape.fillAlpha()
});
this.setAttr('fillStyle', fill);
shape._fillFunc(this);
},
_fillPattern: function(shape) {
var fillPatternImage = shape.getFillPatternImage(),
fillPatternX = shape.getFillPatternX(),
fillPatternY = shape.getFillPatternY(),
fillPatternScale = shape.getFillPatternScale(),
fillPatternRotation = Kinetic.getAngle(shape.getFillPatternRotation()),
fillPatternOffset = shape.getFillPatternOffset(),
fillPatternRepeat = shape.getFillPatternRepeat();
if(fillPatternX || fillPatternY) {
this.translate(fillPatternX || 0, fillPatternY || 0);
}
if(fillPatternRotation) {
this.rotate(fillPatternRotation);
}
if(fillPatternScale) {
this.scale(fillPatternScale.x, fillPatternScale.y);
}
if(fillPatternOffset) {
this.translate(-1 * fillPatternOffset.x, -1 * fillPatternOffset.y);
}
this.setAttr('fillStyle', this.createPattern(fillPatternImage, fillPatternRepeat || 'repeat'));
this.fill();
},
_fillLinearGradient: function(shape) {
var start = shape.getFillLinearGradientStartPoint(),
end = shape.getFillLinearGradientEndPoint(),
colorStops = shape.getFillLinearGradientColorStops(),
grd = this.createLinearGradient(start.x, start.y, end.x, end.y);
if (colorStops) {
// build color stops
for(var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
this.setAttr('fillStyle', grd);
this.fill();
}
},
_fillRadialGradient: function(shape) {
var start = shape.getFillRadialGradientStartPoint(),
end = shape.getFillRadialGradientEndPoint(),
startRadius = shape.getFillRadialGradientStartRadius(),
endRadius = shape.getFillRadialGradientEndRadius(),
colorStops = shape.getFillRadialGradientColorStops(),
grd = this.createRadialGradient(start.x, start.y, startRadius, end.x, end.y, endRadius);
// build color stops
for(var n = 0; n < colorStops.length; n += 2) {
grd.addColorStop(colorStops[n], colorStops[n + 1]);
}
this.setAttr('fillStyle', grd);
this.fill();
},
_fill: function(shape) {
var hasColor = shape.fill() || shape.fillRed() || shape.fillGreen() || shape.fillBlue(),
hasPattern = shape.getFillPatternImage(),
hasLinearGradient = shape.getFillLinearGradientColorStops(),
hasRadialGradient = shape.getFillRadialGradientColorStops(),
fillPriority = shape.getFillPriority();
// priority fills
if(hasColor && fillPriority === 'color') {
this._fillColor(shape);
}
else if(hasPattern && fillPriority === 'pattern') {
this._fillPattern(shape);
}
else if(hasLinearGradient && fillPriority === 'linear-gradient') {
this._fillLinearGradient(shape);
}
else if(hasRadialGradient && fillPriority === 'radial-gradient') {
this._fillRadialGradient(shape);
}
// now just try and fill with whatever is available
else if(hasColor) {
this._fillColor(shape);
}
else if(hasPattern) {
this._fillPattern(shape);
}
else if(hasLinearGradient) {
this._fillLinearGradient(shape);
}
else if(hasRadialGradient) {
this._fillRadialGradient(shape);
}
},
_stroke: function(shape) {
var dash = shape.dash(),
strokeScaleEnabled = shape.getStrokeScaleEnabled();
if(shape.hasStroke()) {
if (!strokeScaleEnabled) {
this.save();
this.setTransform(1, 0, 0, 1, 0, 0);
}
this._applyLineCap(shape);
if(dash && shape.dashEnabled()) {
this.setLineDash(dash);
}
this.setAttr('lineWidth', shape.strokeWidth());
this.setAttr('strokeStyle', shape.stroke()
|| Kinetic.Util._getRGBAString({
red: shape.strokeRed(),
green: shape.strokeGreen(),
blue: shape.strokeBlue(),
alpha: shape.strokeAlpha()
}));
shape._strokeFunc(this);
if (!strokeScaleEnabled) {
this.restore();
}
}
},
_applyShadow: function(shape) {
var util = Kinetic.Util,
absOpacity = shape.getAbsoluteOpacity(),
color = util.get(shape.getShadowColor(), 'black'),
blur = util.get(shape.getShadowBlur(), 5),
shadowOpacity = util.get(shape.getShadowOpacity(), 1),
offset = util.get(shape.getShadowOffset(), {
x: 0,
y: 0
});
if(shadowOpacity) {
this.setAttr('globalAlpha', shadowOpacity * absOpacity);
}
this.setAttr('shadowColor', color);
this.setAttr('shadowBlur', blur);
this.setAttr('shadowOffsetX', offset.x);
this.setAttr('shadowOffsetY', offset.y);
}
};
Kinetic.Util.extend(Kinetic.SceneContext, Kinetic.Context);
Kinetic.HitContext = function(canvas) {
Kinetic.Context.call(this, canvas);
};
Kinetic.HitContext.prototype = {
_fill: function(shape) {
this.save();
this.setAttr('fillStyle', shape.colorKey);
shape._fillFuncHit(this);
this.restore();
},
_stroke: function(shape) {
if(shape.hasStroke()) {
this._applyLineCap(shape);
this.setAttr('lineWidth', shape.strokeWidth());
this.setAttr('strokeStyle', shape.colorKey);
shape._strokeFuncHit(this);
}
}
};
Kinetic.Util.extend(Kinetic.HitContext, Kinetic.Context);
})();
;/*jshint unused:false */
(function() {
// CONSTANTS
var ABSOLUTE_OPACITY = 'absoluteOpacity',
ABSOLUTE_TRANSFORM = 'absoluteTransform',
ADD = 'add',
B = 'b',
BEFORE = 'before',
BLACK = 'black',
CHANGE = 'Change',
CHILDREN = 'children',
DEG = 'Deg',
DOT = '.',
EMPTY_STRING = '',
G = 'g',
GET = 'get',
HASH = '#',
ID = 'id',
KINETIC = 'kinetic',
LISTENING = 'listening',
MOUSEENTER = 'mouseenter',
MOUSELEAVE = 'mouseleave',
NAME = 'name',
OFF = 'off',
ON = 'on',
PRIVATE_GET = '_get',
R = 'r',
RGB = 'RGB',
SET = 'set',
SHAPE = 'Shape',
SPACE = ' ',
STAGE = 'Stage',
TRANSFORM = 'transform',
UPPER_B = 'B',
UPPER_G = 'G',
UPPER_HEIGHT = 'Height',
UPPER_R = 'R',
UPPER_WIDTH = 'Width',
UPPER_X = 'X',
UPPER_Y = 'Y',
VISIBLE = 'visible',
X = 'x',
Y = 'y';
Kinetic.Factory = {
addGetterSetter: function(constructor, attr, def, validator, after) {
this.addGetter(constructor, attr, def);
this.addSetter(constructor, attr, validator, after);
this.addOverloadedGetterSetter(constructor, attr);
},
addGetter: function(constructor, attr, def) {
var method = GET + Kinetic.Util._capitalize(attr);
constructor.prototype[method] = function() {
var val = this.attrs[attr];
return val === undefined ? def : val;
};
},
addSetter: function(constructor, attr, validator, after) {
var method = SET + Kinetic.Util._capitalize(attr);
constructor.prototype[method] = function(val) {
if (validator) {
val = validator.call(this, val);
}
this._setAttr(attr, val);
if (after) {
after.call(this);
}
return this;
};
},
addComponentsGetterSetter: function(constructor, attr, components, validator, after) {
var len = components.length,
capitalize = Kinetic.Util._capitalize,
getter = GET + capitalize(attr),
setter = SET + capitalize(attr),
n, component;
// getter
constructor.prototype[getter] = function() {
var ret = {};
for (n=0; n<len; n++) {
component = components[n];
ret[component] = this.getAttr(attr + capitalize(component));
}
return ret;
};
// setter
constructor.prototype[setter] = function(val) {
var oldVal = this.attrs[attr],
key;
if (validator) {
val = validator.call(this, val);
}
for (key in val) {
this._setAttr(attr + capitalize(key), val[key]);
}
this._fireChangeEvent(attr, oldVal, val);
if (after) {
after.call(this);
}
return this;
};
this.addOverloadedGetterSetter(constructor, attr);
},
addOverloadedGetterSetter: function(constructor, attr) {
var capitalizedAttr = Kinetic.Util._capitalize(attr),
setter = SET + capitalizedAttr,
getter = GET + capitalizedAttr;
constructor.prototype[attr] = function() {
// setting
if (arguments.length) {
this[setter](arguments[0]);
return this;
}
// getting
else {
return this[getter]();
}
};
},
backCompat: function(constructor, methods) {
var key;
for (key in methods) {
constructor.prototype[key] = constructor.prototype[methods[key]];
}
},
afterSetFilter: function() {
this._filterUpToDate = false;
}
};
Kinetic.Validators = {
RGBComponent: function(val) {
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
},
alphaComponent: function(val) {
if (val > 1) {
return 1;
}
// chrome does not honor alpha values of 0
else if (val < 0.0001) {
return 0.0001;
}
else {
return val;
}
}
};
})();;(function() {
// CONSTANTS
var ABSOLUTE_OPACITY = 'absoluteOpacity',
ABSOLUTE_TRANSFORM = 'absoluteTransform',
BEFORE = 'before',
CHANGE = 'Change',
CHILDREN = 'children',
DOT = '.',
EMPTY_STRING = '',
GET = 'get',
ID = 'id',
KINETIC = 'kinetic',
LISTENING = 'listening',
MOUSEENTER = 'mouseenter',
MOUSELEAVE = 'mouseleave',
NAME = 'name',
SET = 'set',
SHAPE = 'Shape',
SPACE = ' ',
STAGE = 'stage',
TRANSFORM = 'transform',
UPPER_STAGE = 'Stage',
VISIBLE = 'visible',
CLONE_BLACK_LIST = ['id'],
TRANSFORM_CHANGE_STR = [
'xChange.kinetic',
'yChange.kinetic',
'scaleXChange.kinetic',
'scaleYChange.kinetic',
'skewXChange.kinetic',
'skewYChange.kinetic',
'rotationChange.kinetic',
'offsetXChange.kinetic',
'offsetYChange.kinetic',
'transformsEnabledChange.kinetic'
].join(SPACE);
Kinetic.Util.addMethods(Kinetic.Node, {
_init: function(config) {
var that = this;
this._id = Kinetic.idCounter++;
this.eventListeners = {};
this.attrs = {};
this._cache = {};
this._filterUpToDate = false;
this.setAttrs(config);
// event bindings for cache handling
this.on(TRANSFORM_CHANGE_STR, function() {
this._clearCache(TRANSFORM);
that._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
});
this.on('visibleChange.kinetic', function() {
that._clearSelfAndDescendantCache(VISIBLE);
});
this.on('listeningChange.kinetic', function() {
that._clearSelfAndDescendantCache(LISTENING);
});
this.on('opacityChange.kinetic', function() {
that._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
});
},
_clearCache: function(attr){
if (attr) {
delete this._cache[attr];
}
else {
this._cache = {};
}
},
_getCache: function(attr, privateGetter){
var cache = this._cache[attr];
// if not cached, we need to set it using the private getter method.
if (cache === undefined) {
this._cache[attr] = privateGetter.call(this);
}
return this._cache[attr];
},
/*
* when the logic for a cached result depends on ancestor propagation, use this
* method to clear self and children cache
*/
_clearSelfAndDescendantCache: function(attr) {
this._clearCache(attr);
if (this.children) {
this.getChildren().each(function(node) {
node._clearSelfAndDescendantCache(attr);
});
}
},
/**
* clear cached canvas
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
* @example
* node.clearCache();
*/
clearCache: function() {
delete this._cache.canvas;
this._filterUpToDate = false;
return this;
},
/**
* cache node to improve drawing performance, apply filters, or create more accurate
* hit regions
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.drawBorder] when set to true, a red border will be drawn around the cached
* region for debugging purposes
* @returns {Kinetic.Node}
* @example
* // cache a shape with the x,y position of the bounding box at the center and<br>
* // the width and height of the bounding box equal to the width and height of<br>
* // the shape obtained from shape.width() and shape.height()<br>
* image.cache();<br><br>
*
* // cache a node and define the bounding box position and size<br>
* node.cache({<br>
* x: -30,<br>
* y: -30,<br>
* width: 100,<br>
* height: 200<br>
* });<br><br>
*
* // cache a node and draw a red border around the bounding box<br>
* // for debugging purposes<br>
* node.cache({<br>
* x: -30,<br>
* y: -30,<br>
* width: 100,<br>
* height: 200,<br>
* drawBorder: true<br>
* });
*/
cache: function(config) {
var conf = config || {},
x = conf.x || 0,
y = conf.y || 0,
width = conf.width || this.width(),
height = conf.height || this.height(),
drawBorder = conf.drawBorder || false,
layer = this.getLayer();
if (width === 0 || height === 0) {
Kinetic.Util.warn('Width or height of caching configuration equals 0. Cache is ignored.');
return;
}
var cachedSceneCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1,
width: width,
height: height
}),
cachedFilterCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1,
width: width,
height: height
}),
cachedHitCanvas = new Kinetic.HitCanvas({
width: width,
height: height
}),
origTransEnabled = this.transformsEnabled(),
origX = this.x(),
origY = this.y(),
sceneContext = cachedSceneCanvas.getContext(),
hitContext = cachedHitCanvas.getContext();
this.clearCache();
sceneContext.save();
hitContext.save();
// this will draw a red border around the cached box for
// debugging purposes
if (drawBorder) {
sceneContext.save();
sceneContext.beginPath();
sceneContext.rect(0, 0, width, height);
sceneContext.closePath();
sceneContext.setAttr('strokeStyle', 'red');
sceneContext.setAttr('lineWidth', 5);
sceneContext.stroke();
sceneContext.restore();
}
sceneContext.translate(x * -1, y * -1);
hitContext.translate(x * -1, y * -1);
if (this.nodeType === 'Shape') {
sceneContext.translate(this.x() * -1, this.y() * -1);
hitContext.translate(this.x() * -1, this.y() * -1);
}
this.drawScene(cachedSceneCanvas, this);
this.drawHit(cachedHitCanvas, this);
sceneContext.restore();
hitContext.restore();
this._cache.canvas = {
scene: cachedSceneCanvas,
filter: cachedFilterCanvas,
hit: cachedHitCanvas
};
return this;
},
_drawCachedSceneCanvas: function(context) {
context.save();
this.getLayer()._applyTransform(this, context);
context.drawImage(this._getCachedSceneCanvas()._canvas, 0, 0);
context.restore();
},
_getCachedSceneCanvas: function() {
var filters = this.filters(),
cachedCanvas = this._cache.canvas,
sceneCanvas = cachedCanvas.scene,
filterCanvas = cachedCanvas.filter,
filterContext = filterCanvas.getContext(),
len, imageData, n, filter;
if (filters) {
if (!this._filterUpToDate) {
try {
len = filters.length;
filterContext.clear();
// copy cached canvas onto filter context
filterContext.drawImage(sceneCanvas._canvas, 0, 0);
imageData = filterContext.getImageData(0, 0, filterCanvas.getWidth(), filterCanvas.getHeight());
// apply filters to filter context
for (n=0; n<len; n++) {
filter = filters[n];
filter.call(this, imageData);
filterContext.putImageData(imageData, 0, 0);
}
}
catch(e) {
Kinetic.Util.warn('Unable to apply filter. ' + e.message);
}
this._filterUpToDate = true;
}
return filterCanvas;
}
else {
return sceneCanvas;
}
},
_drawCachedHitCanvas: function(context) {
var cachedCanvas = this._cache.canvas,
hitCanvas = cachedCanvas.hit;
context.save();
this.getLayer()._applyTransform(this, context);
context.drawImage(hitCanvas._canvas, 0, 0);
context.restore();
},
/**
* bind events to the node. KineticJS supports mouseover, mousemove,
* mouseout, mouseenter, mouseleave, mousedown, mouseup, click, dblclick, touchstart, touchmove,
* touchend, tap, dbltap, dragstart, dragmove, and dragend events. The Kinetic Stage supports
* contentMouseover, contentMousemove, contentMouseout, contentMousedown, contentMouseup,
* contentClick, contentDblclick, contentTouchstart, contentTouchmove, contentTouchend, contentTap,
* and contentDblTap. Pass in a string of events delimmited by a space to bind multiple events at once
* such as 'mousedown mouseup mousemove'. Include a namespace to bind an
* event by name such as 'click.foobar'.
* @method
* @memberof Kinetic.Node.prototype
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'
* @param {Function} handler The handler function is passed an event object
* @returns {Kinetic.Node}
* @example
* // add click listener<br>
* node.on('click', function() {<br>
* console.log('you clicked me!');<br>
* });<br><br>
*
* // get the target node<br>
* node.on('click', function(evt) {<br>
* console.log(evt.target);<br>
* });<br><br>
*
* // stop event propagation<br>
* node.on('click', function(evt) {<br>
* evt.cancelBubble = true;<br>
* });<br><br>
*
* // bind multiple listeners<br>
* node.on('click touchstart', function() {<br>
* console.log('you clicked/touched me!');<br>
* });<br><br>
*
* // namespace listener<br>
* node.on('click.foo', function() {<br>
* console.log('you clicked/touched me!');<br>
* });<br><br>
*
* // get the event type<br>
* node.on('click tap', function(evt) {<br>
* var eventType = evt.type;<br>
* });<br><br>
*
* // get native event object<br>
* node.on('click tap', function(evt) {<br>
* var nativeEvent = evt.evt;<br>
* });<br><br>
*
* // for change events, get the old and new val<br>
* node.on('xChange', function(evt) {<br>
* var oldVal = evt.oldVal;<br>
* var newVal = evt.newVal;<br>
* });
*/
on: function(evtStr, handler) {
var events = evtStr.split(SPACE),
len = events.length,
n, event, parts, baseEvent, name;
/*
* loop through types and attach event listeners to
* each one. eg. 'click mouseover.namespace mouseout'
* will create three event bindings
*/
for(n = 0; n < len; n++) {
event = events[n];
parts = event.split(DOT);
baseEvent = parts[0];
name = parts[1] || EMPTY_STRING;
// create events array if it doesn't exist
if(!this.eventListeners[baseEvent]) {
this.eventListeners[baseEvent] = [];
}
this.eventListeners[baseEvent].push({
name: name,
handler: handler
});
// NOTE: this flag is set to true when any event handler is added, even non
// mouse or touch gesture events. This improves performance for most
// cases where users aren't using events, but is still very light weight.
// To ensure perfect accuracy, devs can explicitly set listening to false.
/*
if (name !== KINETIC) {
this._listeningEnabled = true;
this._clearSelfAndAncestorCache(LISTENING_ENABLED);
}
*/
}
return this;
},
/**
* remove event bindings from the node. Pass in a string of
* event types delimmited by a space to remove multiple event
* bindings at once such as 'mousedown mouseup mousemove'.
* include a namespace to remove an event binding by name
* such as 'click.foobar'. If you only give a name like '.foobar',
* all events in that namespace will be removed.
* @method
* @memberof Kinetic.Node.prototype
* @param {String} evtStr e.g. 'click', 'mousedown touchstart', '.foobar'
* @returns {Kinetic.Node}
* @example
* // remove listener<br>
* node.off('click');<br><br>
*
* // remove multiple listeners<br>
* node.off('click touchstart');<br><br>
*
* // remove listener by name<br>
* node.off('click.foo');
*/
off: function(evtStr) {
var events = evtStr.split(SPACE),
len = events.length,
n, t, event, parts, baseEvent, name;
for(n = 0; n < len; n++) {
event = events[n];
parts = event.split(DOT);
baseEvent = parts[0];
name = parts[1];
if(baseEvent) {
if(this.eventListeners[baseEvent]) {
this._off(baseEvent, name);
}
}
else {
for(t in this.eventListeners) {
this._off(t, name);
}
}
}
return this;
},
// some event aliases for third party integration like HammerJS
dispatchEvent: function(evt) {
var e = {
target: this,
type: evt.type,
evt: evt
};
this.fire(evt.type, e);
},
addEventListener: function(type, handler) {
// we to pass native event to handler
this.on(type, function(evt){
handler.call(this, evt.evt);
});
},
/**
* remove self from parent, but don't destroy
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
* @example
* node.remove();
*/
remove: function() {
var parent = this.getParent();
if(parent && parent.children) {
parent.children.splice(this.index, 1);
parent._setChildrenIndices();
delete this.parent;
}
// every cached attr that is calculated via node tree
// traversal must be cleared when removing a node
this._clearSelfAndDescendantCache(STAGE);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
this._clearSelfAndDescendantCache(VISIBLE);
this._clearSelfAndDescendantCache(LISTENING);
this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
return this;
},
/**
* remove and destroy self
* @method
* @memberof Kinetic.Node.prototype
* @example
* node.destroy();
*/
destroy: function() {
// remove from ids and names hashes
Kinetic._removeId(this.getId());
Kinetic._removeName(this.getName(), this._id);
this.remove();
},
/**
* get attr
* @method
* @memberof Kinetic.Node.prototype
* @param {String} attr
* @returns {Integer|String|Object|Array}
* @example
* var x = node.getAttr('x');
*/
getAttr: function(attr) {
var method = GET + Kinetic.Util._capitalize(attr);
if(Kinetic.Util._isFunction(this[method])) {
return this[method]();
}
// otherwise get directly
else {
return this.attrs[attr];
}
},
/**
* get ancestors
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Collection}
* @example
* shape.getAncestors().each(function(node) {
* console.log(node.getId());
* })
*/
getAncestors: function() {
var parent = this.getParent(),
ancestors = new Kinetic.Collection();
while (parent) {
ancestors.push(parent);
parent = parent.getParent();
}
return ancestors;
},
/**
* get attrs object literal
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
getAttrs: function() {
return this.attrs || {};
},
/**
* set multiple attrs at once using an object literal
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config object containing key value pairs
* @returns {Kinetic.Node}
* @example
* node.setAttrs({<br>
* x: 5,<br>
* fill: 'red'<br>
* });<br>
*/
setAttrs: function(config) {
var key, method;
if(config) {
for(key in config) {
if (key === CHILDREN) {
}
else {
method = SET + Kinetic.Util._capitalize(key);
// use setter if available
if(Kinetic.Util._isFunction(this[method])) {
this[method](config[key]);
}
// otherwise set directly
else {
this._setAttr(key, config[key]);
}
}
}
}
return this;
},
/**
* determine if node is listening for events by taking into account ancestors.
*
* Parent | Self | isListening
* listening | listening |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | T
* F | F | F
* ----------+-----------+------------
* T | I | T
* F | I | F
* I | I | T
*
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
isListening: function() {
return this._getCache(LISTENING, this._isListening);
},
_isListening: function() {
var listening = this.getListening(),
parent = this.getParent();
// the following conditions are a simplification of the truth table above.
// please modify carefully
if (listening === 'inherit') {
if (parent) {
return parent.isListening();
}
else {
return true;
}
}
else {
return listening;
}
},
/**
* determine if node is visible by taking into account ancestors.
*
* Parent | Self | isVisible
* visible | visible |
* ----------+-----------+------------
* T | T | T
* T | F | F
* F | T | T
* F | F | F
* ----------+-----------+------------
* T | I | T
* F | I | F
* I | I | T
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
isVisible: function() {
return this._getCache(VISIBLE, this._isVisible);
},
_isVisible: function() {
var visible = this.getVisible(),
parent = this.getParent();
// the following conditions are a simplification of the truth table above.
// please modify carefully
if (visible === 'inherit') {
if (parent) {
return parent.isVisible();
}
else {
return true;
}
}
else {
return visible;
}
},
/**
* determine if listening is enabled by taking into account descendants. If self or any children
* have _isListeningEnabled set to true, then self also has listening enabled.
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
shouldDrawHit: function() {
var layer = this.getLayer();
return layer && layer.hitGraphEnabled() && this.isListening() && this.isVisible() && !Kinetic.isDragging();
},
/**
* show node
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
show: function() {
this.setVisible(true);
return this;
},
/**
* hide node. Hidden nodes are no longer detectable
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
hide: function() {
this.setVisible(false);
return this;
},
/**
* get zIndex relative to the node's siblings who share the same parent
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getZIndex: function() {
return this.index || 0;
},
/**
* get absolute z-index which takes into account sibling
* and ancestor indices
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getAbsoluteZIndex: function() {
var depth = this.getDepth(),
that = this,
index = 0,
nodes, len, n, child;
function addChildren(children) {
nodes = [];
len = children.length;
for(n = 0; n < len; n++) {
child = children[n];
index++;
if(child.nodeType !== SHAPE) {
nodes = nodes.concat(child.getChildren().toArray());
}
if(child._id === that._id) {
n = len;
}
}
if(nodes.length > 0 && nodes[0].getDepth() <= depth) {
addChildren(nodes);
}
}
if(that.nodeType !== UPPER_STAGE) {
addChildren(that.getStage().getChildren());
}
return index;
},
/**
* get node depth in node tree. Returns an integer.<br><br>
* e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always
* be >= 2
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getDepth: function() {
var depth = 0,
parent = this.parent;
while(parent) {
depth++;
parent = parent.parent;
}
return depth;
},
setPosition: function(pos) {
this.setX(pos.x);
this.setY(pos.y);
return this;
},
getPosition: function() {
return {
x: this.getX(),
y: this.getY()
};
},
/**
* get absolute position relative to the top left corner of the stage container div
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
getAbsolutePosition: function() {
var absoluteMatrix = this.getAbsoluteTransform().getMatrix(),
absoluteTransform = new Kinetic.Transform(),
offset = this.offset();
// clone the matrix array
absoluteTransform.m = absoluteMatrix.slice();
absoluteTransform.translate(offset.x, offset.y);
return absoluteTransform.getTranslation();
},
/**
* set absolute position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Node}
*/
setAbsolutePosition: function(pos) {
var origTrans = this._clearTransform(),
it;
// don't clear translation
this.attrs.x = origTrans.x;
this.attrs.y = origTrans.y;
delete origTrans.x;
delete origTrans.y;
// unravel transform
it = this.getAbsoluteTransform();
it.invert();
it.translate(pos.x, pos.y);
pos = {
x: this.attrs.x + it.getTranslation().x,
y: this.attrs.y + it.getTranslation().y
};
this.setPosition({x:pos.x, y:pos.y});
this._setTransform(origTrans);
return this;
},
_setTransform: function(trans) {
var key;
for(key in trans) {
this.attrs[key] = trans[key];
}
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
},
_clearTransform: function() {
var trans = {
x: this.getX(),
y: this.getY(),
rotation: this.getRotation(),
scaleX: this.getScaleX(),
scaleY: this.getScaleY(),
offsetX: this.getOffsetX(),
offsetY: this.getOffsetY(),
skewX: this.getSkewX(),
skewY: this.getSkewY()
};
this.attrs.x = 0;
this.attrs.y = 0;
this.attrs.rotation = 0;
this.attrs.scaleX = 1;
this.attrs.scaleY = 1;
this.attrs.offsetX = 0;
this.attrs.offsetY = 0;
this.attrs.skewX = 0;
this.attrs.skewY = 0;
this._clearCache(TRANSFORM);
this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
// return original transform
return trans;
},
/**
* move node by an amount relative to its current position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} change
* @param {Number} change.x
* @param {Number} change.y
* @returns {Kinetic.Node}
* @example
* // move node in x direction by 1px and y direction by 2px<br>
* node.move({<br>
* x: 1,<br>
* y: 2)<br>
* });
*/
move: function(change) {
var changeX = change.x,
changeY = change.y,
x = this.getX(),
y = this.getY();
if(changeX !== undefined) {
x += changeX;
}
if(changeY !== undefined) {
y += changeY;
}
this.setPosition({x:x, y:y});
return this;
},
_eachAncestorReverse: function(func, top) {
var family = [],
parent = this.getParent(),
len, n;
// if top node is defined, and this node is top node,
// there's no need to build a family tree. just execute
// func with this because it will be the only node
if (top && top._id === this._id) {
func(this);
return true;
}
family.unshift(this);
while(parent && (!top || parent._id !== top._id)) {
family.unshift(parent);
parent = parent.parent;
}
len = family.length;
for(n = 0; n < len; n++) {
func(family[n]);
}
},
/**
* rotate node by an amount in degrees relative to its current rotation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} theta
* @returns {Kinetic.Node}
*/
rotate: function(theta) {
this.setRotation(this.getRotation() + theta);
return this;
},
/**
* move node to the top of its siblings
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveToTop: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveToTop function is ignored.');
return;
}
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.push(this);
this.parent._setChildrenIndices();
return true;
},
/**
* move node up
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveUp: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveUp function is ignored.');
return;
}
var index = this.index,
len = this.parent.getChildren().length;
if(index < len - 1) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index + 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* move node down
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveDown: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveDown function is ignored.');
return;
}
var index = this.index;
if(index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index - 1, 0, this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* move node to the bottom of its siblings
* @method
* @memberof Kinetic.Node.prototype
* @returns {Boolean}
*/
moveToBottom: function() {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. moveToBottom function is ignored.');
return;
}
var index = this.index;
if(index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.unshift(this);
this.parent._setChildrenIndices();
return true;
}
return false;
},
/**
* set zIndex relative to siblings
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} zIndex
* @returns {Kinetic.Node}
*/
setZIndex: function(zIndex) {
if (!this.parent) {
Kinetic.Util.warn('Node has no parent. zIndex parameter is ignored.');
return;
}
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.splice(zIndex, 0, this);
this.parent._setChildrenIndices();
return this;
},
/**
* get absolute opacity
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
*/
getAbsoluteOpacity: function() {
return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity);
},
_getAbsoluteOpacity: function() {
var absOpacity = this.getOpacity();
if(this.getParent()) {
absOpacity *= this.getParent().getAbsoluteOpacity();
}
return absOpacity;
},
/**
* move node to another container
* @method
* @memberof Kinetic.Node.prototype
* @param {Container} newContainer
* @returns {Kinetic.Node}
* @example
* // move node from current layer into layer2<br>
* node.moveTo(layer2);
*/
moveTo: function(newContainer) {
Kinetic.Node.prototype.remove.call(this);
newContainer.add(this);
return this;
},
/**
* convert Node into an object for serialization. Returns an object.
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
*/
toObject: function() {
var type = Kinetic.Util,
obj = {},
attrs = this.getAttrs(),
key, val, getter, defaultValue;
obj.attrs = {};
// serialize only attributes that are not function, image, DOM, or objects with methods
for(key in attrs) {
val = attrs[key];
if (!type._isFunction(val) && !type._isElement(val) && !(type._isObject(val) && type._hasMethods(val))) {
getter = this[key];
// remove attr value so that we can extract the default value from the getter
delete attrs[key];
defaultValue = getter ? getter.call(this) : null;
// restore attr value
attrs[key] = val;
if (defaultValue !== val) {
obj.attrs[key] = val;
}
}
}
obj.className = this.getClassName();
return obj;
},
/**
* convert Node into a JSON string. Returns a JSON string.
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}}
*/
toJSON: function() {
return JSON.stringify(this.toObject());
},
/**
* get parent container
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
getParent: function() {
return this.parent;
},
/**
* get layer ancestor
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Layer}
*/
getLayer: function() {
var parent = this.getParent();
return parent ? parent.getLayer() : null;
},
/**
* get stage ancestor
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Stage}
*/
getStage: function() {
return this._getCache(STAGE, this._getStage);
},
_getStage: function() {
var parent = this.getParent();
if(parent) {
return parent.getStage();
}
else {
return undefined;
}
},
/**
* fire event
* @method
* @memberof Kinetic.Node.prototype
* @param {String} eventType event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEvent
* @param {EventObject} [evt] event object
* @param {Boolean} [bubble] setting the value to false, or leaving it undefined, will result in the event
* not bubbling. Setting the value to true will result in the event bubbling.
* @returns {Kinetic.Node}
* @example
* // manually fire click event<br>
* node.fire('click');<br><br>
*
* // fire custom event<br>
* node.fire('foo');<br><br>
*
* // fire custom event with custom event object<br>
* node.fire('foo', {<br>
* bar: 10<br>
* });<br><br>
*
* // fire click event that bubbles<br>
* node.fire('click', null, true);
*/
fire: function(eventType, evt, bubble) {
// bubble
if (bubble) {
this._fireAndBubble(eventType, evt || {});
}
// no bubble
else {
this._fire(eventType, evt || {});
}
return this;
},
/**
* get absolute transform of the node which takes into
* account its ancestor transforms
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Transform}
*/
getAbsoluteTransform: function(top) {
// if using an argument, we can't cache the result.
if (top) {
return this._getAbsoluteTransform(top);
}
// if no argument, we can cache the result
else {
return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform);
}
},
_getAbsoluteTransform: function(top) {
var at = new Kinetic.Transform(),
transformsEnabled, trans;
// start with stage and traverse downwards to self
this._eachAncestorReverse(function(node) {
transformsEnabled = node.transformsEnabled();
trans = node.getTransform();
if (transformsEnabled === 'all') {
at.multiply(trans);
}
else if (transformsEnabled === 'position') {
at.translate(node.x(), node.y());
}
}, top);
return at;
},
/**
* get transform of the node
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Transform}
*/
getTransform: function() {
return this._getCache(TRANSFORM, this._getTransform);
},
_getTransform: function() {
var m = new Kinetic.Transform(),
x = this.getX(),
y = this.getY(),
rotation = Kinetic.getAngle(this.getRotation()),
scaleX = this.getScaleX(),
scaleY = this.getScaleY(),
skewX = this.getSkewX(),
skewY = this.getSkewY(),
offsetX = this.getOffsetX(),
offsetY = this.getOffsetY();
if(x !== 0 || y !== 0) {
m.translate(x, y);
}
if(rotation !== 0) {
m.rotate(rotation);
}
if(skewX !== 0 || skewY !== 0) {
m.skew(skewX, skewY);
}
if(scaleX !== 1 || scaleY !== 1) {
m.scale(scaleX, scaleY);
}
if(offsetX !== 0 || offsetY !== 0) {
m.translate(-1 * offsetX, -1 * offsetY);
}
return m;
},
/**
* clone node. Returns a new Node instance with identical attributes. You can also override
* the node properties with an object literal, enabling you to use an existing node as a template
* for another node
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} attrs override attrs
* @returns {Kinetic.Node}
* @example
* // simple clone<br>
* var clone = node.clone();<br><br>
*
* // clone a node and override the x position<br>
* var clone = rect.clone({<br>
* x: 5<br>
* });
*/
clone: function(obj) {
// instantiate new node
var className = this.getClassName(),
attrs = Kinetic.Util.cloneObject(this.attrs),
key, allListeners, len, n, listener;
// filter black attrs
for (var i in CLONE_BLACK_LIST) {
var blockAttr = CLONE_BLACK_LIST[i];
delete attrs[blockAttr];
}
// apply attr overrides
for (key in obj) {
attrs[key] = obj[key];
}
var node = new Kinetic[className](attrs);
// copy over listeners
for(key in this.eventListeners) {
allListeners = this.eventListeners[key];
len = allListeners.length;
for(n = 0; n < len; n++) {
listener = allListeners[n];
/*
* don't include kinetic namespaced listeners because
* these are generated by the constructors
*/
if(listener.name.indexOf(KINETIC) < 0) {
// if listeners array doesn't exist, then create it
if(!node.eventListeners[key]) {
node.eventListeners[key] = [];
}
node.eventListeners[key].push(listener);
}
}
}
return node;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @returns {String}
*/
toDataURL: function(config) {
config = config || {};
var mimeType = config.mimeType || null,
quality = config.quality || null,
stage = this.getStage(),
x = config.x || 0,
y = config.y || 0,
canvas = new Kinetic.SceneCanvas({
width: config.width || this.getWidth() || (stage ? stage.getWidth() : 0),
height: config.height || this.getHeight() || (stage ? stage.getHeight() : 0),
pixelRatio: 1
}),
context = canvas.getContext();
context.save();
if(x || y) {
context.translate(-1 * x, -1 * y);
}
this.drawScene(canvas);
context.restore();
return canvas.toDataURL(mimeType, quality);
},
/**
* converts node into an image. Since the toImage
* method is asynchronous, a callback is required. toImage is most commonly used
* to cache complex drawings as an image so that they don't have to constantly be redrawn
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
* @example
* var image = node.toImage({<br>
* callback: function(img) {<br>
* // do stuff with img<br>
* }<br>
* });
*/
toImage: function(config) {
Kinetic.Util._getImage(this.toDataURL(config), function(img) {
config.callback(img);
});
},
setSize: function(size) {
this.setWidth(size.width);
this.setHeight(size.height);
return this;
},
getSize: function() {
return {
width: this.getWidth(),
height: this.getHeight()
};
},
/**
* get width
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getWidth: function() {
return this.attrs.width || 0;
},
/**
* get height
* @method
* @memberof Kinetic.Node.prototype
* @returns {Integer}
*/
getHeight: function() {
return this.attrs.height || 0;
},
/**
* get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc.
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}
*/
getClassName: function() {
return this.className || this.nodeType;
},
/**
* get the node type, which may return Stage, Layer, Group, or Node
* @method
* @memberof Kinetic.Node.prototype
* @returns {String}
*/
getType: function() {
return this.nodeType;
},
getDragDistance: function() {
// compare with undefined because we need to track 0 value
if (this.attrs.dragDistance !== undefined) {
return this.attrs.dragDistance;
} else if (this.parent) {
return this.parent.getDragDistance();
} else {
return Kinetic.dragDistance;
}
},
_get: function(selector) {
return this.nodeType === selector ? [this] : [];
},
_off: function(type, name) {
var evtListeners = this.eventListeners[type],
i, evtName;
for(i = 0; i < evtListeners.length; i++) {
evtName = evtListeners[i].name;
// the following two conditions must be true in order to remove a handler:
// 1) the current event name cannot be kinetic unless the event name is kinetic
// this enables developers to force remove a kinetic specific listener for whatever reason
// 2) an event name is not specified, or if one is specified, it matches the current event name
if((evtName !== 'kinetic' || name === 'kinetic') && (!name || evtName === name)) {
evtListeners.splice(i, 1);
if(evtListeners.length === 0) {
delete this.eventListeners[type];
break;
}
i--;
}
}
},
_fireChangeEvent: function(attr, oldVal, newVal) {
this._fire(attr + CHANGE, {
oldVal: oldVal,
newVal: newVal
});
},
/**
* set id
* @method
* @memberof Kinetic.Node.prototype
* @param {String} id
* @returns {Kinetic.Node}
*/
setId: function(id) {
var oldId = this.getId();
Kinetic._removeId(oldId);
Kinetic._addId(this, id);
this._setAttr(ID, id);
return this;
},
setName: function(name) {
var oldName = this.getName();
Kinetic._removeName(oldName, this._id);
Kinetic._addName(this, name);
this._setAttr(NAME, name);
return this;
},
/**
* set attr
* @method
* @memberof Kinetic.Node.prototype
* @param {String} attr
* @param {*} val
* @returns {Kinetic.Node}
* @example
* node.setAttr('x', 5);
*/
setAttr: function() {
var args = Array.prototype.slice.call(arguments),
attr = args[0],
val = args[1],
method = SET + Kinetic.Util._capitalize(attr),
func = this[method];
if(Kinetic.Util._isFunction(func)) {
func.call(this, val);
}
// otherwise set directly
else {
this._setAttr(attr, val);
}
return this;
},
_setAttr: function(key, val) {
var oldVal;
if(val !== undefined) {
oldVal = this.attrs[key];
this.attrs[key] = val;
this._fireChangeEvent(key, oldVal, val);
}
},
_setComponentAttr: function(key, component, val) {
var oldVal;
if(val !== undefined) {
oldVal = this.attrs[key];
if (!oldVal) {
// set value to default value using getAttr
this.attrs[key] = this.getAttr(key);
}
this.attrs[key][component] = val;
this._fireChangeEvent(key, oldVal, val);
}
},
_fireAndBubble: function(eventType, evt, compareShape) {
var okayToRun = true;
if(evt && this.nodeType === SHAPE) {
evt.target = this;
}
if(eventType === MOUSEENTER && compareShape && this._id === compareShape._id) {
okayToRun = false;
}
else if(eventType === MOUSELEAVE && compareShape && this._id === compareShape._id) {
okayToRun = false;
}
if(okayToRun) {
this._fire(eventType, evt);
// simulate event bubbling
if(evt && !evt.cancelBubble && this.parent) {
if(compareShape && compareShape.parent) {
this._fireAndBubble.call(this.parent, eventType, evt, compareShape.parent);
}
else {
this._fireAndBubble.call(this.parent, eventType, evt);
}
}
}
},
_fire: function(eventType, evt) {
var events = this.eventListeners[eventType],
i;
evt.type = eventType;
if (events) {
for(i = 0; i < events.length; i++) {
events[i].handler.call(this, evt);
}
}
},
/**
* draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn
* @method
* @memberof Kinetic.Node.prototype
* @returns {Kinetic.Node}
*/
draw: function() {
this.drawScene();
this.drawHit();
return this;
}
});
/**
* create node with JSON string. De-serializtion does not generate custom
* shape drawing functions, images, or event handlers (this would make the
* serialized object huge). If your app uses custom shapes, images, and
* event handlers (it probably does), then you need to select the appropriate
* shapes after loading the stage and set these properties via on(), setDrawFunc(),
* and setImage() methods
* @method
* @memberof Kinetic.Node
* @param {String} JSON string
* @param {DomElement} [container] optional container dom element used only if you're
* creating a stage node
*/
Kinetic.Node.create = function(json, container) {
return this._createNode(JSON.parse(json), container);
};
Kinetic.Node._createNode = function(obj, container) {
var className = Kinetic.Node.prototype.getClassName.call(obj),
children = obj.children,
no, len, n;
// if container was passed in, add it to attrs
if(container) {
obj.attrs.container = container;
}
no = new Kinetic[className](obj.attrs);
if(children) {
len = children.length;
for(n = 0; n < len; n++) {
no.add(this._createNode(children[n]));
}
}
return no;
};
// =========================== add getters setters ===========================
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'position');
/**
* get/set node position relative to parent
* @name position
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Nubmer} pos.y
* @returns {Object}
* @example
* // get position<br>
* var position = node.position();<br><br>
*
* // set position<br>
* node.position({<br>
* x: 5<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'x', 0);
/**
* get/set x position
* @name x
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} x
* @returns {Object}
* @example
* // get x<br>
* var x = node.x();<br><br>
*
* // set x<br>
* node.x(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'y', 0);
/**
* get/set y position
* @name y
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} y
* @returns {Integer}
* @example
* // get y<br>
* var y = node.y();<br><br>
*
* // set y<br>
* node.y(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'opacity', 1);
/**
* get/set opacity. Opacity values range from 0 to 1.
* A node with an opacity of 0 is fully transparent, and a node
* with an opacity of 1 is fully opaque
* @name opacity
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} opacity
* @returns {Number}
* @example
* // get opacity<br>
* var opacity = node.opacity();<br><br>
*
* // set opacity<br>
* node.opacity(0.5);
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'name');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'name');
/**
* get/set name
* @name name
* @method
* @memberof Kinetic.Node.prototype
* @param {String} name
* @returns {String}
* @example
* // get name<br>
* var name = node.name();<br><br>
*
* // set name<br>
* node.name('foo');
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'id');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'id');
/**
* get/set id
* @name id
* @method
* @memberof Kinetic.Node.prototype
* @param {String} id
* @returns {String}
* @example
* // get id<br>
* var name = node.id();<br><br>
*
* // set id<br>
* node.id('foo');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'rotation', 0);
/**
* get/set rotation in degrees
* @name rotation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} rotation
* @returns {Number}
* @example
* // get rotation in degrees<br>
* var rotation = node.rotation();<br><br>
*
* // set rotation in degrees<br>
* node.rotation(45);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'scale', ['x', 'y']);
/**
* get/set scale
* @name scale
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
* @example
* // get scale<br>
* var scale = node.scale();<br><br>
*
* // set scale <br>
* shape.scale({<br>
* x: 2<br>
* y: 3<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleX', 1);
/**
* get/set scale x
* @name scaleX
* @param {Number} x
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get scale x<br>
* var scaleX = node.scaleX();<br><br>
*
* // set scale x<br>
* node.scaleX(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleY', 1);
/**
* get/set scale y
* @name scaleY
* @param {Number} y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get scale y<br>
* var scaleY = node.scaleY();<br><br>
*
* // set scale y<br>
* node.scaleY(2);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'skew', ['x', 'y']);
/**
* get/set skew
* @name skew
* @param {Object} skew
* @param {Number} skew.x
* @param {Number} skew.y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Object}
* @example
* // get skew<br>
* var skew = node.skew();<br><br>
*
* // set skew <br>
* node.skew({<br>
* x: 20<br>
* y: 10
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewX', 0);
/**
* get/set skew x
* @name skewX
* @param {Number} x
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get skew x<br>
* var skewX = node.skewX();<br><br>
*
* // set skew x<br>
* node.skewX(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewY', 0);
/**
* get/set skew y
* @name skewY
* @param {Number} y
* @method
* @memberof Kinetic.Node.prototype
* @returns {Number}
* @example
* // get skew y<br>
* var skewY = node.skewY();<br><br>
*
* // set skew y<br>
* node.skewY(3);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'offset', ['x', 'y']);
/**
* get/set offset. Offsets the default position and rotation point
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get offset<br>
* var offset = node.offset();<br><br>
*
* // set offset<br>
* node.offset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetX', 0);
/**
* get/set offset x
* @name offsetX
* @memberof Kinetic.Node.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get offset x<br>
* var offsetX = node.offsetX();<br><br>
*
* // set offset x<br>
* node.offsetX(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetY', 0);
/**
* get/set drag distance
* @name dragDistance
* @memberof Kinetic.Node.prototype
* @param {Number} distance
* @returns {Number}
* @example
* // get drag distance<br>
* var dragDistance = node.dragDistance();<br><br>
*
* // set distance<br>
* // node starts dragging only if pointer moved more then 3 pixels<br>
* node.dragDistance(3);<br>
* // or set globally<br>
* Kinetic.dragDistance = 3;
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'dragDistance');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'dragDistance');
/**
* get/set offset y
* @name offsetY
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get offset y<br>
* var offsetY = node.offsetY();<br><br>
*
* // set offset y<br>
* node.offsetY(3);
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'width', 0);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'width');
/**
* get/set width
* @name width
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get width<br>
* var width = node.width();<br><br>
*
* // set width<br>
* node.width(100);
*/
Kinetic.Factory.addSetter(Kinetic.Node, 'height', 0);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'height');
/**
* get/set height
* @name height
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get height<br>
* var height = node.height();<br><br>
*
* // set height<br>
* node.height(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'listening', 'inherit');
/**
* get/set listenig attr. If you need to determine if a node is listening or not
* by taking into account its parents, use the isListening() method
* @name listening
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean|String} listening Can be "inherit", true, or false. The default is "inherit".
* @returns {Boolean|String}
* @example
* // get listening attr<br>
* var listening = node.listening();<br><br>
*
* // stop listening for events<br>
* node.listening(false);<br><br>
*
* // listen for events<br>
* node.listening(true);<br><br>
*
* // listen to events according to the parent<br>
* node.listening('inherit');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'filters', undefined, function(val) {this._filterUpToDate = false;return val;});
/**
* get/set filters. Filters are applied to cached canvases
* @name filters
* @method
* @memberof Kinetic.Node.prototype
* @param {Array} filters array of filters
* @returns {Array}
* @example
* // get filters<br>
* var filters = node.filters();<br><br>
*
* // set a single filter<br>
* node.cache();<br>
* node.filters([Kinetic.Filters.Blur]);<br><br>
*
* // set multiple filters<br>
* node.cache();<br>
* node.filters([<br>
* Kinetic.Filters.Blur,<br>
* Kinetic.Filters.Sepia,<br>
* Kinetic.Filters.Invert<br>
* ]);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'visible', 'inherit');
/**
* get/set visible attr. Can be "inherit", true, or false. The default is "inherit".
* If you need to determine if a node is visible or not
* by taking into account its parents, use the isVisible() method
* @name visible
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean|String} visible
* @returns {Boolean|String}
* @example
* // get visible attr<br>
* var visible = node.visible();<br><br>
*
* // make invisible<br>
* node.visible(false);<br><br>
*
* // make visible<br>
* node.visible(true);<br><br>
*
* // make visible according to the parent<br>
* node.visible('inherit');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'transformsEnabled', 'all');
/**
* get/set transforms that are enabled. Can be "all", "none", or "position". The default
* is "all"
* @name transformsEnabled
* @method
* @memberof Kinetic.Node.prototype
* @param {String} enabled
* @returns {String}
* @example
* // enable position transform only to improve draw performance<br>
* node.transformsEnabled('position');<br><br>
*
* // enable all transforms<br>
* node.transformsEnabled('all');
*/
/**
* get/set node size
* @name size
* @method
* @memberof Kinetic.Node.prototype
* @param {Object} size
* @param {Number} size.width
* @param {Number} size.height
* @returns {Object}
* @example
* // get node size<br>
* var size = node.size();<br>
* var x = size.x;<br>
* var y = size.y;<br><br>
*
* // set size<br>
* node.size({<br>
* width: 100,<br>
* height: 200<br>
* });
*/
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'size');
Kinetic.Factory.backCompat(Kinetic.Node, {
rotateDeg: 'rotate',
setRotationDeg: 'setRotation',
getRotationDeg: 'getRotation'
});
Kinetic.Collection.mapMethods(Kinetic.Node);
})();
;(function() {
/**
* Grayscale Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Grayscale = function(imageData) {
var data = imageData.data,
len = data.length,
i, brightness;
for(i = 0; i < len; i += 4) {
brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
};
})();
;(function() {
/**
* Brighten Filter.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Brighten = function(imageData) {
var brightness = this.brightness() * 255,
data = imageData.data,
len = data.length,
i;
for(i = 0; i < len; i += 4) {
// red
data[i] += brightness;
// green
data[i + 1] += brightness;
// blue
data[i + 2] += brightness;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'brightness', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set filter brightness. The brightness is a number between -1 and 1. Positive values
* brighten the pixels and negative values darken them.
* @name brightness
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} brightness value between -1 and 1
* @returns {Number}
*/
})();
;(function() {
/**
* Invert Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Invert = function(imageData) {
var data = imageData.data,
len = data.length,
i;
for(i = 0; i < len; i += 4) {
// red
data[i] = 255 - data[i];
// green
data[i + 1] = 255 - data[i + 1];
// blue
data[i + 2] = 255 - data[i + 2];
}
};
})();;/*
the Gauss filter
master repo: https://github.com/pavelpower/kineticjsGaussFilter/
*/
(function() {
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: [email protected]
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
[email protected]
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
Copyright (c) 2010 Mario Klingemann
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
function BlurStack() {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 0;
this.next = null;
}
var mul_table = [
512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
289,287,285,282,280,278,275,273,271,269,267,265,263,261,259
];
var shg_table = [
9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24
];
function filterGaussBlurRGBA( imageData, radius) {
var pixels = imageData.data,
width = imageData.width,
height = imageData.height;
var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum,
r_out_sum, g_out_sum, b_out_sum, a_out_sum,
r_in_sum, g_in_sum, b_in_sum, a_in_sum,
pr, pg, pb, pa, rbs;
var div = radius + radius + 1,
widthMinus1 = width - 1,
heightMinus1 = height - 1,
radiusPlus1 = radius + 1,
sumFactor = radiusPlus1 * ( radiusPlus1 + 1 ) / 2,
stackStart = new BlurStack(),
stackEnd = null,
stack = stackStart,
stackIn = null,
stackOut = null,
mul_sum = mul_table[radius],
shg_sum = shg_table[radius];
for ( i = 1; i < div; i++ ) {
stack = stack.next = new BlurStack();
if ( i == radiusPlus1 ){
stackEnd = stack;
}
}
stack.next = stackStart;
yw = yi = 0;
for ( y = 0; y < height; y++ )
{
r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0;
r_out_sum = radiusPlus1 * ( pr = pixels[yi] );
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1] );
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2] );
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3] );
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
for( i = 1; i < radiusPlus1; i++ )
{
p = yi + (( widthMinus1 < i ? widthMinus1 : i ) << 2 );
r_sum += ( stack.r = ( pr = pixels[p])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[p+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[p+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[p+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
}
stackIn = stackStart;
stackOut = stackEnd;
for ( x = 0; x < width; x++ )
{
pixels[yi+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa !== 0 )
{
pa = 255 / pa;
pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+1] = ((g_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+2] = ((b_sum * mul_sum) >> shg_sum) * pa;
} else {
pixels[yi] = pixels[yi+1] = pixels[yi+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( yw + ( ( p = x + radius + 1 ) < widthMinus1 ? p : widthMinus1 ) ) << 2;
r_in_sum += ( stackIn.r = pixels[p]);
g_in_sum += ( stackIn.g = pixels[p+1]);
b_in_sum += ( stackIn.b = pixels[p+2]);
a_in_sum += ( stackIn.a = pixels[p+3]);
r_sum += r_in_sum;
g_sum += g_in_sum;
b_sum += b_in_sum;
a_sum += a_in_sum;
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += 4;
}
yw += width;
}
for ( x = 0; x < width; x++ )
{
g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0;
yi = x << 2;
r_out_sum = radiusPlus1 * ( pr = pixels[yi]);
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1]);
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2]);
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3]);
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
yp = width;
for( i = 1; i <= radius; i++ )
{
yi = ( yp + x ) << 2;
r_sum += ( stack.r = ( pr = pixels[yi])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[yi+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[yi+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[yi+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
if( i < heightMinus1 )
{
yp += width;
}
}
yi = x;
stackIn = stackStart;
stackOut = stackEnd;
for ( y = 0; y < height; y++ )
{
p = yi << 2;
pixels[p+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa > 0 )
{
pa = 255 / pa;
pixels[p] = ((r_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+1] = ((g_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+2] = ((b_sum * mul_sum) >> shg_sum ) * pa;
} else {
pixels[p] = pixels[p+1] = pixels[p+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( x + (( ( p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1 ) * width )) << 2;
r_sum += ( r_in_sum += ( stackIn.r = pixels[p]));
g_sum += ( g_in_sum += ( stackIn.g = pixels[p+1]));
b_sum += ( b_in_sum += ( stackIn.b = pixels[p+2]));
a_sum += ( a_in_sum += ( stackIn.a = pixels[p+3]));
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += width;
}
}
}
/**
* Blur Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Blur = function(imageData) {
var radius = Math.round(this.blurRadius());
if (radius > 0) {
filterGaussBlurRGBA(imageData, radius);
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blurRadius', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set blur radius
* @name blurRadius
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} radius
* @returns {Integer}
*/
})();;(function() {
function pixelAt(idata, x, y) {
var idx = (y * idata.width + x) * 4;
var d = [];
d.push(idata.data[idx++], idata.data[idx++], idata.data[idx++], idata.data[idx++]);
return d;
}
function rgbDistance(p1, p2) {
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2) + Math.pow(p1[2] - p2[2], 2));
}
function rgbMean(pTab) {
var m = [0, 0, 0];
for (var i = 0; i < pTab.length; i++) {
m[0] += pTab[i][0];
m[1] += pTab[i][1];
m[2] += pTab[i][2];
}
m[0] /= pTab.length;
m[1] /= pTab.length;
m[2] /= pTab.length;
return m;
}
function backgroundMask(idata, threshold) {
var rgbv_no = pixelAt(idata, 0, 0);
var rgbv_ne = pixelAt(idata, idata.width - 1, 0);
var rgbv_so = pixelAt(idata, 0, idata.height - 1);
var rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1);
var thres = threshold || 10;
if (rgbDistance(rgbv_no, rgbv_ne) < thres && rgbDistance(rgbv_ne, rgbv_se) < thres && rgbDistance(rgbv_se, rgbv_so) < thres && rgbDistance(rgbv_so, rgbv_no) < thres) {
// Mean color
var mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]);
// Mask based on color distance
var mask = [];
for (var i = 0; i < idata.width * idata.height; i++) {
var d = rgbDistance(mean, [idata.data[i * 4], idata.data[i * 4 + 1], idata.data[i * 4 + 2]]);
mask[i] = (d < thres) ? 0 : 255;
}
return mask;
}
}
function applyMask(idata, mask) {
for (var i = 0; i < idata.width * idata.height; i++) {
idata.data[4 * i + 3] = mask[i];
}
}
function erodeMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 0, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = (a === 255 * 8) ? 255 : 0;
}
}
return maskResult;
}
function dilateMask(mask, sw, sh) {
var weights = [1, 1, 1, 1, 1, 1, 1, 1, 1];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = (a >= 255 * 4) ? 255 : 0;
}
}
return maskResult;
}
function smoothEdgeMask(mask, sw, sh) {
var weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9];
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side / 2);
var maskResult = [];
for (var y = 0; y < sh; y++) {
for (var x = 0; x < sw; x++) {
var so = y * sw + x;
var a = 0;
for (var cy = 0; cy < side; cy++) {
for (var cx = 0; cx < side; cx++) {
var scy = y + cy - halfSide;
var scx = x + cx - halfSide;
if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) {
var srcOff = scy * sw + scx;
var wt = weights[cy * side + cx];
a += mask[srcOff] * wt;
}
}
}
maskResult[so] = a;
}
}
return maskResult;
}
/**
* Mask Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Mask = function(imageData) {
// Detect pixels close to the background color
var threshold = this.threshold(),
mask = backgroundMask(imageData, threshold);
if (mask) {
// Erode
mask = erodeMask(mask, imageData.width, imageData.height);
// Dilate
mask = dilateMask(mask, imageData.width, imageData.height);
// Gradient
mask = smoothEdgeMask(mask, imageData.width, imageData.height);
// Apply mask
applyMask(imageData, mask);
// todo : Update hit region function according to mask
}
return imageData;
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0, null, Kinetic.Factory.afterSetFilter);
})();
;(function () {
/**
* RGB Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.RGB = function (imageData) {
var data = imageData.data,
nPixels = data.length,
red = this.red(),
green = this.green(),
blue = this.blue(),
i, brightness;
for (i = 0; i < nPixels; i += 4) {
brightness = (0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2])/255;
data[i ] = brightness*red; // r
data[i + 1] = brightness*green; // g
data[i + 2] = brightness*blue; // b
data[i + 3] = data[i + 3]; // alpha
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'red', 0, function(val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter red value
* @name red
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} red value between 0 and 255
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'green', 0, function(val) {
this._filterUpToDate = false;
if (val > 255) {
return 255;
}
else if (val < 0) {
return 0;
}
else {
return Math.round(val);
}
});
/**
* get/set filter green value
* @name green
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} green value between 0 and 255
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blue', 0, Kinetic.Validators.RGBComponent, Kinetic.Factory.afterSetFilter);
/**
* get/set filter blue value
* @name blue
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} blue value between 0 and 255
* @returns {Integer}
*/
})();
;(function () {
/**
* HSV Filter. Adjusts the hue, saturation and value
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.HSV = function (imageData) {
var data = imageData.data,
nPixels = data.length,
v = Math.pow(2,this.value()),
s = Math.pow(2,this.saturation()),
h = Math.abs((this.hue()) + 360) % 360,
i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v*s*Math.cos(h*Math.PI/180),
vsw = v*s*Math.sin(h*Math.PI/180);
// (result spot)(source spot)
var rr = 0.299*v+0.701*vsu+0.167*vsw,
rg = 0.587*v-0.587*vsu+0.330*vsw,
rb = 0.114*v-0.114*vsu-0.497*vsw;
var gr = 0.299*v-0.299*vsu-0.328*vsw,
gg = 0.587*v+0.413*vsu+0.035*vsw,
gb = 0.114*v-0.114*vsu+0.293*vsw;
var br = 0.299*v-0.300*vsu+1.250*vsw,
bg = 0.587*v-0.586*vsu-1.050*vsw,
bb = 0.114*v+0.886*vsu-0.200*vsw;
var r,g,b,a;
for (i = 0; i < nPixels; i += 4) {
r = data[i+0];
g = data[i+1];
b = data[i+2];
a = data[i+3];
data[i+0] = rr*r + rg*g + rb*b;
data[i+1] = gr*r + gg*g + gb*b;
data[i+2] = br*r + bg*g + bb*b;
data[i+3] = a; // alpha
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv hue in degrees
* @name hue
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv saturation
* @name saturation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'value', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv value
* @name value
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc..
* @returns {Number}
*/
})();
;(function () {
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv hue in degrees
* @name hue
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} hue value between 0 and 359
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsv saturation
* @name saturation
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc..
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'luminance', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set hsl luminance
* @name value
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc..
* @returns {Number}
*/
/**
* HSL Filter. Adjusts the hue, saturation and luminance (or lightness)
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.HSL = function (imageData) {
var data = imageData.data,
nPixels = data.length,
v = 1,
s = Math.pow(2,this.saturation()),
h = Math.abs((this.hue()) + 360) % 360,
l = this.luminance()*127,
i;
// Basis for the technique used:
// http://beesbuzz.biz/code/hsv_color_transforms.php
// V is the value multiplier (1 for none, 2 for double, 0.5 for half)
// S is the saturation multiplier (1 for none, 2 for double, 0.5 for half)
// H is the hue shift in degrees (0 to 360)
// vsu = V*S*cos(H*PI/180);
// vsw = V*S*sin(H*PI/180);
//[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R]
//[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G]
//[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B]
// Precompute the values in the matrix:
var vsu = v*s*Math.cos(h*Math.PI/180),
vsw = v*s*Math.sin(h*Math.PI/180);
// (result spot)(source spot)
var rr = 0.299*v+0.701*vsu+0.167*vsw,
rg = 0.587*v-0.587*vsu+0.330*vsw,
rb = 0.114*v-0.114*vsu-0.497*vsw;
var gr = 0.299*v-0.299*vsu-0.328*vsw,
gg = 0.587*v+0.413*vsu+0.035*vsw,
gb = 0.114*v-0.114*vsu+0.293*vsw;
var br = 0.299*v-0.300*vsu+1.250*vsw,
bg = 0.587*v-0.586*vsu-1.050*vsw,
bb = 0.114*v+0.886*vsu-0.200*vsw;
var r,g,b,a;
for (i = 0; i < nPixels; i += 4) {
r = data[i+0];
g = data[i+1];
b = data[i+2];
a = data[i+3];
data[i+0] = rr*r + rg*g + rb*b + l;
data[i+1] = gr*r + gg*g + gb*b + l;
data[i+2] = br*r + bg*g + bb*b + l;
data[i+3] = a; // alpha
}
};
})();
;(function () {
/**
* Emboss Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* Pixastic Lib - Emboss filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Emboss = function (imageData) {
// pixastic strength is between 0 and 10. I want it between 0 and 1
// pixastic greyLevel is between 0 and 255. I want it between 0 and 1. Also,
// a max value of greyLevel yields a white emboss, and the min value yields a black
// emboss. Therefore, I changed greyLevel to whiteLevel
var strength = this.embossStrength() * 10,
greyLevel = this.embossWhiteLevel() * 255,
direction = this.embossDirection(),
blend = this.embossBlend(),
dirY = 0,
dirX = 0,
data = imageData.data,
w = imageData.width,
h = imageData.height,
w4 = w*4,
y = h;
switch (direction) {
case 'top-left':
dirY = -1;
dirX = -1;
break;
case 'top':
dirY = -1;
dirX = 0;
break;
case 'top-right':
dirY = -1;
dirX = 1;
break;
case 'right':
dirY = 0;
dirX = 1;
break;
case 'bottom-right':
dirY = 1;
dirX = 1;
break;
case 'bottom':
dirY = 1;
dirX = 0;
break;
case 'bottom-left':
dirY = 1;
dirX = -1;
break;
case 'left':
dirY = 0;
dirX = -1;
break;
}
do {
var offsetY = (y-1)*w4;
var otherY = dirY;
if (y + otherY < 1){
otherY = 0;
}
if (y + otherY > h) {
otherY = 0;
}
var offsetYOther = (y-1+otherY)*w*4;
var x = w;
do {
var offset = offsetY + (x-1)*4;
var otherX = dirX;
if (x + otherX < 1){
otherX = 0;
}
if (x + otherX > w) {
otherX = 0;
}
var offsetOther = offsetYOther + (x-1+otherX)*4;
var dR = data[offset] - data[offsetOther];
var dG = data[offset+1] - data[offsetOther+1];
var dB = data[offset+2] - data[offsetOther+2];
var dif = dR;
var absDif = dif > 0 ? dif : -dif;
var absG = dG > 0 ? dG : -dG;
var absB = dB > 0 ? dB : -dB;
if (absG > absDif) {
dif = dG;
}
if (absB > absDif) {
dif = dB;
}
dif *= strength;
if (blend) {
var r = data[offset] + dif;
var g = data[offset+1] + dif;
var b = data[offset+2] + dif;
data[offset] = (r > 255) ? 255 : (r < 0 ? 0 : r);
data[offset+1] = (g > 255) ? 255 : (g < 0 ? 0 : g);
data[offset+2] = (b > 255) ? 255 : (b < 0 ? 0 : b);
} else {
var grey = greyLevel - dif;
if (grey < 0) {
grey = 0;
} else if (grey > 255) {
grey = 255;
}
data[offset] = data[offset+1] = data[offset+2] = grey;
}
} while (--x);
} while (--y);
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossStrength', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss strength
* @name embossStrength
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} level between 0 and 1. Default is 0.5
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossWhiteLevel', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss white level
* @name embossWhiteLevel
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} embossWhiteLevel between 0 and 1. Default is 0.5
* @returns {Number}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossDirection', 'top-left', null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss direction
* @name embossDirection
* @method
* @memberof Kinetic.Node.prototype
* @param {String} embossDirection can be top-left, top, top-right, right, bottom-right, bottom, bottom-left or left
* The default is top-left
* @returns {String}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossBlend', false, null, Kinetic.Factory.afterSetFilter);
/**
* get/set emboss blend
* @name embossBlend
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean} embossBlend
* @returns {Boolean}
*/
})();
;(function () {
function remap(fromValue, fromMin, fromMax, toMin, toMax) {
// Compute the range of the data
var fromRange = fromMax - fromMin,
toRange = toMax - toMin,
toValue;
// If either range is 0, then the value can only be mapped to 1 value
if (fromRange === 0) {
return toMin + toRange / 2;
}
if (toRange === 0) {
return toMin;
}
// (1) untranslate, (2) unscale, (3) rescale, (4) retranslate
toValue = (fromValue - fromMin) / fromRange;
toValue = (toRange * toValue) + toMin;
return toValue;
}
/**
* Enhance Filter. Adjusts the colors so that they span the widest
* possible range (ie 0-255). Performs w*h pixel reads and w*h pixel
* writes.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Enhance = function (imageData) {
var data = imageData.data,
nSubPixels = data.length,
rMin = data[0], rMax = rMin, r,
gMin = data[1], gMax = gMin, g,
bMin = data[2], bMax = bMin, b,
aMin = data[3], aMax = aMin,
i;
// If we are not enhancing anything - don't do any computation
var enhanceAmount = this.enhance();
if( enhanceAmount === 0 ){ return; }
// 1st Pass - find the min and max for each channel:
for (i = 0; i < nSubPixels; i += 4) {
r = data[i + 0];
if (r < rMin) { rMin = r; }
else if (r > rMax) { rMax = r; }
g = data[i + 1];
if (g < gMin) { gMin = g; } else
if (g > gMax) { gMax = g; }
b = data[i + 2];
if (b < bMin) { bMin = b; } else
if (b > bMax) { bMax = b; }
//a = data[i + 3];
//if (a < aMin) { aMin = a; } else
//if (a > aMax) { aMax = a; }
}
// If there is only 1 level - don't remap
if( rMax === rMin ){ rMax = 255; rMin = 0; }
if( gMax === gMin ){ gMax = 255; gMin = 0; }
if( bMax === bMin ){ bMax = 255; bMin = 0; }
if( aMax === aMin ){ aMax = 255; aMin = 0; }
var rMid, rGoalMax,rGoalMin,
gMid, gGoalMax,gGoalMin,
bMid, bGoalMax,aGoalMin,
aMid, aGoalMax,bGoalMin;
// If the enhancement is positive - stretch the histogram
if ( enhanceAmount > 0 ){
rGoalMax = rMax + enhanceAmount*(255-rMax);
rGoalMin = rMin - enhanceAmount*(rMin-0);
gGoalMax = gMax + enhanceAmount*(255-gMax);
gGoalMin = gMin - enhanceAmount*(gMin-0);
bGoalMax = bMax + enhanceAmount*(255-bMax);
bGoalMin = bMin - enhanceAmount*(bMin-0);
aGoalMax = aMax + enhanceAmount*(255-aMax);
aGoalMin = aMin - enhanceAmount*(aMin-0);
// If the enhancement is negative - compress the histogram
} else {
rMid = (rMax + rMin)*0.5;
rGoalMax = rMax + enhanceAmount*(rMax-rMid);
rGoalMin = rMin + enhanceAmount*(rMin-rMid);
gMid = (gMax + gMin)*0.5;
gGoalMax = gMax + enhanceAmount*(gMax-gMid);
gGoalMin = gMin + enhanceAmount*(gMin-gMid);
bMid = (bMax + bMin)*0.5;
bGoalMax = bMax + enhanceAmount*(bMax-bMid);
bGoalMin = bMin + enhanceAmount*(bMin-bMid);
aMid = (aMax + aMin)*0.5;
aGoalMax = aMax + enhanceAmount*(aMax-aMid);
aGoalMin = aMin + enhanceAmount*(aMin-aMid);
}
// Pass 2 - remap everything, except the alpha
for (i = 0; i < nSubPixels; i += 4) {
data[i + 0] = remap(data[i + 0], rMin, rMax, rGoalMin, rGoalMax);
data[i + 1] = remap(data[i + 1], gMin, gMax, gGoalMin, gGoalMax);
data[i + 2] = remap(data[i + 2], bMin, bMax, bGoalMin, bGoalMax);
//data[i + 3] = remap(data[i + 3], aMin, aMax, aGoalMin, aGoalMax);
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'enhance', 0, null, Kinetic.Factory.afterSetFilter);
/**
* get/set enhance
* @name enhance
* @method
* @memberof Kinetic.Node.prototype
* @param {Float} amount
* @returns {Float}
*/
})();
;(function () {
/**
* Posterize Filter. Adjusts the channels so that there are no more
* than n different values for that channel. This is also applied
* to the alpha channel.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {Object} imageData
*/
Kinetic.Filters.Posterize = function (imageData) {
// level must be between 1 and 255
var levels = Math.round(this.levels() * 254) + 1,
data = imageData.data,
len = data.length,
scale = (255 / levels),
i;
for (i = 0; i < len; i += 1) {
data[i] = Math.floor(data[i] / scale) * scale;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'levels', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set levels. Must be a number between 0 and 1
* @name levels
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} level between 0 and 1
* @returns {Number}
*/
})();;(function () {
/**
* Noise Filter. Randomly adds or substracts to the color channels
* @function
* @memberof Kinetic.Filters
* @param {Object} imagedata
* @author ippo615
*/
Kinetic.Filters.Noise = function (imageData) {
var amount = this.noise() * 255,
data = imageData.data,
nPixels = data.length,
half = amount / 2,
i;
for (i = 0; i < nPixels; i += 4) {
data[i + 0] += half - 2 * half * Math.random();
data[i + 1] += half - 2 * half * Math.random();
data[i + 2] += half - 2 * half * Math.random();
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'noise', 0.2, null, Kinetic.Factory.afterSetFilter);
/**
* get/set noise amount. Must be a value between 0 and 1
* @name noise
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} noise
* @returns {Number}
*/
})();
;(function () {
/**
* Pixelate Filter. Averages groups of pixels and redraws
* them as larger pixels
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Pixelate = function (imageData) {
var pixelSize = Math.ceil(this.pixelSize()),
width = imageData.width,
height = imageData.height,
x, y, i,
//pixelsPerBin = pixelSize * pixelSize,
red, green, blue, alpha,
nBinsX = Math.ceil(width / pixelSize),
nBinsY = Math.ceil(height / pixelSize),
xBinStart, xBinEnd, yBinStart, yBinEnd,
xBin, yBin, pixelsInBin;
imageData = imageData.data;
for (xBin = 0; xBin < nBinsX; xBin += 1) {
for (yBin = 0; yBin < nBinsY; yBin += 1) {
// Initialize the color accumlators to 0
red = 0;
green = 0;
blue = 0;
alpha = 0;
// Determine which pixels are included in this bin
xBinStart = xBin * pixelSize;
xBinEnd = xBinStart + pixelSize;
yBinStart = yBin * pixelSize;
yBinEnd = yBinStart + pixelSize;
// Add all of the pixels to this bin!
pixelsInBin = 0;
for (x = xBinStart; x < xBinEnd; x += 1) {
if( x >= width ){ continue; }
for (y = yBinStart; y < yBinEnd; y += 1) {
if( y >= height ){ continue; }
i = (width * y + x) * 4;
red += imageData[i + 0];
green += imageData[i + 1];
blue += imageData[i + 2];
alpha += imageData[i + 3];
pixelsInBin += 1;
}
}
// Make sure the channels are between 0-255
red = red / pixelsInBin;
green = green / pixelsInBin;
blue = blue / pixelsInBin;
// Draw this bin
for (x = xBinStart; x < xBinEnd; x += 1) {
if( x >= width ){ continue; }
for (y = yBinStart; y < yBinEnd; y += 1) {
if( y >= height ){ continue; }
i = (width * y + x) * 4;
imageData[i + 0] = red;
imageData[i + 1] = green;
imageData[i + 2] = blue;
imageData[i + 3] = alpha;
}
}
}
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'pixelSize', 8, null, Kinetic.Factory.afterSetFilter);
/**
* get/set pixel size
* @name pixelSize
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} pixelSize
* @returns {Integer}
*/
})();;(function () {
/**
* Threshold Filter. Pushes any value above the mid point to
* the max and any value below the mid point to the min.
* This affects the alpha channel.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Threshold = function (imageData) {
var level = this.threshold() * 255,
data = imageData.data,
len = data.length,
i;
for (i = 0; i < len; i += 1) {
data[i] = data[i] < level ? 0 : 255;
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0.5, null, Kinetic.Factory.afterSetFilter);
/**
* get/set threshold. Must be a value between 0 and 1
* @name threshold
* @method
* @memberof Kinetic.Node.prototype
* @param {Number} threshold
* @returns {Number}
*/
})();;(function() {
/**
* Sepia Filter
* Based on: Pixastic Lib - Sepia filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author Jacob Seidelin <[email protected]>
* @license MPL v1.1 [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Sepia = function (imageData) {
var data = imageData.data,
w = imageData.width,
y = imageData.height,
w4 = w*4,
offsetY, x, offset, or, og, ob, r, g, b;
do {
offsetY = (y-1)*w4;
x = w;
do {
offset = offsetY + (x-1)*4;
or = data[offset];
og = data[offset+1];
ob = data[offset+2];
r = or * 0.393 + og * 0.769 + ob * 0.189;
g = or * 0.349 + og * 0.686 + ob * 0.168;
b = or * 0.272 + og * 0.534 + ob * 0.131;
data[offset] = r > 255 ? 255 : r;
data[offset+1] = g > 255 ? 255 : g;
data[offset+2] = b > 255 ? 255 : b;
data[offset+3] = data[offset+3];
} while (--x);
} while (--y);
};
})();
;(function () {
/**
* Solarize Filter
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* Pixastic Lib - Solarize filter - v0.1.0
* Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/
* License: [http://www.pixastic.com/lib/license.txt]
*/
Kinetic.Filters.Solarize = function (imageData) {
var data = imageData.data,
w = imageData.width,
h = imageData.height,
w4 = w*4,
y = h;
do {
var offsetY = (y-1)*w4;
var x = w;
do {
var offset = offsetY + (x-1)*4;
var r = data[offset];
var g = data[offset+1];
var b = data[offset+2];
if (r > 127) {
r = 255 - r;
}
if (g > 127) {
g = 255 - g;
}
if (b > 127) {
b = 255 - b;
}
data[offset] = r;
data[offset+1] = g;
data[offset+2] = b;
} while (--x);
} while (--y);
};
})();
;/*jshint newcap:false */
(function () {
/*
* ToPolar Filter. Converts image data to polar coordinates. Performs
* w*h*4 pixel reads and w*h pixel writes. The r axis is placed along
* what would be the y axis and the theta axis along the x axis.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
*/
var ToPolar = function(src,dst,opt){
var srcPixels = src.data,
dstPixels = dst.data,
xSize = src.width,
ySize = src.height,
xMid = opt.polarCenterX || xSize/2,
yMid = opt.polarCenterY || ySize/2,
i, x, y, r=0,g=0,b=0,a=0;
// Find the largest radius
var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid );
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt( x*x + y*y );
rMax = (rad > rMax)?rad:rMax;
// We'll be uisng y as the radius, and x as the angle (theta=t)
var rSize = ySize,
tSize = xSize,
radius, theta;
// We want to cover all angles (0-360) and we need to convert to
// radians (*PI/180)
var conversion = 360/tSize*Math.PI/180, sin, cos;
// var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale;
for( theta=0; theta<tSize; theta+=1 ){
sin = Math.sin(theta*conversion);
cos = Math.cos(theta*conversion);
for( radius=0; radius<rSize; radius+=1 ){
x = Math.floor(xMid+rMax*radius/rSize*cos);
y = Math.floor(yMid+rMax*radius/rSize*sin);
i = (y*xSize + x)*4;
r = srcPixels[i+0];
g = srcPixels[i+1];
b = srcPixels[i+2];
a = srcPixels[i+3];
// Store it
//i = (theta * xSize + radius) * 4;
i = (theta + radius*xSize) * 4;
dstPixels[i+0] = r;
dstPixels[i+1] = g;
dstPixels[i+2] = b;
dstPixels[i+3] = a;
}
}
};
/*
* FromPolar Filter. Converts image data from polar coordinates back to rectangular.
* Performs w*h*4 pixel reads and w*h pixel writes.
* @function
* @author ippo615
* @memberof Kinetic.Filters
* @param {ImageData} src, the source image data (what will be transformed)
* @param {ImageData} dst, the destination image data (where it will be saved)
* @param {Object} opt
* @param {Number} [opt.polarCenterX] horizontal location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarCenterY] vertical location for the center of the circle,
* default is in the middle
* @param {Number} [opt.polarRotation] amount to rotate the image counterclockwis,
* 0 is no rotation, 360 degrees is a full rotation
*/
var FromPolar = function(src,dst,opt){
var srcPixels = src.data,
dstPixels = dst.data,
xSize = src.width,
ySize = src.height,
xMid = opt.polarCenterX || xSize/2,
yMid = opt.polarCenterY || ySize/2,
i, x, y, dx, dy, r=0,g=0,b=0,a=0;
// Find the largest radius
var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid );
x = xSize - xMid;
y = ySize - yMid;
rad = Math.sqrt( x*x + y*y );
rMax = (rad > rMax)?rad:rMax;
// We'll be uisng x as the radius, and y as the angle (theta=t)
var rSize = ySize,
tSize = xSize,
radius, theta,
phaseShift = opt.polarRotation || 0;
// We need to convert to degrees and we need to make sure
// it's between (0-360)
// var conversion = tSize/360*180/Math.PI;
//var conversion = tSize/360*180/Math.PI;
var x1, y1;
for( x=0; x<xSize; x+=1 ){
for( y=0; y<ySize; y+=1 ){
dx = x - xMid;
dy = y - yMid;
radius = Math.sqrt(dx*dx + dy*dy)*rSize/rMax;
theta = (Math.atan2(dy,dx)*180/Math.PI + 360 + phaseShift)%360;
theta = theta*tSize/360;
x1 = Math.floor(theta);
y1 = Math.floor(radius);
i = (y1*xSize + x1)*4;
r = srcPixels[i+0];
g = srcPixels[i+1];
b = srcPixels[i+2];
a = srcPixels[i+3];
// Store it
i = (y*xSize + x)*4;
dstPixels[i+0] = r;
dstPixels[i+1] = g;
dstPixels[i+2] = b;
dstPixels[i+3] = a;
}
}
};
//Kinetic.Filters.ToPolar = Kinetic.Util._FilterWrapDoubleBuffer(ToPolar);
//Kinetic.Filters.FromPolar = Kinetic.Util._FilterWrapDoubleBuffer(FromPolar);
// create a temporary canvas for working - shared between multiple calls
var tempCanvas = Kinetic.Util.createCanvasElement();
/*
* Kaleidoscope Filter.
* @function
* @author ippo615
* @memberof Kinetic.Filters
*/
Kinetic.Filters.Kaleidoscope = function(imageData){
var xSize = imageData.width,
ySize = imageData.height;
var x,y,xoff,i, r,g,b,a, srcPos, dstPos;
var power = Math.round( this.kaleidoscopePower() );
var angle = Math.round( this.kaleidoscopeAngle() );
var offset = Math.floor(xSize*(angle%360)/360);
if( power < 1 ){return;}
// Work with our shared buffer canvas
tempCanvas.width = xSize;
tempCanvas.height = ySize;
var scratchData = tempCanvas.getContext('2d').getImageData(0,0,xSize,ySize);
// Convert thhe original to polar coordinates
ToPolar( imageData, scratchData, {
polarCenterX:xSize/2,
polarCenterY:ySize/2
});
// Determine how big each section will be, if it's too small
// make it bigger
var minSectionSize = xSize / Math.pow(2,power);
while( minSectionSize <= 8){
minSectionSize = minSectionSize*2;
power -= 1;
}
minSectionSize = Math.ceil(minSectionSize);
var sectionSize = minSectionSize;
// Copy the offset region to 0
// Depending on the size of filter and location of the offset we may need
// to copy the section backwards to prevent it from rewriting itself
var xStart = 0,
xEnd = sectionSize,
xDelta = 1;
if( offset+minSectionSize > xSize ){
xStart = sectionSize;
xEnd = 0;
xDelta = -1;
}
for( y=0; y<ySize; y+=1 ){
for( x=xStart; x !== xEnd; x+=xDelta ){
xoff = Math.round(x+offset)%xSize;
srcPos = (xSize*y+xoff)*4;
r = scratchData.data[srcPos+0];
g = scratchData.data[srcPos+1];
b = scratchData.data[srcPos+2];
a = scratchData.data[srcPos+3];
dstPos = (xSize*y+x)*4;
scratchData.data[dstPos+0] = r;
scratchData.data[dstPos+1] = g;
scratchData.data[dstPos+2] = b;
scratchData.data[dstPos+3] = a;
}
}
// Perform the actual effect
for( y=0; y<ySize; y+=1 ){
sectionSize = Math.floor( minSectionSize );
for( i=0; i<power; i+=1 ){
for( x=0; x<sectionSize+1; x+=1 ){
srcPos = (xSize*y+x)*4;
r = scratchData.data[srcPos+0];
g = scratchData.data[srcPos+1];
b = scratchData.data[srcPos+2];
a = scratchData.data[srcPos+3];
dstPos = (xSize*y+sectionSize*2-x-1)*4;
scratchData.data[dstPos+0] = r;
scratchData.data[dstPos+1] = g;
scratchData.data[dstPos+2] = b;
scratchData.data[dstPos+3] = a;
}
sectionSize *= 2;
}
}
// Convert back from polar coordinates
FromPolar(scratchData,imageData,{polarRotation:0});
};
/**
* get/set kaleidoscope power
* @name kaleidoscopePower
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} power of kaleidoscope
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopePower', 2, null, Kinetic.Factory.afterSetFilter);
/**
* get/set kaleidoscope angle
* @name kaleidoscopeAngle
* @method
* @memberof Kinetic.Node.prototype
* @param {Integer} degrees
* @returns {Integer}
*/
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopeAngle', 0, null, Kinetic.Factory.afterSetFilter);
})();
;(function() {
var BATCH_DRAW_STOP_TIME_DIFF = 500;
var now =(function() {
if (Kinetic.root.performance && Kinetic.root.performance.now) {
return function() {
return Kinetic.root.performance.now();
};
}
else {
return function() {
return new Date().getTime();
};
}
})();
var RAF = (function() {
return Kinetic.root.requestAnimationFrame
|| Kinetic.root.webkitRequestAnimationFrame
|| Kinetic.root.mozRequestAnimationFrame
|| Kinetic.root.oRequestAnimationFrame
|| Kinetic.root.msRequestAnimationFrame
|| FRAF;
})();
function FRAF(callback) {
Kinetic.root.setTimeout(callback, 1000 / 60);
}
function requestAnimFrame() {
return RAF.apply(Kinetic.root, arguments);
}
/**
* Animation constructor. A stage is used to contain multiple layers and handle
* @constructor
* @memberof Kinetic
* @param {Function} func function executed on each animation frame. The function is passed a frame object, which contains
* timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed
* since the last animation frame. The lastTime property is time in milliseconds that elapsed from the moment the animation started
* to the last animation frame. The time property is the time in milliseconds that ellapsed from the moment the animation started
* to the current animation frame. The frameRate property is the current frame rate in frames / second
* @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null.
* Not specifying a node will result in no redraw.
* @example
* // move a node to the right at 50 pixels / second<br>
* var velocity = 50;<br><br>
*
* var anim = new Kinetic.Animation(function(frame) {<br>
* var dist = velocity * (frame.timeDiff / 1000);<br>
* node.move(dist, 0);<br>
* }, layer);<br><br>
*
* anim.start();
*/
Kinetic.Animation = function(func, layers) {
var Anim = Kinetic.Animation;
this.func = func;
this.setLayers(layers);
this.id = Anim.animIdCounter++;
this.frame = {
time: 0,
timeDiff: 0,
lastTime: now()
};
};
/*
* Animation methods
*/
Kinetic.Animation.prototype = {
/**
* set layers to be redrawn on each animation frame
* @method
* @memberof Kinetic.Animation.prototype
* @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw.
*/
setLayers: function(layers) {
var lays = [];
// if passing in no layers
if (!layers) {
lays = [];
}
// if passing in an array of Layers
// NOTE: layers could be an array or Kinetic.Collection. for simplicity, I'm just inspecting
// the length property to check for both cases
else if (layers.length > 0) {
lays = layers;
}
// if passing in a Layer
else {
lays = [layers];
}
this.layers = lays;
},
/**
* get layers
* @method
* @memberof Kinetic.Animation.prototype
*/
getLayers: function() {
return this.layers;
},
/**
* add layer. Returns true if the layer was added, and false if it was not
* @method
* @memberof Kinetic.Animation.prototype
* @param {Kinetic.Layer} layer
*/
addLayer: function(layer) {
var layers = this.layers,
len, n;
if (layers) {
len = layers.length;
// don't add the layer if it already exists
for (n = 0; n < len; n++) {
if (layers[n]._id === layer._id) {
return false;
}
}
}
else {
this.layers = [];
}
this.layers.push(layer);
return true;
},
/**
* determine if animation is running or not. returns true or false
* @method
* @memberof Kinetic.Animation.prototype
*/
isRunning: function() {
var a = Kinetic.Animation,
animations = a.animations,
len = animations.length,
n;
for(n = 0; n < len; n++) {
if(animations[n].id === this.id) {
return true;
}
}
return false;
},
/**
* start animation
* @method
* @memberof Kinetic.Animation.prototype
*/
start: function() {
var Anim = Kinetic.Animation;
this.stop();
this.frame.timeDiff = 0;
this.frame.lastTime = now();
Anim._addAnimation(this);
},
/**
* stop animation
* @method
* @memberof Kinetic.Animation.prototype
*/
stop: function() {
Kinetic.Animation._removeAnimation(this);
},
_updateFrameObject: function(time) {
this.frame.timeDiff = time - this.frame.lastTime;
this.frame.lastTime = time;
this.frame.time += this.frame.timeDiff;
this.frame.frameRate = 1000 / this.frame.timeDiff;
}
};
Kinetic.Animation.animations = [];
Kinetic.Animation.animIdCounter = 0;
Kinetic.Animation.animRunning = false;
Kinetic.Animation._addAnimation = function(anim) {
this.animations.push(anim);
this._handleAnimation();
};
Kinetic.Animation._removeAnimation = function(anim) {
var id = anim.id,
animations = this.animations,
len = animations.length,
n;
for(n = 0; n < len; n++) {
if(animations[n].id === id) {
this.animations.splice(n, 1);
break;
}
}
};
Kinetic.Animation._runFrames = function() {
var layerHash = {},
animations = this.animations,
anim, layers, func, n, i, layersLen, layer, key;
/*
* loop through all animations and execute animation
* function. if the animation object has specified node,
* we can add the node to the nodes hash to eliminate
* drawing the same node multiple times. The node property
* can be the stage itself or a layer
*/
/*
* WARNING: don't cache animations.length because it could change while
* the for loop is running, causing a JS error
*/
for(n = 0; n < animations.length; n++) {
anim = animations[n];
layers = anim.layers;
func = anim.func;
anim._updateFrameObject(now());
layersLen = layers.length;
for (i=0; i<layersLen; i++) {
layer = layers[i];
if(layer._id !== undefined) {
layerHash[layer._id] = layer;
}
}
// if animation object has a function, execute it
if(func) {
func.call(anim, anim.frame);
}
}
for(key in layerHash) {
layerHash[key].draw();
}
};
Kinetic.Animation._animationLoop = function() {
var Anim = Kinetic.Animation;
if(Anim.animations.length) {
requestAnimFrame(Anim._animationLoop);
Anim._runFrames();
}
else {
Anim.animRunning = false;
}
};
Kinetic.Animation._handleAnimation = function() {
var that = this;
if(!this.animRunning) {
this.animRunning = true;
that._animationLoop();
}
};
var moveTo = Kinetic.Node.prototype.moveTo;
Kinetic.Node.prototype.moveTo = function(container) {
moveTo.call(this, container);
};
/**
* batch draw
* @method
* @memberof Kinetic.Layer.prototype
*/
Kinetic.Layer.prototype.batchDraw = function() {
var that = this,
Anim = Kinetic.Animation;
if (!this.batchAnim) {
this.batchAnim = new Anim(function() {
if (that.lastBatchDrawTime && now() - that.lastBatchDrawTime > BATCH_DRAW_STOP_TIME_DIFF) {
that.batchAnim.stop();
}
}, this);
}
this.lastBatchDrawTime = now();
if (!this.batchAnim.isRunning()) {
this.draw();
this.batchAnim.start();
}
};
/**
* batch draw
* @method
* @memberof Kinetic.Stage.prototype
*/
Kinetic.Stage.prototype.batchDraw = function() {
this.getChildren().each(function(layer) {
layer.batchDraw();
});
};
})((1,eval)('this'));;(function() {
var blacklist = {
node: 1,
duration: 1,
easing: 1,
onFinish: 1,
yoyo: 1
},
PAUSED = 1,
PLAYING = 2,
REVERSING = 3,
idCounter = 0;
/**
* Tween constructor. Tweens enable you to animate a node between the current state and a new state.
* You can play, pause, reverse, seek, reset, and finish tweens. By default, tweens are animated using
* a linear easing. For more tweening options, check out {@link Kinetic.Easings}
* @constructor
* @memberof Kinetic
* @example
* // instantiate new tween which fully rotates a node in 1 second
* var tween = new Kinetic.Tween({<br>
* node: node,<br>
* rotationDeg: 360,<br>
* duration: 1,<br>
* easing: Kinetic.Easings.EaseInOut<br>
* });<br><br>
*
* // play tween<br>
* tween.play();<br><br>
*
* // pause tween<br>
* tween.pause();
*/
Kinetic.Tween = function(config) {
var that = this,
node = config.node,
nodeId = node._id,
duration = config.duration || 1,
easing = config.easing || Kinetic.Easings.Linear,
yoyo = !!config.yoyo,
key;
this.node = node;
this._id = idCounter++;
this.anim = new Kinetic.Animation(function() {
that.tween.onEnterFrame();
}, node.getLayer());
this.tween = new Tween(key, function(i) {
that._tweenFunc(i);
}, easing, 0, 1, duration * 1000, yoyo);
this._addListeners();
// init attrs map
if (!Kinetic.Tween.attrs[nodeId]) {
Kinetic.Tween.attrs[nodeId] = {};
}
if (!Kinetic.Tween.attrs[nodeId][this._id]) {
Kinetic.Tween.attrs[nodeId][this._id] = {};
}
// init tweens map
if (!Kinetic.Tween.tweens[nodeId]) {
Kinetic.Tween.tweens[nodeId] = {};
}
for (key in config) {
if (blacklist[key] === undefined) {
this._addAttr(key, config[key]);
}
}
this.reset();
// callbacks
this.onFinish = config.onFinish;
this.onReset = config.onReset;
};
// start/diff object = attrs.nodeId.tweenId.attr
Kinetic.Tween.attrs = {};
// tweenId = tweens.nodeId.attr
Kinetic.Tween.tweens = {};
Kinetic.Tween.prototype = {
_addAttr: function(key, end) {
var node = this.node,
nodeId = node._id,
start, diff, tweenId, n, len;
// remove conflict from tween map if it exists
tweenId = Kinetic.Tween.tweens[nodeId][key];
if (tweenId) {
delete Kinetic.Tween.attrs[nodeId][tweenId][key];
}
// add to tween map
start = node.getAttr(key);
if (Kinetic.Util._isArray(end)) {
diff = [];
len = end.length;
for (n=0; n<len; n++) {
diff.push(end[n] - start[n]);
}
}
else {
diff = end - start;
}
Kinetic.Tween.attrs[nodeId][this._id][key] = {
start: start,
diff: diff
};
Kinetic.Tween.tweens[nodeId][key] = this._id;
},
_tweenFunc: function(i) {
var node = this.node,
attrs = Kinetic.Tween.attrs[node._id][this._id],
key, attr, start, diff, newVal, n, len;
for (key in attrs) {
attr = attrs[key];
start = attr.start;
diff = attr.diff;
if (Kinetic.Util._isArray(start)) {
newVal = [];
len = start.length;
for (n=0; n<len; n++) {
newVal.push(start[n] + (diff[n] * i));
}
}
else {
newVal = start + (diff * i);
}
node.setAttr(key, newVal);
}
},
_addListeners: function() {
var that = this;
// start listeners
this.tween.onPlay = function() {
that.anim.start();
};
this.tween.onReverse = function() {
that.anim.start();
};
// stop listeners
this.tween.onPause = function() {
that.anim.stop();
};
this.tween.onFinish = function() {
if (that.onFinish) {
that.onFinish();
}
};
this.tween.onReset = function() {
if (that.onReset) {
that.onReset();
}
};
},
/**
* play
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
play: function() {
this.tween.play();
return this;
},
/**
* reverse
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
reverse: function() {
this.tween.reverse();
return this;
},
/**
* reset
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
reset: function() {
var node = this.node;
this.tween.reset();
return this;
},
/**
* seek
* @method
* @memberof Kinetic.Tween.prototype
* @param {Integer} t time in seconds between 0 and the duration
* @returns {Tween}
*/
seek: function(t) {
var node = this.node;
this.tween.seek(t * 1000);
return this;
},
/**
* pause
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
pause: function() {
this.tween.pause();
return this;
},
/**
* finish
* @method
* @memberof Kinetic.Tween.prototype
* @returns {Tween}
*/
finish: function() {
var node = this.node;
this.tween.finish();
return this;
},
/**
* destroy
* @method
* @memberof Kinetic.Tween.prototype
*/
destroy: function() {
var nodeId = this.node._id,
thisId = this._id,
attrs = Kinetic.Tween.tweens[nodeId],
key;
this.pause();
for (key in attrs) {
delete Kinetic.Tween.tweens[nodeId][key];
}
delete Kinetic.Tween.attrs[nodeId][thisId];
}
};
var Tween = function(prop, propFunc, func, begin, finish, duration, yoyo) {
this.prop = prop;
this.propFunc = propFunc;
this.begin = begin;
this._pos = begin;
this.duration = duration;
this._change = 0;
this.prevPos = 0;
this.yoyo = yoyo;
this._time = 0;
this._position = 0;
this._startTime = 0;
this._finish = 0;
this.func = func;
this._change = finish - this.begin;
this.pause();
};
/*
* Tween methods
*/
Tween.prototype = {
fire: function(str) {
var handler = this[str];
if (handler) {
handler();
}
},
setTime: function(t) {
if(t > this.duration) {
if(this.yoyo) {
this._time = this.duration;
this.reverse();
}
else {
this.finish();
}
}
else if(t < 0) {
if(this.yoyo) {
this._time = 0;
this.play();
}
else {
this.reset();
}
}
else {
this._time = t;
this.update();
}
},
getTime: function() {
return this._time;
},
setPosition: function(p) {
this.prevPos = this._pos;
this.propFunc(p);
this._pos = p;
},
getPosition: function(t) {
if(t === undefined) {
t = this._time;
}
return this.func(t, this.begin, this._change, this.duration);
},
play: function() {
this.state = PLAYING;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onPlay');
},
reverse: function() {
this.state = REVERSING;
this._time = this.duration - this._time;
this._startTime = this.getTimer() - this._time;
this.onEnterFrame();
this.fire('onReverse');
},
seek: function(t) {
this.pause();
this._time = t;
this.update();
this.fire('onSeek');
},
reset: function() {
this.pause();
this._time = 0;
this.update();
this.fire('onReset');
},
finish: function() {
this.pause();
this._time = this.duration;
this.update();
this.fire('onFinish');
},
update: function() {
this.setPosition(this.getPosition(this._time));
},
onEnterFrame: function() {
var t = this.getTimer() - this._startTime;
if(this.state === PLAYING) {
this.setTime(t);
}
else if (this.state === REVERSING) {
this.setTime(this.duration - t);
}
},
pause: function() {
this.state = PAUSED;
this.fire('onPause');
},
getTimer: function() {
return new Date().getTime();
}
};
/*
* These eases were ported from an Adobe Flash tweening library to JavaScript
* by Xaric
*/
/**
* @namespace Easings
* @memberof Kinetic
*/
Kinetic.Easings = {
/**
* back ease in
* @function
* @memberof Kinetic.Easings
*/
'BackEaseIn': function(t, b, c, d) {
var s = 1.70158;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
/**
* back ease out
* @function
* @memberof Kinetic.Easings
*/
'BackEaseOut': function(t, b, c, d) {
var s = 1.70158;
return c * (( t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
/**
* back ease in out
* @function
* @memberof Kinetic.Easings
*/
'BackEaseInOut': function(t, b, c, d) {
var s = 1.70158;
if((t /= d / 2) < 1) {
return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
}
return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
},
/**
* elastic ease in
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseIn': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d) == 1) {
return b + c;
}
if(!p) {
p = d * 0.3;
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
},
/**
* elastic ease out
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseOut': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d) == 1) {
return b + c;
}
if(!p) {
p = d * 0.3;
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b);
},
/**
* elastic ease in out
* @function
* @memberof Kinetic.Easings
*/
'ElasticEaseInOut': function(t, b, c, d, a, p) {
// added s = 0
var s = 0;
if(t === 0) {
return b;
}
if((t /= d / 2) == 2) {
return b + c;
}
if(!p) {
p = d * (0.3 * 1.5);
}
if(!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p / (2 * Math.PI) * Math.asin(c / a);
}
if(t < 1) {
return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * 0.5 + c + b;
},
/**
* bounce ease out
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseOut': function(t, b, c, d) {
if((t /= d) < (1 / 2.75)) {
return c * (7.5625 * t * t) + b;
}
else if(t < (2 / 2.75)) {
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
}
else if(t < (2.5 / 2.75)) {
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
}
else {
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
}
},
/**
* bounce ease in
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseIn': function(t, b, c, d) {
return c - Kinetic.Easings.BounceEaseOut(d - t, 0, c, d) + b;
},
/**
* bounce ease in out
* @function
* @memberof Kinetic.Easings
*/
'BounceEaseInOut': function(t, b, c, d) {
if(t < d / 2) {
return Kinetic.Easings.BounceEaseIn(t * 2, 0, c, d) * 0.5 + b;
}
else {
return Kinetic.Easings.BounceEaseOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
},
/**
* ease in
* @function
* @memberof Kinetic.Easings
*/
'EaseIn': function(t, b, c, d) {
return c * (t /= d) * t + b;
},
/**
* ease out
* @function
* @memberof Kinetic.Easings
*/
'EaseOut': function(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
/**
* ease in out
* @function
* @memberof Kinetic.Easings
*/
'EaseInOut': function(t, b, c, d) {
if((t /= d / 2) < 1) {
return c / 2 * t * t + b;
}
return -c / 2 * ((--t) * (t - 2) - 1) + b;
},
/**
* strong ease in
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseIn': function(t, b, c, d) {
return c * (t /= d) * t * t * t * t + b;
},
/**
* strong ease out
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseOut': function(t, b, c, d) {
return c * (( t = t / d - 1) * t * t * t * t + 1) + b;
},
/**
* strong ease in out
* @function
* @memberof Kinetic.Easings
*/
'StrongEaseInOut': function(t, b, c, d) {
if((t /= d / 2) < 1) {
return c / 2 * t * t * t * t * t + b;
}
return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
},
/**
* linear
* @function
* @memberof Kinetic.Easings
*/
'Linear': function(t, b, c, d) {
return c * t / d + b;
}
};
})();
;(function() {
Kinetic.DD = {
// properties
anim: new Kinetic.Animation(),
isDragging: false,
offset: {
x: 0,
y: 0
},
node: null,
// methods
_drag: function(evt) {
var dd = Kinetic.DD,
node = dd.node;
if(node) {
if(!dd.isDragging) {
var pos = node.getStage().getPointerPosition();
var dragDistance = node.dragDistance();
var distance = Math.max(
Math.abs(pos.x - dd.startPointerPos.x),
Math.abs(pos.y - dd.startPointerPos.y)
);
if (distance < dragDistance) {
return;
}
}
node._setDragPosition(evt);
if(!dd.isDragging) {
dd.isDragging = true;
node.fire('dragstart', {
type : 'dragstart',
target : node,
evt : evt
}, true);
}
// execute ondragmove if defined
node.fire('dragmove', {
type : 'dragmove',
target : node,
evt : evt
}, true);
}
},
_endDragBefore: function(evt) {
var dd = Kinetic.DD,
node = dd.node,
nodeType, layer;
if(node) {
nodeType = node.nodeType;
layer = node.getLayer();
dd.anim.stop();
// only fire dragend event if the drag and drop
// operation actually started.
if(dd.isDragging) {
dd.isDragging = false;
Kinetic.listenClickTap = false;
if (evt) {
evt.dragEndNode = node;
}
}
delete dd.node;
(layer || node).draw();
}
},
_endDragAfter: function(evt) {
evt = evt || {};
var dragEndNode = evt.dragEndNode;
if (evt && dragEndNode) {
dragEndNode.fire('dragend', {
type : 'dragend',
target : dragEndNode,
evt : evt
}, true);
}
}
};
// Node extenders
/**
* initiate drag and drop
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.startDrag = function() {
var dd = Kinetic.DD,
stage = this.getStage(),
layer = this.getLayer(),
pos = stage.getPointerPosition(),
ap = this.getAbsolutePosition();
if(pos) {
if (dd.node) {
dd.node.stopDrag();
}
dd.node = this;
dd.startPointerPos = pos;
dd.offset.x = pos.x - ap.x;
dd.offset.y = pos.y - ap.y;
dd.anim.setLayers(layer || this.getLayers());
dd.anim.start();
this._setDragPosition();
}
};
Kinetic.Node.prototype._setDragPosition = function(evt) {
var dd = Kinetic.DD,
pos = this.getStage().getPointerPosition(),
dbf = this.getDragBoundFunc();
if (!pos) {
return;
}
var newNodePos = {
x: pos.x - dd.offset.x,
y: pos.y - dd.offset.y
};
if(dbf !== undefined) {
newNodePos = dbf.call(this, newNodePos, evt);
}
this.setAbsolutePosition(newNodePos);
};
/**
* stop drag and drop
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.stopDrag = function() {
var dd = Kinetic.DD,
evt = {};
dd._endDragBefore(evt);
dd._endDragAfter(evt);
};
Kinetic.Node.prototype.setDraggable = function(draggable) {
this._setAttr('draggable', draggable);
this._dragChange();
};
var origDestroy = Kinetic.Node.prototype.destroy;
Kinetic.Node.prototype.destroy = function() {
var dd = Kinetic.DD;
// stop DD
if(dd.node && dd.node._id === this._id) {
this.stopDrag();
}
origDestroy.call(this);
};
/**
* determine if node is currently in drag and drop mode
* @method
* @memberof Kinetic.Node.prototype
*/
Kinetic.Node.prototype.isDragging = function() {
var dd = Kinetic.DD;
return dd.node && dd.node._id === this._id && dd.isDragging;
};
Kinetic.Node.prototype._listenDrag = function() {
var that = this;
this._dragCleanup();
if (this.getClassName() === 'Stage') {
this.on('contentMousedown.kinetic contentTouchstart.kinetic', function(evt) {
if(!Kinetic.DD.node) {
that.startDrag(evt);
}
});
}
else {
this.on('mousedown.kinetic touchstart.kinetic', function(evt) {
if(!Kinetic.DD.node) {
that.startDrag(evt);
}
});
}
// listening is required for drag and drop
/*
this._listeningEnabled = true;
this._clearSelfAndAncestorCache('listeningEnabled');
*/
};
Kinetic.Node.prototype._dragChange = function() {
if(this.attrs.draggable) {
this._listenDrag();
}
else {
// remove event listeners
this._dragCleanup();
/*
* force drag and drop to end
* if this node is currently in
* drag and drop mode
*/
var stage = this.getStage();
var dd = Kinetic.DD;
if(stage && dd.node && dd.node._id === this._id) {
dd.node.stopDrag();
}
}
};
Kinetic.Node.prototype._dragCleanup = function() {
if (this.getClassName() === 'Stage') {
this.off('contentMousedown.kinetic');
this.off('contentTouchstart.kinetic');
} else {
this.off('mousedown.kinetic');
this.off('touchstart.kinetic');
}
};
Kinetic.Factory.addGetterSetter(Kinetic.Node, 'dragBoundFunc');
/**
* get/set drag bound function. This is used to override the default
* drag and drop position
* @name dragBoundFunc
* @method
* @memberof Kinetic.Node.prototype
* @param {Function} dragBoundFunc
* @returns {Function}
* @example
* // get drag bound function<br>
* var dragBoundFunc = node.dragBoundFunc();<br><br>
*
* // create vertical drag and drop<br>
* node.dragBoundFunc(function(){<br>
* return {<br>
* x: this.getAbsolutePosition().x,<br>
* y: pos.y<br>
* };<br>
* });
*/
Kinetic.Factory.addGetter(Kinetic.Node, 'draggable', false);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'draggable');
/**
* get/set draggable flag
* @name draggable
* @method
* @memberof Kinetic.Node.prototype
* @param {Boolean} draggable
* @returns {Boolean}
* @example
* // get draggable flag<br>
* var draggable = node.draggable();<br><br>
*
* // enable drag and drop<br>
* node.draggable(true);<br><br>
*
* // disable drag and drop<br>
* node.draggable(false);
*/
var html = Kinetic.document.documentElement;
html.addEventListener('mouseup', Kinetic.DD._endDragBefore, true);
html.addEventListener('touchend', Kinetic.DD._endDragBefore, true);
html.addEventListener('mouseup', Kinetic.DD._endDragAfter, false);
html.addEventListener('touchend', Kinetic.DD._endDragAfter, false);
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.Container, {
__init: function(config) {
this.children = new Kinetic.Collection();
Kinetic.Node.call(this, config);
},
/**
* returns a {@link Kinetic.Collection} of direct descendant nodes
* @method
* @memberof Kinetic.Container.prototype
* @param {Function} [filterFunc] filter function
* @returns {Kinetic.Collection}
* @example
* // get all children<br>
* var children = layer.getChildren();<br><br>
*
* // get only circles<br>
* var circles = layer.getChildren(function(node){<br>
* return node.getClassName() === 'Circle';<br>
* });
*/
getChildren: function(predicate) {
if (!predicate) {
return this.children;
} else {
var results = new Kinetic.Collection();
this.children.each(function(child){
if (predicate(child)) {
results.push(child);
}
});
return results;
}
},
/**
* determine if node has children
* @method
* @memberof Kinetic.Container.prototype
* @returns {Boolean}
*/
hasChildren: function() {
return this.getChildren().length > 0;
},
/**
* remove all children
* @method
* @memberof Kinetic.Container.prototype
*/
removeChildren: function() {
var children = Kinetic.Collection.toCollection(this.children);
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
// reset parent to prevent many _setChildrenIndices calls
delete child.parent;
child.index = 0;
if (child.hasChildren()) {
child.removeChildren();
}
child.remove();
}
children = null;
this.children = new Kinetic.Collection();
return this;
},
/**
* destroy all children
* @method
* @memberof Kinetic.Container.prototype
*/
destroyChildren: function() {
var children = Kinetic.Collection.toCollection(this.children);
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
// reset parent to prevent many _setChildrenIndices calls
delete child.parent;
child.index = 0;
child.destroy();
}
children = null;
this.children = new Kinetic.Collection();
return this;
},
/**
* Add node or nodes to container.
* @method
* @memberof Kinetic.Container.prototype
* @param {...Kinetic.Node} child
* @returns {Container}
* @example
* layer.add(shape1, shape2, shape3);
*/
add: function(child) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return;
}
if (child.getParent()) {
child.moveTo(this);
return;
}
var children = this.children;
this._validateAdd(child);
child.index = children.length;
child.parent = this;
children.push(child);
this._fire('add', {
child: child
});
// chainable
return this;
},
destroy: function() {
// destroy children
if (this.hasChildren()) {
this.destroyChildren();
}
// then destroy self
Kinetic.Node.prototype.destroy.call(this);
},
/**
* return a {@link Kinetic.Collection} of nodes that match the selector. Use '#' for id selections
* and '.' for name selections. You can also select by type or class name. Pass multiple selectors
* separated by a space.
* @method
* @memberof Kinetic.Container.prototype
* @param {String} selector
* @returns {Collection}
* @example
* // select node with id foo<br>
* var node = stage.find('#foo');<br><br>
*
* // select nodes with name bar inside layer<br>
* var nodes = layer.find('.bar');<br><br>
*
* // select all groups inside layer<br>
* var nodes = layer.find('Group');<br><br>
*
* // select all rectangles inside layer<br>
* var nodes = layer.find('Rect');<br><br>
*
* // select node with an id of foo or a name of bar inside layer<br>
* var nodes = layer.find('#foo, .bar');
*/
find: function(selector) {
var retArr = [],
selectorArr = selector.replace(/ /g, '').split(','),
len = selectorArr.length,
n, i, sel, arr, node, children, clen;
for (n = 0; n < len; n++) {
sel = selectorArr[n];
// id selector
if(sel.charAt(0) === '#') {
node = this._getNodeById(sel.slice(1));
if(node) {
retArr.push(node);
}
}
// name selector
else if(sel.charAt(0) === '.') {
arr = this._getNodesByName(sel.slice(1));
retArr = retArr.concat(arr);
}
// unrecognized selector, pass to children
else {
children = this.getChildren();
clen = children.length;
for(i = 0; i < clen; i++) {
retArr = retArr.concat(children[i]._get(sel));
}
}
}
return Kinetic.Collection.toCollection(retArr);
},
_getNodeById: function(key) {
var node = Kinetic.ids[key];
if(node !== undefined && this.isAncestorOf(node)) {
return node;
}
return null;
},
_getNodesByName: function(key) {
var arr = Kinetic.names[key] || [];
return this._getDescendants(arr);
},
_get: function(selector) {
var retArr = Kinetic.Node.prototype._get.call(this, selector);
var children = this.getChildren();
var len = children.length;
for(var n = 0; n < len; n++) {
retArr = retArr.concat(children[n]._get(selector));
}
return retArr;
},
// extenders
toObject: function() {
var obj = Kinetic.Node.prototype.toObject.call(this);
obj.children = [];
var children = this.getChildren();
var len = children.length;
for(var n = 0; n < len; n++) {
var child = children[n];
obj.children.push(child.toObject());
}
return obj;
},
_getDescendants: function(arr) {
var retArr = [];
var len = arr.length;
for(var n = 0; n < len; n++) {
var node = arr[n];
if(this.isAncestorOf(node)) {
retArr.push(node);
}
}
return retArr;
},
/**
* determine if node is an ancestor
* of descendant
* @method
* @memberof Kinetic.Container.prototype
* @param {Kinetic.Node} node
*/
isAncestorOf: function(node) {
var parent = node.getParent();
while(parent) {
if(parent._id === this._id) {
return true;
}
parent = parent.getParent();
}
return false;
},
clone: function(obj) {
// call super method
var node = Kinetic.Node.prototype.clone.call(this, obj);
this.getChildren().each(function(no) {
node.add(no.clone());
});
return node;
},
/**
* get all shapes that intersect a point. Note: because this method must clear a temporary
* canvas and redraw every shape inside the container, it should only be used for special sitations
* because it performs very poorly. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @memberof Kinetic.Container.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Array} array of shapes
*/
getAllIntersections: function(pos) {
var arr = [];
this.find('Shape').each(function(shape) {
if(shape.isVisible() && shape.intersects(pos)) {
arr.push(shape);
}
});
return arr;
},
_setChildrenIndices: function() {
this.children.each(function(child, n) {
child.index = n;
});
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas()),
context = canvas && canvas.getContext(),
cachedCanvas = this._cache.canvas,
cachedSceneCanvas = cachedCanvas && cachedCanvas.scene;
if (this.isVisible()) {
if (cachedSceneCanvas) {
this._drawCachedSceneCanvas(context);
}
else {
this._drawChildren(canvas, 'drawScene', top);
}
}
return this;
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.hitCanvas),
context = canvas && canvas.getContext(),
cachedCanvas = this._cache.canvas,
cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if (this.shouldDrawHit()) {
if (cachedHitCanvas) {
this._drawCachedHitCanvas(context);
}
else {
this._drawChildren(canvas, 'drawHit', top);
}
}
return this;
},
_drawChildren: function(canvas, drawMethod, top) {
var layer = this.getLayer(),
context = canvas && canvas.getContext(),
clipWidth = this.getClipWidth(),
clipHeight = this.getClipHeight(),
hasClip = clipWidth && clipHeight,
clipX, clipY;
if (hasClip && layer) {
clipX = this.getClipX();
clipY = this.getClipY();
context.save();
layer._applyTransform(this, context);
context.beginPath();
context.rect(clipX, clipY, clipWidth, clipHeight);
context.clip();
context.reset();
}
this.children.each(function(child) {
child[drawMethod](canvas, top);
});
if (hasClip) {
context.restore();
}
}
});
Kinetic.Util.extend(Kinetic.Container, Kinetic.Node);
// deprecated methods
Kinetic.Container.prototype.get = Kinetic.Container.prototype.find;
// add getters setters
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Container, 'clip', ['x', 'y', 'width', 'height']);
/**
* get/set clip
* @method
* @name clip
* @memberof Kinetic.Container.prototype
* @param {Object} clip
* @param {Number} clip.x
* @param {Number} clip.y
* @param {Number} clip.width
* @param {Number} clip.height
* @returns {Object}
* @example
* // get clip<br>
* var clip = container.clip();<br><br>
*
* // set clip<br>
* container.setClip({<br>
* x: 20,<br>
* y: 20,<br>
* width: 20,<br>
* height: 20<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipX');
/**
* get/set clip x
* @name clipX
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get clip x<br>
* var clipX = container.clipX();<br><br>
*
* // set clip x<br>
* container.clipX(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipY');
/**
* get/set clip y
* @name clipY
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get clip y<br>
* var clipY = container.clipY();<br><br>
*
* // set clip y<br>
* container.clipY(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipWidth');
/**
* get/set clip width
* @name clipWidth
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get clip width<br>
* var clipWidth = container.clipWidth();<br><br>
*
* // set clip width<br>
* container.clipWidth(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipHeight');
/**
* get/set clip height
* @name clipHeight
* @method
* @memberof Kinetic.Container.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get clip height<br>
* var clipHeight = container.clipHeight();<br><br>
*
* // set clip height<br>
* container.clipHeight(100);
*/
Kinetic.Collection.mapMethods(Kinetic.Container);
})();
;(function() {
var HAS_SHADOW = 'hasShadow';
function _fillFunc(context) {
context.fill();
}
function _strokeFunc(context) {
context.stroke();
}
function _fillFuncHit(context) {
context.fill();
}
function _strokeFuncHit(context) {
context.stroke();
}
function _clearHasShadowCache() {
this._clearCache(HAS_SHADOW);
}
Kinetic.Util.addMethods(Kinetic.Shape, {
__init: function(config) {
this.nodeType = 'Shape';
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this._fillFuncHit = _fillFuncHit;
this._strokeFuncHit = _strokeFuncHit;
// set colorKey
var shapes = Kinetic.shapes;
var key;
while(true) {
key = Kinetic.Util.getRandomColor();
if(key && !( key in shapes)) {
break;
}
}
this.colorKey = key;
shapes[key] = this;
// call super constructor
Kinetic.Node.call(this, config);
this.on('shadowColorChange.kinetic shadowBlurChange.kinetic shadowOffsetChange.kinetic shadowOpacityChange.kinetic shadowEnabledChange.kinetic', _clearHasShadowCache);
},
hasChildren: function() {
return false;
},
getChildren: function() {
return [];
},
/**
* get canvas context tied to the layer
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Kinetic.Context}
*/
getContext: function() {
return this.getLayer().getContext();
},
/**
* get canvas renderer tied to the layer. Note that this returns a canvas renderer, not a canvas element
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Kinetic.Canvas}
*/
getCanvas: function() {
return this.getLayer().getCanvas();
},
/**
* returns whether or not a shadow will be rendered
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasShadow: function() {
return this._getCache(HAS_SHADOW, this._hasShadow);
},
_hasShadow: function() {
return this.getShadowEnabled() && (this.getShadowOpacity() !== 0 && !!(this.getShadowColor() || this.getShadowBlur() || this.getShadowOffsetX() || this.getShadowOffsetY()));
},
/**
* returns whether or not the shape will be filled
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasFill: function() {
return !!(this.getFill() || this.getFillPatternImage() || this.getFillLinearGradientColorStops() || this.getFillRadialGradientColorStops());
},
/**
* returns whether or not the shape will be stroked
* @method
* @memberof Kinetic.Shape.prototype
* @returns {Boolean}
*/
hasStroke: function() {
return !!(this.stroke() || this.strokeRed() || this.strokeGreen() || this.strokeBlue());
},
_get: function(selector) {
return this.className === selector || this.nodeType === selector ? [this] : [];
},
/**
* determines if point is in the shape, regardless if other shapes are on top of it. Note: because
* this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times
* consecutively. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible
* because it performs much better
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} point
* @param {Number} point.x
* @param {Number} point.y
* @returns {Boolean}
*/
intersects: function(pos) {
var stage = this.getStage(),
bufferHitCanvas = stage.bufferHitCanvas,
p;
bufferHitCanvas.getContext().clear();
this.drawScene(bufferHitCanvas);
p = bufferHitCanvas.context.getImageData(Math.round(pos.x), Math.round(pos.y), 1, 1).data;
return p[3] > 0;
},
// extends Node.prototype.destroy
destroy: function() {
Kinetic.Node.prototype.destroy.call(this);
delete Kinetic.shapes[this.colorKey];
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasFill() && this.hasStroke() && this.getStage();
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || layer.getCanvas(),
context = canvas.getContext(),
cachedCanvas = this._cache.canvas,
drawFunc = this.sceneFunc(),
hasShadow = this.hasShadow(),
stage, bufferCanvas, bufferContext;
if(this.isVisible()) {
if (cachedCanvas) {
this._drawCachedSceneCanvas(context);
}
else if (drawFunc) {
context.save();
// if buffer canvas is needed
if (this._useBufferCanvas()) {
stage = this.getStage();
bufferCanvas = stage.bufferCanvas;
bufferContext = bufferCanvas.getContext();
bufferContext.clear();
bufferContext.save();
bufferContext._applyLineJoin(this);
layer._applyTransform(this, bufferContext, top);
drawFunc.call(this, bufferContext);
bufferContext.restore();
if (hasShadow) {
context.save();
context._applyShadow(this);
context.drawImage(bufferCanvas._canvas, 0, 0);
context.restore();
}
context._applyOpacity(this);
context.drawImage(bufferCanvas._canvas, 0, 0);
}
// if buffer canvas is not needed
else {
context._applyLineJoin(this);
layer._applyTransform(this, context, top);
if (hasShadow) {
context.save();
context._applyShadow(this);
drawFunc.call(this, context);
context.restore();
}
context._applyOpacity(this);
drawFunc.call(this, context);
}
context.restore();
}
}
return this;
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || layer.hitCanvas,
context = canvas.getContext(),
drawFunc = this.hitFunc() || this.sceneFunc(),
cachedCanvas = this._cache.canvas,
cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
if(this.shouldDrawHit()) {
if (cachedHitCanvas) {
this._drawCachedHitCanvas(context);
}
else if (drawFunc) {
context.save();
context._applyLineJoin(this);
layer._applyTransform(this, context, top);
drawFunc.call(this, context);
context.restore();
}
}
return this;
},
/**
* draw hit graph using the cached scene canvas
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} alphaThreshold alpha channel threshold that determines whether or not
* a pixel should be drawn onto the hit graph. Must be a value between 0 and 255.
* The default is 0
* @returns {Kinetic.Shape}
* @example
* shape.cache();
* shape.drawHitFromCache();
*/
drawHitFromCache: function(alphaThreshold) {
var threshold = alphaThreshold || 0,
cachedCanvas = this._cache.canvas,
sceneCanvas = this._getCachedSceneCanvas(),
sceneContext = sceneCanvas.getContext(),
hitCanvas = cachedCanvas.hit,
hitContext = hitCanvas.getContext(),
width = sceneCanvas.getWidth(),
height = sceneCanvas.getHeight(),
sceneImageData, sceneData, hitImageData, hitData, len, rgbColorKey, i, alpha;
hitContext.clear();
try {
sceneImageData = sceneContext.getImageData(0, 0, width, height);
sceneData = sceneImageData.data;
hitImageData = hitContext.getImageData(0, 0, width, height);
hitData = hitImageData.data;
len = sceneData.length;
rgbColorKey = Kinetic.Util._hexToRgb(this.colorKey);
// replace non transparent pixels with color key
for(i = 0; i < len; i += 4) {
alpha = sceneData[i + 3];
if (alpha > threshold) {
hitData[i] = rgbColorKey.r;
hitData[i + 1] = rgbColorKey.g;
hitData[i + 2] = rgbColorKey.b;
hitData[i + 3] = 255;
}
}
hitContext.putImageData(hitImageData, 0, 0);
}
catch(e) {
Kinetic.Util.warn('Unable to draw hit graph from cached scene canvas. ' + e.message);
}
return this;
},
});
Kinetic.Util.extend(Kinetic.Shape, Kinetic.Node);
// add getters and setters
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'stroke');
/**
* get/set stroke color
* @name stroke
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get stroke color<br>
* var stroke = shape.stroke();<br><br>
*
* // set stroke color with color string<br>
* shape.stroke('green');<br><br>
*
* // set stroke color with hex<br>
* shape.stroke('#00ff00');<br><br>
*
* // set stroke color with rgb<br>
* shape.stroke('rgb(0,255,0)');<br><br>
*
* // set stroke color with rgba and make it 50% opaque<br>
* shape.stroke('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke red component
* @name strokeRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get stroke red component<br>
* var strokeRed = shape.strokeRed();<br><br>
*
* // set stroke red component<br>
* shape.strokeRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke green component
* @name strokeGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get stroke green component<br>
* var strokeGreen = shape.strokeGreen();<br><br>
*
* // set stroke green component<br>
* shape.strokeGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set stroke blue component
* @name strokeBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get stroke blue component<br>
* var strokeBlue = shape.strokeBlue();<br><br>
*
* // set stroke blue component<br>
* shape.strokeBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set stroke alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name strokeAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get stroke alpha component<br>
* var strokeAlpha = shape.strokeAlpha();<br><br>
*
* // set stroke alpha component<br>
* shape.strokeAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeWidth', 2);
/**
* get/set stroke width
* @name strokeWidth
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} strokeWidth
* @returns {Number}
* @example
* // get stroke width<br>
* var strokeWidth = shape.strokeWidth();<br><br>
*
* // set stroke width<br>
* shape.strokeWidth();
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineJoin');
/**
* get/set line join. Can be miter, round, or bevel. The
* default is miter
* @name lineJoin
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} lineJoin
* @returns {String}
* @example
* // get line join<br>
* var lineJoin = shape.lineJoin();<br><br>
*
* // set line join<br>
* shape.lineJoin('round');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineCap');
/**
* get/set line cap. Can be butt, round, or square
* @name lineCap
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} lineCap
* @returns {String}
* @example
* // get line cap<br>
* var lineCap = shape.lineCap();<br><br>
*
* // set line cap<br>
* shape.lineCap('round');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'sceneFunc');
/**
* get/set scene draw function
* @name sceneFunc
* @method
* @memberof Kinetic.Shape.prototype
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get scene draw function<br>
* var sceneFunc = shape.sceneFunc();<br><br>
*
* // set scene draw function<br>
* shape.sceneFunc(function(context) {<br>
* context.beginPath();<br>
* context.rect(0, 0, this.width(), this.height());<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'hitFunc');
/**
* get/set hit draw function
* @name hitFunc
* @method
* @memberof Kinetic.Shape.prototype
* @param {Function} drawFunc drawing function
* @returns {Function}
* @example
* // get hit draw function<br>
* var hitFunc = shape.hitFunc();<br><br>
*
* // set hit draw function<br>
* shape.hitFunc(function(context) {<br>
* context.beginPath();<br>
* context.rect(0, 0, this.width(), this.height());<br>
* context.closePath();<br>
* context.fillStrokeShape(this);<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dash');
/**
* get/set dash array for stroke.
* @name dash
* @method
* @memberof Kinetic.Shape.prototype
* @param {Array} dash
* @returns {Array}
* @example
* // apply dashed stroke that is 10px long and 5 pixels apart<br>
* line.dash([10, 5]);<br><br>
*
* // apply dashed stroke that is made up of alternating dashed<br>
* // lines that are 10px long and 20px apart, and dots that have<br>
* // a radius of 5px and are 20px apart<br>
* line.dash([10, 20, 0.001, 20]);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowColor');
/**
* get/set shadow color
* @name shadowColor
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get shadow color<br>
* var shadow = shape.shadowColor();<br><br>
*
* // set shadow color with color string<br>
* shape.shadowColor('green');<br><br>
*
* // set shadow color with hex<br>
* shape.shadowColor('#00ff00');<br><br>
*
* // set shadow color with rgb<br>
* shape.shadowColor('rgb(0,255,0)');<br><br>
*
* // set shadow color with rgba and make it 50% opaque<br>
* shape.shadowColor('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow red component
* @name shadowRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get shadow red component<br>
* var shadowRed = shape.shadowRed();<br><br>
*
* // set shadow red component<br>
* shape.shadowRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow green component
* @name shadowGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get shadow green component<br>
* var shadowGreen = shape.shadowGreen();<br><br>
*
* // set shadow green component<br>
* shape.shadowGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set shadow blue component
* @name shadowBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get shadow blue component<br>
* var shadowBlue = shape.shadowBlue();<br><br>
*
* // set shadow blue component<br>
* shape.shadowBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set shadow alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name shadowAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get shadow alpha component<br>
* var shadowAlpha = shape.shadowAlpha();<br><br>
*
* // set shadow alpha component<br>
* shape.shadowAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlur');
/**
* get/set shadow blur
* @name shadowBlur
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} blur
* @returns {Number}
* @example
* // get shadow blur<br>
* var shadowBlur = shape.shadowBlur();<br><br>
*
* // set shadow blur<br>
* shape.shadowBlur(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOpacity');
/**
* get/set shadow opacity. must be a value between 0 and 1
* @name shadowOpacity
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} opacity
* @returns {Number}
* @example
* // get shadow opacity<br>
* var shadowOpacity = shape.shadowOpacity();<br><br>
*
* // set shadow opacity<br>
* shape.shadowOpacity(0.5);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'shadowOffset', ['x', 'y']);
/**
* get/set shadow offset
* @name shadowOffset
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get shadow offset<br>
* var shadowOffset = shape.shadowOffset();<br><br>
*
* // set shadow offset<br>
* shape.shadowOffset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetX', 0);
/**
* get/set shadow offset x
* @name shadowOffsetX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get shadow offset x<br>
* var shadowOffsetX = shape.shadowOffsetX();<br><br>
*
* // set shadow offset x<br>
* shape.shadowOffsetX(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetY', 0);
/**
* get/set shadow offset y
* @name shadowOffsetY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get shadow offset y<br>
* var shadowOffsetY = shape.shadowOffsetY();<br><br>
*
* // set shadow offset y<br>
* shape.shadowOffsetY(5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternImage');
/**
* get/set fill pattern image
* @name fillPatternImage
* @method
* @memberof Kinetic.Shape.prototype
* @param {Image} image object
* @returns {Image}
* @example
* // get fill pattern image<br>
* var fillPatternImage = shape.fillPatternImage();<br><br>
*
* // set fill pattern image<br>
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* shape.fillPatternImage(imageObj);<br>
* };<br>
* imageObj.src = 'path/to/image/jpg';
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fill');
/**
* get/set fill color
* @name fill
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} color
* @returns {String}
* @example
* // get fill color<br>
* var fill = shape.fill();<br><br>
*
* // set fill color with color string<br>
* shape.fill('green');<br><br>
*
* // set fill color with hex<br>
* shape.fill('#00ff00');<br><br>
*
* // set fill color with rgb<br>
* shape.fill('rgb(0,255,0)');<br><br>
*
* // set fill color with rgba and make it 50% opaque<br>
* shape.fill('rgba(0,255,0,0.5');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRed', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill red component
* @name fillRed
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} red
* @returns {Integer}
* @example
* // get fill red component<br>
* var fillRed = shape.fillRed();<br><br>
*
* // set fill red component<br>
* shape.fillRed(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillGreen', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill green component
* @name fillGreen
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} green
* @returns {Integer}
* @example
* // get fill green component<br>
* var fillGreen = shape.fillGreen();<br><br>
*
* // set fill green component<br>
* shape.fillGreen(255);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillBlue', 0, Kinetic.Validators.RGBComponent);
/**
* get/set fill blue component
* @name fillBlue
* @method
* @memberof Kinetic.Shape.prototype
* @param {Integer} blue
* @returns {Integer}
* @example
* // get fill blue component<br>
* var fillBlue = shape.fillBlue();<br><br>
*
* // set fill blue component<br>
* shape.fillBlue(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillAlpha', 1, Kinetic.Validators.alphaComponent);
/**
* get/set fill alpha component. Alpha is a real number between 0 and 1. The default
* is 1.
* @name fillAlpha
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} alpha
* @returns {Number}
* @example
* // get fill alpha component<br>
* var fillAlpha = shape.fillAlpha();<br><br>
*
* // set fill alpha component<br>
* shape.fillAlpha(0.5);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternX', 0);
/**
* get/set fill pattern x
* @name fillPatternX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern x<br>
* var fillPatternX = shape.fillPatternX();<br><br>
*
* // set fill pattern x<br>
* shape.fillPatternX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternY', 0);
/**
* get/set fill pattern y
* @name fillPatternY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern y<br>
* var fillPatternY = shape.fillPatternY();<br><br>
*
* // set fill pattern y<br>
* shape.fillPatternY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientColorStops');
/**
* get/set fill linear gradient color stops
* @name fillLinearGradientColorStops
* @method
* @memberof Kinetic.Shape.prototype
* @param {Array} colorStops
* @returns {Array} colorStops
* @example
* // get fill linear gradient color stops<br>
* var colorStops = shape.fillLinearGradientColorStops();<br><br>
*
* // create a linear gradient that starts with red, changes to blue <br>
* // halfway through, and then changes to green<br>
* shape.fillLinearGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartRadius', 0);
/**
* get/set fill radial gradient start radius
* @name fillRadialGradientStartRadius
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient start radius<br>
* var startRadius = shape.fillRadialGradientStartRadius();<br><br>
*
* // set radial gradient start radius<br>
* shape.fillRadialGradientStartRadius(0);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndRadius', 0);
/**
* get/set fill radial gradient end radius
* @name fillRadialGradientEndRadius
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radial gradient end radius<br>
* var endRadius = shape.fillRadialGradientEndRadius();<br><br>
*
* // set radial gradient end radius<br>
* shape.fillRadialGradientEndRadius(100);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientColorStops');
/**
* get/set fill radial gradient color stops
* @name fillRadialGradientColorStops
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} colorStops
* @returns {Array}
* @example
* // get fill radial gradient color stops<br>
* var colorStops = shape.fillRadialGradientColorStops();<br><br>
*
* // create a radial gradient that starts with red, changes to blue <br>
* // halfway through, and then changes to green<br>
* shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRepeat', 'repeat');
/**
* get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat'
* @name fillPatternRepeat
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} repeat
* @returns {String}
* @example
* // get fill pattern repeat<br>
* var repeat = shape.fillPatternRepeat();<br><br>
*
* // repeat pattern in x direction only<br>
* shape.fillPatternRepeat('repeat-x');<br><br>
*
* // do not repeat the pattern<br>
* shape.fillPatternRepeat('no repeat');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillEnabled', true);
/**
* get/set fill enabled flag
* @name fillEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get fill enabled flag<br>
* var fillEnabled = shape.fillEnabled();<br><br>
*
* // disable fill<br>
* shape.fillEnabled(false);<br><br>
*
* // enable fill<br>
* shape.fillEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeEnabled', true);
/**
* get/set stroke enabled flag
* @name strokeEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke enabled flag<br>
* var strokeEnabled = shape.strokeEnabled();<br><br>
*
* // disable stroke<br>
* shape.strokeEnabled(false);<br><br>
*
* // enable stroke<br>
* shape.strokeEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowEnabled', true);
/**
* get/set shadow enabled flag
* @name shadowEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get shadow enabled flag<br>
* var shadowEnabled = shape.shadowEnabled();<br><br>
*
* // disable shadow<br>
* shape.shadowEnabled(false);<br><br>
*
* // enable shadow<br>
* shape.shadowEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dashEnabled', true);
/**
* get/set dash enabled flag
* @name dashEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get dash enabled flag<br>
* var dashEnabled = shape.dashEnabled();<br><br>
*
* // disable dash<br>
* shape.dashEnabled(false);<br><br>
*
* // enable dash<br>
* shape.dashEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeScaleEnabled', true);
/**
* get/set strokeScale enabled flag
* @name strokeScaleEnabled
* @method
* @memberof Kinetic.Shape.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get stroke scale enabled flag<br>
* var strokeScaleEnabled = shape.strokeScaleEnabled();<br><br>
*
* // disable stroke scale<br>
* shape.strokeScaleEnabled(false);<br><br>
*
* // enable stroke scale<br>
* shape.strokeScaleEnabled(true);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPriority', 'color');
/**
* get/set fill priority. can be color, pattern, linear-gradient, or radial-gradient. The default is color.
* This is handy if you want to toggle between different fill types.
* @name fillPriority
* @method
* @memberof Kinetic.Shape.prototype
* @param {String} priority
* @returns {String}
* @example
* // get fill priority<br>
* var fillPriority = shape.fillPriority();<br><br>
*
* // set fill priority<br>
* shape.fillPriority('linear-gradient');
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternOffset', ['x', 'y']);
/**
* get/set fill pattern offset
* @name fillPatternOffset
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} offset
* @param {Number} offset.x
* @param {Number} offset.y
* @returns {Object}
* @example
* // get fill pattern offset<br>
* var patternOffset = shape.fillPatternOffset();<br><br>
*
* // set fill pattern offset<br>
* shape.fillPatternOffset({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetX', 0);
/**
* get/set fill pattern offset x
* @name fillPatternOffsetX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern offset x<br>
* var patternOffsetX = shape.fillPatternOffsetX();<br><br>
*
* // set fill pattern offset x<br>
* shape.fillPatternOffsetX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetY', 0);
/**
* get/set fill pattern offset y
* @name fillPatternOffsetY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern offset y<br>
* var patternOffsetY = shape.fillPatternOffsetY();<br><br>
*
* // set fill pattern offset y<br>
* shape.fillPatternOffsetY(10);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternScale', ['x', 'y']);
/**
* get/set fill pattern scale
* @name fillPatternScale
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} scale
* @param {Number} scale.x
* @param {Number} scale.y
* @returns {Object}
* @example
* // get fill pattern scale<br>
* var patternScale = shape.fillPatternScale();<br><br>
*
* // set fill pattern scale<br>
* shape.fillPatternScale({<br>
* x: 2<br>
* y: 2<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleX', 1);
/**
* get/set fill pattern scale x
* @name fillPatternScaleX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill pattern scale x<br>
* var patternScaleX = shape.fillPatternScaleX();<br><br>
*
* // set fill pattern scale x<br>
* shape.fillPatternScaleX(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleY', 1);
/**
* get/set fill pattern scale y
* @name fillPatternScaleY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill pattern scale y<br>
* var patternScaleY = shape.fillPatternScaleY();<br><br>
*
* // set fill pattern scale y<br>
* shape.fillPatternScaleY(2);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPoint', ['x', 'y']);
/**
* get/set fill linear gradient start point
* @name fillLinearGradientStartPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill linear gradient start point<br>
* var startPoint = shape.fillLinearGradientStartPoint();<br><br>
*
* // set fill linear gradient start point<br>
* shape.fillLinearGradientStartPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointX', 0);
/**
* get/set fill linear gradient start point x
* @name fillLinearGradientStartPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient start point x<br>
* var startPointX = shape.fillLinearGradientStartPointX();<br><br>
*
* // set fill linear gradient start point x<br>
* shape.fillLinearGradientStartPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointY', 0);
/**
* get/set fill linear gradient start point y
* @name fillLinearGradientStartPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient start point y<br>
* var startPointY = shape.fillLinearGradientStartPointY();<br><br>
*
* // set fill linear gradient start point y<br>
* shape.fillLinearGradientStartPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPoint', ['x', 'y']);
/**
* get/set fill linear gradient end point
* @name fillLinearGradientEndPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill linear gradient end point<br>
* var endPoint = shape.fillLinearGradientEndPoint();<br><br>
*
* // set fill linear gradient end point<br>
* shape.fillLinearGradientEndPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointX', 0);
/**
* get/set fill linear gradient end point x
* @name fillLinearGradientEndPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill linear gradient end point x<br>
* var endPointX = shape.fillLinearGradientEndPointX();<br><br>
*
* // set fill linear gradient end point x<br>
* shape.fillLinearGradientEndPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointY', 0);
/**
* get/set fill linear gradient end point y
* @name fillLinearGradientEndPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill linear gradient end point y<br>
* var endPointY = shape.fillLinearGradientEndPointY();<br><br>
*
* // set fill linear gradient end point y<br>
* shape.fillLinearGradientEndPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPoint', ['x', 'y']);
/**
* get/set fill radial gradient start point
* @name fillRadialGradientStartPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} startPoint
* @param {Number} startPoint.x
* @param {Number} startPoint.y
* @returns {Object}
* @example
* // get fill radial gradient start point<br>
* var startPoint = shape.fillRadialGradientStartPoint();<br><br>
*
* // set fill radial gradient start point<br>
* shape.fillRadialGradientStartPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointX', 0);
/**
* get/set fill radial gradient start point x
* @name fillRadialGradientStartPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient start point x<br>
* var startPointX = shape.fillRadialGradientStartPointX();<br><br>
*
* // set fill radial gradient start point x<br>
* shape.fillRadialGradientStartPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointY', 0);
/**
* get/set fill radial gradient start point y
* @name fillRadialGradientStartPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient start point y<br>
* var startPointY = shape.fillRadialGradientStartPointY();<br><br>
*
* // set fill radial gradient start point y<br>
* shape.fillRadialGradientStartPointY(20);
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPoint', ['x', 'y']);
/**
* get/set fill radial gradient end point
* @name fillRadialGradientEndPoint
* @method
* @memberof Kinetic.Shape.prototype
* @param {Object} endPoint
* @param {Number} endPoint.x
* @param {Number} endPoint.y
* @returns {Object}
* @example
* // get fill radial gradient end point<br>
* var endPoint = shape.fillRadialGradientEndPoint();<br><br>
*
* // set fill radial gradient end point<br>
* shape.fillRadialGradientEndPoint({<br>
* x: 20<br>
* y: 10<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointX', 0);
/**
* get/set fill radial gradient end point x
* @name fillRadialGradientEndPointX
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get fill radial gradient end point x<br>
* var endPointX = shape.fillRadialGradientEndPointX();<br><br>
*
* // set fill radial gradient end point x<br>
* shape.fillRadialGradientEndPointX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointY', 0);
/**
* get/set fill radial gradient end point y
* @name fillRadialGradientEndPointY
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get fill radial gradient end point y<br>
* var endPointY = shape.fillRadialGradientEndPointY();<br><br>
*
* // set fill radial gradient end point y<br>
* shape.fillRadialGradientEndPointY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRotation', 0);
/**
* get/set fill pattern rotation in degrees
* @name fillPatternRotation
* @method
* @memberof Kinetic.Shape.prototype
* @param {Number} rotation
* @returns {Kinetic.Shape}
* @example
* // get fill pattern rotation<br>
* var patternRotation = shape.fillPatternRotation();<br><br>
*
* // set fill pattern rotation<br>
* shape.fillPatternRotation(20);
*/
Kinetic.Factory.backCompat(Kinetic.Shape, {
dashArray: 'dash',
getDashArray: 'getDash',
setDashArray: 'getDash',
drawFunc: 'sceneFunc',
getDrawFunc: 'getSceneFunc',
setDrawFunc: 'setSceneFunc',
drawHitFunc: 'hitFunc',
getDrawHitFunc: 'getHitFunc',
setDrawHitFunc: 'setHitFunc'
});
Kinetic.Collection.mapMethods(Kinetic.Shape);
})();
;/*jshint unused:false */
(function() {
// CONSTANTS
var STAGE = 'Stage',
STRING = 'string',
PX = 'px',
MOUSEOUT = 'mouseout',
MOUSELEAVE = 'mouseleave',
MOUSEOVER = 'mouseover',
MOUSEENTER = 'mouseenter',
MOUSEMOVE = 'mousemove',
MOUSEDOWN = 'mousedown',
MOUSEUP = 'mouseup',
CLICK = 'click',
DBL_CLICK = 'dblclick',
TOUCHSTART = 'touchstart',
TOUCHEND = 'touchend',
TAP = 'tap',
DBL_TAP = 'dbltap',
TOUCHMOVE = 'touchmove',
CONTENT_MOUSEOUT = 'contentMouseout',
CONTENT_MOUSELEAVE = 'contentMouseleave',
CONTENT_MOUSEOVER = 'contentMouseover',
CONTENT_MOUSEENTER = 'contentMouseenter',
CONTENT_MOUSEMOVE = 'contentMousemove',
CONTENT_MOUSEDOWN = 'contentMousedown',
CONTENT_MOUSEUP = 'contentMouseup',
CONTENT_CLICK = 'contentClick',
CONTENT_DBL_CLICK = 'contentDblclick',
CONTENT_TOUCHSTART = 'contentTouchstart',
CONTENT_TOUCHEND = 'contentTouchend',
CONTENT_TAP = 'contentTap',
CONTENT_DBL_TAP = 'contentDbltap',
CONTENT_TOUCHMOVE = 'contentTouchmove',
DIV = 'div',
RELATIVE = 'relative',
INLINE_BLOCK = 'inline-block',
KINETICJS_CONTENT = 'kineticjs-content',
SPACE = ' ',
UNDERSCORE = '_',
CONTAINER = 'container',
EMPTY_STRING = '',
EVENTS = [MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEOUT, TOUCHSTART, TOUCHMOVE, TOUCHEND, MOUSEOVER],
// cached variables
eventsLength = EVENTS.length;
function addEvent(ctx, eventName) {
ctx.content.addEventListener(eventName, function(evt) {
ctx[UNDERSCORE + eventName](evt);
}, false);
}
Kinetic.Util.addMethods(Kinetic.Stage, {
___init: function(config) {
this.nodeType = STAGE;
// call super constructor
Kinetic.Container.call(this, config);
this._id = Kinetic.idCounter++;
this._buildDOM();
this._bindContentEvents();
this._enableNestedTransforms = false;
Kinetic.stages.push(this);
},
_validateAdd: function(child) {
if (child.getType() !== 'Layer') {
Kinetic.Util.error('You may only add layers to the stage.');
}
},
/**
* set container dom element which contains the stage wrapper div element
* @method
* @memberof Kinetic.Stage.prototype
* @param {DomElement} container can pass in a dom element or id string
*/
setContainer: function(container) {
if( typeof container === STRING) {
var id = container;
container = Kinetic.document.getElementById(container);
if (!container) {
throw 'Can not find container in document with id ' + id;
}
}
this._setAttr(CONTAINER, container);
return this;
},
shouldDrawHit: function() {
return true;
},
draw: function() {
Kinetic.Node.prototype.draw.call(this);
return this;
},
/**
* draw layer scene graphs
* @name draw
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* draw layer hit graphs
* @name drawHit
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* set height
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} height
*/
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this._resizeDOM();
return this;
},
/**
* set width
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} width
*/
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this._resizeDOM();
return this;
},
/**
* clear all layers
* @method
* @memberof Kinetic.Stage.prototype
*/
clear: function() {
var layers = this.children,
len = layers.length,
n;
for(n = 0; n < len; n++) {
layers[n].clear();
}
return this;
},
clone: function(obj) {
if (!obj) {
obj = {};
}
obj.container = Kinetic.document.createElement(DIV);
return Kinetic.Container.prototype.clone.call(this, obj);
},
/**
* destroy stage
* @method
* @memberof Kinetic.Stage.prototype
*/
destroy: function() {
var content = this.content;
Kinetic.Container.prototype.destroy.call(this);
if(content && Kinetic.Util._isInDocument(content)) {
this.getContainer().removeChild(content);
}
var index = Kinetic.stages.indexOf(this);
if (index > -1) {
Kinetic.stages.splice(index, 1);
}
},
/**
* get pointer position which can be a touch position or mouse position
* @method
* @memberof Kinetic.Stage.prototype
* @returns {Object}
*/
getPointerPosition: function() {
return this.pointerPos;
},
getStage: function() {
return this;
},
/**
* get stage content div element which has the
* the class name "kineticjs-content"
* @method
* @memberof Kinetic.Stage.prototype
*/
getContent: function() {
return this.content;
},
/**
* Creates a composite data URL and requires a callback because the composite is generated asynchronously.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toDataURL: function(config) {
config = config || {};
var mimeType = config.mimeType || null,
quality = config.quality || null,
x = config.x || 0,
y = config.y || 0,
canvas = new Kinetic.SceneCanvas({
width: config.width || this.getWidth(),
height: config.height || this.getHeight(),
pixelRatio: 1
}),
_context = canvas.getContext()._context,
layers = this.children;
if(x || y) {
_context.translate(-1 * x, -1 * y);
}
function drawLayer(n) {
var layer = layers[n],
layerUrl = layer.toDataURL(),
imageObj = new Kinetic.window.Image();
imageObj.onload = function() {
_context.drawImage(imageObj, 0, 0);
if(n < layers.length - 1) {
drawLayer(n + 1);
}
else {
config.callback(canvas.toDataURL(mimeType, quality));
}
};
imageObj.src = layerUrl;
}
drawLayer(0);
},
/**
* converts stage into an image.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toImage: function(config) {
var cb = config.callback;
config.callback = function(dataUrl) {
Kinetic.Util._getImage(dataUrl, function(img) {
cb(img);
});
};
this.toDataURL(config);
},
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Shape}
*/
getIntersection: function(pos) {
var layers = this.getChildren(),
len = layers.length,
end = len - 1,
n, shape;
for(n = end; n >= 0; n--) {
shape = layers[n].getIntersection(pos);
if (shape) {
return shape;
}
}
return null;
},
_resizeDOM: function() {
if(this.content) {
var width = this.getWidth(),
height = this.getHeight(),
layers = this.getChildren(),
len = layers.length,
n, layer;
// set content dimensions
this.content.style.width = width + PX;
this.content.style.height = height + PX;
this.bufferCanvas.setSize(width, height);
this.bufferHitCanvas.setSize(width, height);
// set layer dimensions
for(n = 0; n < len; n++) {
layer = layers[n];
layer.getCanvas().setSize(width, height);
layer.hitCanvas.setSize(width, height);
layer.draw();
}
}
},
/**
* add layer or layers to stage
* @method
* @memberof Kinetic.Stage.prototype
* @param {...Kinetic.Layer} layer
* @example
* stage.add(layer1, layer2, layer3);
*/
add: function(layer) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return;
}
Kinetic.Container.prototype.add.call(this, layer);
layer._setCanvasSize(this.width(), this.height());
// draw layer and append canvas to container
layer.draw();
this.content.appendChild(layer.canvas._canvas);
// chainable
return this;
},
getParent: function() {
return null;
},
getLayer: function() {
return null;
},
/**
* returns a {@link Kinetic.Collection} of layers
* @method
* @memberof Kinetic.Stage.prototype
*/
getLayers: function() {
return this.getChildren();
},
_bindContentEvents: function() {
for (var n = 0; n < eventsLength; n++) {
addEvent(this, EVENTS[n]);
}
},
_mouseover: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
this._fire(CONTENT_MOUSEOVER, {evt: evt});
}
},
_mouseout: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var targetShape = this.targetShape;
if(targetShape && !Kinetic.isDragging()) {
targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
this.pointerPos = undefined;
this._fire(CONTENT_MOUSEOUT, {evt: evt});
}
},
_mousemove: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var dd = Kinetic.DD,
shape = this.getIntersection(this.getPointerPosition());
if(shape && shape.isListening()) {
if(!Kinetic.isDragging() && (!this.targetShape || this.targetShape._id !== shape._id)) {
if(this.targetShape) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt}, shape);
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}, shape);
}
shape._fireAndBubble(MOUSEOVER, {evt: evt}, this.targetShape);
shape._fireAndBubble(MOUSEENTER, {evt: evt}, this.targetShape);
this.targetShape = shape;
}
else {
shape._fireAndBubble(MOUSEMOVE, {evt: evt});
}
}
/*
* if no shape was detected, clear target shape and try
* to run mouseout from previous target shape
*/
else {
if(this.targetShape && !Kinetic.isDragging()) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
}
// content event
this._fire(CONTENT_MOUSEMOVE, {evt: evt});
if(dd) {
dd._drag(evt);
}
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mousedown: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.clickStartShape = shape;
shape._fireAndBubble(MOUSEDOWN, {evt: evt});
}
// content event
this._fire(CONTENT_MOUSEDOWN, {evt: evt});
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mouseup: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var that = this,
shape = this.getIntersection(this.getPointerPosition()),
clickStartShape = this.clickStartShape,
fireDblClick = false;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
else {
Kinetic.inDblClickWindow = true;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(MOUSEUP, {evt: evt});
// detect if click or double click occurred
if(Kinetic.listenClickTap && clickStartShape && clickStartShape._id === shape._id) {
shape._fireAndBubble(CLICK, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_CLICK, {evt: evt});
}
}
}
// content events
this._fire(CONTENT_MOUSEUP, {evt: evt});
if (Kinetic.listenClickTap) {
this._fire(CONTENT_CLICK, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_CLICK, {evt: evt});
}
}
Kinetic.listenClickTap = false;
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_touchstart: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.tapStartShape = shape;
shape._fireAndBubble(TOUCHSTART, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content event
this._fire(CONTENT_TOUCHSTART, {evt: evt});
},
_touchend: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition()),
fireDblClick = false;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
else {
Kinetic.inDblClickWindow = true;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHEND, {evt: evt});
// detect if tap or double tap occurred
if(Kinetic.listenClickTap && shape._id === this.tapStartShape._id) {
shape._fireAndBubble(TAP, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_TAP, {evt: evt});
}
}
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content events
if (Kinetic.listenClickTap) {
this._fire(CONTENT_TOUCHEND, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_TAP, {evt: evt});
}
}
Kinetic.listenClickTap = false;
},
_touchmove: function(evt) {
this._setPointerPosition(evt);
var dd = Kinetic.DD,
shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHMOVE, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
this._fire(CONTENT_TOUCHMOVE, {evt: evt});
// start drag and drop
if(dd) {
dd._drag(evt);
}
},
_setPointerPosition: function(evt) {
var contentPosition = this._getContentPosition(),
offsetX = evt.offsetX,
clientX = evt.clientX,
x = null,
y = null,
touch;
evt = evt ? evt : window.event;
// touch events
if(evt.touches !== undefined) {
// currently, only handle one finger
if (evt.touches.length > 0) {
touch = evt.touches[0];
// get the information for finger #1
x = touch.clientX - contentPosition.left;
y = touch.clientY - contentPosition.top;
}
}
// mouse events
else {
// if offsetX is defined, assume that offsetY is defined as well
if (offsetX !== undefined) {
x = offsetX;
y = evt.offsetY;
}
// we unforunately have to use UA detection here because accessing
// the layerX or layerY properties in newer veresions of Chrome
// throws a JS warning. layerX and layerY are required for FF
// when the container is transformed via CSS.
else if (Kinetic.UA.browser === 'mozilla') {
x = evt.layerX;
y = evt.layerY;
}
// if clientX is defined, assume that clientY is defined as well
else if (clientX !== undefined && contentPosition) {
x = clientX - contentPosition.left;
y = evt.clientY - contentPosition.top;
}
}
if (x !== null && y !== null) {
this.pointerPos = {
x: x,
y: y
};
}
},
_getContentPosition: function() {
var rect = this.content.getBoundingClientRect ? this.content.getBoundingClientRect() : { top: 0, left: 0 };
return {
top: rect.top,
left: rect.left
};
},
_buildDOM: function() {
var container = this.getContainer();
if (!container) {
if (Kinetic.Util.isBrowser()) {
throw 'Stage has not container. But container is required';
} else {
// automatically create element for jsdom in nodejs env
container = Kinetic.document.createElement(DIV);
}
}
// clear content inside container
container.innerHTML = EMPTY_STRING;
// content
this.content = Kinetic.document.createElement(DIV);
this.content.style.position = RELATIVE;
this.content.style.display = INLINE_BLOCK;
this.content.className = KINETICJS_CONTENT;
this.content.setAttribute('role', 'presentation');
container.appendChild(this.content);
// the buffer canvas pixel ratio must be 1 because it is used as an
// intermediate canvas before copying the result onto a scene canvas.
// not setting it to 1 will result in an over compensation
this.bufferCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1
});
this.bufferHitCanvas = new Kinetic.HitCanvas();
this._resizeDOM();
},
_onContent: function(typesStr, handler) {
var types = typesStr.split(SPACE),
len = types.length,
n, baseEvent;
for(n = 0; n < len; n++) {
baseEvent = types[n];
this.content.addEventListener(baseEvent, handler, false);
}
},
// currently cache function is now working for stage, because stage has no its own canvas element
// TODO: may be it is better to cache all children layers?
cache: function() {
Kinetic.Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.');
return;
},
clearCache : function() {
}
});
Kinetic.Util.extend(Kinetic.Stage, Kinetic.Container);
// add getters and setters
Kinetic.Factory.addGetter(Kinetic.Stage, 'container');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Stage, 'container');
/**
* get container DOM element
* @name container
* @method
* @memberof Kinetic.Stage.prototype
* @returns {DomElement} container
* @example
* // get container<br>
* var container = stage.container();<br><br>
*
* // set container<br>
* var container = document.createElement('div');<br>
* body.appendChild(container);<br>
* stage.container(container);
*/
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.BaseLayer, {
___init: function(config) {
this.nodeType = 'Layer';
Kinetic.Container.call(this, config);
},
createPNGStream : function() {
return this.canvas._canvas.createPNGStream();
},
/**
* get layer canvas
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getCanvas: function() {
return this.canvas;
},
/**
* get layer hit canvas
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getHitCanvas: function() {
return this.hitCanvas;
},
/**
* get layer canvas context
* @method
* @memberof Kinetic.BaseLayer.prototype
*/
getContext: function() {
return this.getCanvas().getContext();
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.BaseLayer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
},
// extend Node.prototype.setZIndex
setZIndex: function(index) {
Kinetic.Node.prototype.setZIndex.call(this, index);
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
if(index < stage.getChildren().length - 1) {
stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getCanvas()._canvas);
}
}
return this;
},
// extend Node.prototype.moveToTop
moveToTop: function() {
Kinetic.Node.prototype.moveToTop.call(this);
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.appendChild(this.getCanvas()._canvas);
}
},
// extend Node.prototype.moveUp
moveUp: function() {
if(Kinetic.Node.prototype.moveUp.call(this)) {
var stage = this.getStage();
if(stage) {
stage.content.removeChild(this.getCanvas()._canvas);
if(this.index < stage.getChildren().length - 1) {
stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[this.index + 1].getCanvas()._canvas);
}
else {
stage.content.appendChild(this.getCanvas()._canvas);
}
}
}
},
// extend Node.prototype.moveDown
moveDown: function() {
if(Kinetic.Node.prototype.moveDown.call(this)) {
var stage = this.getStage();
if(stage) {
var children = stage.getChildren();
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.insertBefore(this.getCanvas()._canvas, children[this.index + 1].getCanvas()._canvas);
}
}
},
// extend Node.prototype.moveToBottom
moveToBottom: function() {
if(Kinetic.Node.prototype.moveToBottom.call(this)) {
var stage = this.getStage();
if(stage) {
var children = stage.getChildren();
stage.content.removeChild(this.getCanvas()._canvas);
stage.content.insertBefore(this.getCanvas()._canvas, children[1].getCanvas()._canvas);
}
}
},
getLayer: function() {
return this;
},
remove: function() {
var _canvas = this.getCanvas()._canvas;
Kinetic.Node.prototype.remove.call(this);
if(_canvas && _canvas.parentNode && Kinetic.Util._isInDocument(_canvas)) {
_canvas.parentNode.removeChild(_canvas);
}
return this;
},
getStage: function() {
return this.parent;
}
});
Kinetic.Util.extend(Kinetic.BaseLayer, Kinetic.Container);
// add getters and setters
Kinetic.Factory.addGetterSetter(Kinetic.BaseLayer, 'clearBeforeDraw', true);
/**
* get/set clearBeforeDraw flag which determines if the layer is cleared or not
* before drawing
* @name clearBeforeDraw
* @method
* @memberof Kinetic.BaseLayer.prototype
* @param {Boolean} clearBeforeDraw
* @returns {Boolean}
* @example
* // get clearBeforeDraw flag<br>
* var clearBeforeDraw = layer.clearBeforeDraw();<br><br>
*
* // disable clear before draw<br>
* layer.clearBeforeDraw(false);<br><br>
*
* // enable clear before draw<br>
* layer.clearBeforeDraw(true);
*/
Kinetic.Collection.mapMethods(Kinetic.BaseLayer);
})();
;(function() {
// constants
var HASH = '#',
BEFORE_DRAW ='beforeDraw',
DRAW = 'draw',
/*
* 2 - 3 - 4
* | |
* 1 - 0 5
* |
* 8 - 7 - 6
*/
INTERSECTION_OFFSETS = [
{x: 0, y: 0}, // 0
{x: -1, y: 0}, // 1
{x: -1, y: -1}, // 2
{x: 0, y: -1}, // 3
{x: 1, y: -1}, // 4
{x: 1, y: 0}, // 5
{x: 1, y: 1}, // 6
{x: 0, y: 1}, // 7
{x: -1, y: 1} // 8
],
INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length;
Kinetic.Util.addMethods(Kinetic.Layer, {
____init: function(config) {
this.nodeType = 'Layer';
this.canvas = new Kinetic.SceneCanvas();
this.hitCanvas = new Kinetic.HitCanvas();
// call super constructor
Kinetic.BaseLayer.call(this, config);
},
_setCanvasSize: function(width, height) {
this.canvas.setSize(width, height);
this.hitCanvas.setSize(width, height);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Kinetic.Util.error('You may only add groups and shapes to a layer.');
}
},
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @memberof Kinetic.Layer.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Shape}
*/
getIntersection: function(pos) {
var obj, i, intersectionOffset, shape;
if(this.hitGraphEnabled() && this.isVisible()) {
for (i=0; i<INTERSECTION_OFFSETS_LEN; i++) {
intersectionOffset = INTERSECTION_OFFSETS[i];
obj = this._getIntersection({
x: pos.x + intersectionOffset.x,
y: pos.y + intersectionOffset.y
});
shape = obj.shape;
if (shape) {
return shape;
}
else if (!obj.antialiased) {
return null;
}
}
}
else {
return null;
}
},
_getIntersection: function(pos) {
var p = this.hitCanvas.context._context.getImageData(pos.x, pos.y, 1, 1).data,
p3 = p[3],
colorKey, shape;
// fully opaque pixel
if(p3 === 255) {
colorKey = Kinetic.Util._rgbToHex(p[0], p[1], p[2]);
shape = Kinetic.shapes[HASH + colorKey];
return {
shape: shape
};
}
// antialiased pixel
else if(p3 > 0) {
return {
antialiased: true
};
}
// empty pixel
else {
return {};
}
},
drawScene: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas());
this._fire(BEFORE_DRAW, {
node: this
});
if(this.getClearBeforeDraw()) {
canvas.getContext().clear();
}
Kinetic.Container.prototype.drawScene.call(this, canvas, top);
this._fire(DRAW, {
node: this
});
return this;
},
// the apply transform method is handled by the Layer and FastLayer class
// because it is up to the layer to decide if an absolute or relative transform
// should be used
_applyTransform: function(shape, context, top) {
var m = shape.getAbsoluteTransform(top).getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
},
drawHit: function(can, top) {
var layer = this.getLayer(),
canvas = can || (layer && layer.hitCanvas);
if(layer && layer.getClearBeforeDraw()) {
layer.getHitCanvas().getContext().clear();
}
Kinetic.Container.prototype.drawHit.call(this, canvas, top);
return this;
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.Layer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
},
// extend Node.prototype.setVisible
setVisible: function(visible) {
Kinetic.Node.prototype.setVisible.call(this, visible);
if(visible) {
this.getCanvas()._canvas.style.display = 'block';
this.hitCanvas._canvas.style.display = 'block';
}
else {
this.getCanvas()._canvas.style.display = 'none';
this.hitCanvas._canvas.style.display = 'none';
}
return this;
},
/**
* enable hit graph
* @name enableHitGraph
* @method
* @memberof Kinetic.Layer.prototype
* @returns {Node}
*/
enableHitGraph: function() {
this.setHitGraphEnabled(true);
return this;
},
/**
* disable hit graph
* @name enableHitGraph
* @method
* @memberof Kinetic.Layer.prototype
* @returns {Node}
*/
disableHitGraph: function() {
this.setHitGraphEnabled(false);
return this;
}
});
Kinetic.Util.extend(Kinetic.Layer, Kinetic.BaseLayer);
Kinetic.Factory.addGetterSetter(Kinetic.Layer, 'hitGraphEnabled', true);
/**
* get/set hitGraphEnabled flag. Disabling the hit graph will greatly increase
* draw performance because the hit graph will not be redrawn each time the layer is
* drawn. This, however, also disables mouse/touch event detection
* @name hitGraphEnabled
* @method
* @memberof Kinetic.Layer.prototype
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get hitGraphEnabled flag<br>
* var hitGraphEnabled = layer.hitGraphEnabled();<br><br>
*
* // disable hit graph<br>
* layer.hitGraphEnabled(false);<br><br>
*
* // enable hit graph<br>
* layer.hitGraphEnabled(true);
*/
Kinetic.Collection.mapMethods(Kinetic.Layer);
})();
;(function() {
// constants
var HASH = '#',
BEFORE_DRAW ='beforeDraw',
DRAW = 'draw';
Kinetic.Util.addMethods(Kinetic.FastLayer, {
____init: function(config) {
this.nodeType = 'Layer';
this.canvas = new Kinetic.SceneCanvas();
// call super constructor
Kinetic.BaseLayer.call(this, config);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Shape') {
Kinetic.Util.error('You may only add shapes to a fast layer.');
}
},
_setCanvasSize: function(width, height) {
this.canvas.setSize(width, height);
},
hitGraphEnabled: function() {
return false;
},
getIntersection: function() {
return null;
},
drawScene: function(can) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas());
if(this.getClearBeforeDraw()) {
canvas.getContext().clear();
}
Kinetic.Container.prototype.drawScene.call(this, canvas);
return this;
},
// the apply transform method is handled by the Layer and FastLayer class
// because it is up to the layer to decide if an absolute or relative transform
// should be used
_applyTransform: function(shape, context, top) {
if (!top || top._id !== this._id) {
var m = shape.getTransform().getMatrix();
context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
},
draw: function() {
this.drawScene();
return this;
},
/**
* clear scene and hit canvas contexts tied to the layer
* @method
* @memberof Kinetic.FastLayer.prototype
* @param {Object} [bounds]
* @param {Number} [bounds.x]
* @param {Number} [bounds.y]
* @param {Number} [bounds.width]
* @param {Number} [bounds.height]
* @example
* layer.clear();<br>
* layer.clear(0, 0, 100, 100);
*/
clear: function(bounds) {
this.getContext().clear(bounds);
return this;
},
// extend Node.prototype.setVisible
setVisible: function(visible) {
Kinetic.Node.prototype.setVisible.call(this, visible);
if(visible) {
this.getCanvas()._canvas.style.display = 'block';
}
else {
this.getCanvas()._canvas.style.display = 'none';
}
return this;
}
});
Kinetic.Util.extend(Kinetic.FastLayer, Kinetic.BaseLayer);
Kinetic.Collection.mapMethods(Kinetic.FastLayer);
})();
;(function() {
Kinetic.Util.addMethods(Kinetic.Group, {
___init: function(config) {
this.nodeType = 'Group';
// call super constructor
Kinetic.Container.call(this, config);
},
_validateAdd: function(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Kinetic.Util.error('You may only add groups and shapes to groups.');
}
}
});
Kinetic.Util.extend(Kinetic.Group, Kinetic.Container);
Kinetic.Collection.mapMethods(Kinetic.Group);
})();
;(function() {
/**
* Rect constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} [config.cornerRadius]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var rect = new Kinetic.Rect({<br>
* width: 100,<br>
* height: 50,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Rect = function(config) {
this.___init(config);
};
Kinetic.Rect.prototype = {
___init: function(config) {
Kinetic.Shape.call(this, config);
this.className = 'Rect';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var cornerRadius = this.getCornerRadius(),
width = this.getWidth(),
height = this.getHeight();
context.beginPath();
if(!cornerRadius) {
// simple rect - don't bother doing all that complicated maths stuff.
context.rect(0, 0, width, height);
}
else {
// arcTo would be nicer, but browser support is patchy (Opera)
context.moveTo(cornerRadius, 0);
context.lineTo(width - cornerRadius, 0);
context.arc(width - cornerRadius, cornerRadius, cornerRadius, Math.PI * 3 / 2, 0, false);
context.lineTo(width, height - cornerRadius);
context.arc(width - cornerRadius, height - cornerRadius, cornerRadius, 0, Math.PI / 2, false);
context.lineTo(cornerRadius, height);
context.arc(cornerRadius, height - cornerRadius, cornerRadius, Math.PI / 2, Math.PI, false);
context.lineTo(0, cornerRadius);
context.arc(cornerRadius, cornerRadius, cornerRadius, Math.PI, Math.PI * 3 / 2, false);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Rect, Kinetic.Shape);
Kinetic.Factory.addGetterSetter(Kinetic.Rect, 'cornerRadius', 0);
/**
* get/set corner radius
* @name cornerRadius
* @method
* @memberof Kinetic.Rect.prototype
* @param {Number} cornerRadius
* @returns {Number}
* @example
* // get corner radius<br>
* var cornerRadius = rect.cornerRadius();<br><br>
*
* // set corner radius<br>
* rect.cornerRadius(10);
*/
Kinetic.Collection.mapMethods(Kinetic.Rect);
})();
;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001,
CIRCLE = 'Circle';
/**
* Circle constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create circle
* var circle = new Kinetic.Circle({<br>
* radius: 40,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Circle = function(config) {
this.___init(config);
};
Kinetic.Circle.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = CIRCLE;
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getRadius(), 0, PIx2, false);
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getRadius() * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getRadius() * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setRadius(width / 2);
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setRadius(height / 2);
}
};
Kinetic.Util.extend(Kinetic.Circle, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Circle, 'radius', 0);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Circle.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radius<br>
* var radius = circle.radius();<br><br>
*
* // set radius<br>
* circle.radius(10);<br>
*/
Kinetic.Collection.mapMethods(Kinetic.Circle);
})();
;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001,
ELLIPSE = 'Ellipse';
/**
* Ellipse constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Object} config.radius defines x and y radius
* @@ShapeParams
* @@NodeParams
* @example
* var ellipse = new Kinetic.Ellipse({<br>
* radius : {<br>
* x : 50,<br>
* y : 50<br>
* },<br>
* fill: 'red'<br>
* });
*/
Kinetic.Ellipse = function(config) {
this.___init(config);
};
Kinetic.Ellipse.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = ELLIPSE;
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var r = this.getRadius(),
rx = r.x,
ry = r.y;
context.beginPath();
context.save();
if(rx !== ry) {
context.scale(1, ry / rx);
}
context.arc(0, 0, rx, 0, PIx2, false);
context.restore();
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getRadius().x * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getRadius().y * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setRadius({
x: width / 2
});
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setRadius({
y: height / 2
});
}
};
Kinetic.Util.extend(Kinetic.Ellipse, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Ellipse, 'radius', ['x', 'y']);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Object} radius
* @param {Number} radius.x
* @param {Number} radius.y
* @returns {Object}
* @example
* // get radius<br>
* var radius = ellipse.radius();<br><br>
*
* // set radius<br>
* ellipse.radius({<br>
* x: 200,<br>
* y: 100<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusX', 0);
/**
* get/set radius x
* @name radiusX
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get radius x<br>
* var radiusX = ellipse.radiusX();<br><br>
*
* // set radius x<br>
* ellipse.radiusX(200);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusY', 0);
/**
* get/set radius y
* @name radiusY
* @method
* @memberof Kinetic.Ellipse.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get radius y<br>
* var radiusY = ellipse.radiusY();<br><br>
*
* // set radius y<br>
* ellipse.radiusY(200);
*/
Kinetic.Collection.mapMethods(Kinetic.Ellipse);
})();;(function() {
// the 0.0001 offset fixes a bug in Chrome 27
var PIx2 = (Math.PI * 2) - 0.0001;
/**
* Ring constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var ring = new Kinetic.Ring({<br>
* innerRadius: 40,<br>
* outerRadius: 80,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 5<br>
* });
*/
Kinetic.Ring = function(config) {
this.___init(config);
};
Kinetic.Ring.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Ring';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getInnerRadius(), 0, PIx2, false);
context.moveTo(this.getOuterRadius(), 0);
context.arc(0, 0, this.getOuterRadius(), PIx2, 0, true);
context.closePath();
context.fillStrokeShape(this);
},
// implements Shape.prototype.getWidth()
getWidth: function() {
return this.getOuterRadius() * 2;
},
// implements Shape.prototype.getHeight()
getHeight: function() {
return this.getOuterRadius() * 2;
},
// implements Shape.prototype.setWidth()
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this.setOuterRadius(width / 2);
},
// implements Shape.prototype.setHeight()
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this.setOuterRadius(height / 2);
}
};
Kinetic.Util.extend(Kinetic.Ring, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'innerRadius', 0);
/**
* get/set innerRadius
* @name innerRadius
* @method
* @memberof Kinetic.Ring.prototype
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius<br>
* var innerRadius = ring.innerRadius();<br><br>
*
* // set inner radius<br>
* ring.innerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'outerRadius', 0);
/**
* get/set outerRadius
* @name outerRadius
* @method
* @memberof Kinetic.Ring.prototype
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius<br>
* var outerRadius = ring.outerRadius();<br><br>
*
* // set outer radius<br>
* ring.outerRadius(20);
*/
Kinetic.Collection.mapMethods(Kinetic.Ring);
})();
;(function() {
/**
* Wedge constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.radius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a wedge that's pointing downwards<br>
* var wedge = new Kinetic.Wedge({<br>
* radius: 40,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5,<br>
* angleDeg: 60,<br>
* rotationDeg: -120<br>
* });
*/
Kinetic.Wedge = function(config) {
this.___init(config);
};
Kinetic.Wedge.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Wedge';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getRadius(), 0, Kinetic.getAngle(this.getAngle()), this.getClockwise());
context.lineTo(0, 0);
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Wedge, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'radius', 0);
/**
* get/set radius
* @name radius
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} radius
* @returns {Number}
* @example
* // get radius<br>
* var radius = wedge.radius();<br><br>
*
* // set radius<br>
* wedge.radius(10);<br>
*/
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'angle', 0);
/**
* get/set angle in degrees
* @name angle
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} angle
* @returns {Number}
* @example
* // get angle<br>
* var angle = wedge.angle();<br><br>
*
* // set angle<br>
* wedge.angle(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'clockwise', false);
/**
* get/set clockwise flag
* @name clockwise
* @method
* @memberof Kinetic.Wedge.prototype
* @param {Number} clockwise
* @returns {Number}
* @example
* // get clockwise flag<br>
* var clockwise = wedge.clockwise();<br><br>
*
* // draw wedge counter-clockwise<br>
* wedge.clockwise(false);<br><br>
*
* // draw wedge clockwise<br>
* wedge.clockwise(true);
*/
Kinetic.Factory.backCompat(Kinetic.Wedge, {
angleDeg: 'angle',
getAngleDeg: 'getAngle',
setAngleDeg: 'setAngle'
});
Kinetic.Collection.mapMethods(Kinetic.Wedge);
})();
;(function() {
var PI_OVER_180 = Math.PI / 180;
/**
* Arc constructor
* @constructor
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.angle in degrees
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {Boolean} [config.clockwise]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // draw a Arc that's pointing downwards<br>
* var arc = new Kinetic.Arc({<br>
* innerRadius: 40,<br>
* outerRadius: 80,<br>
* fill: 'red',<br>
* stroke: 'black'<br>
* strokeWidth: 5,<br>
* angle: 60,<br>
* rotationDeg: -120<br>
* });
*/
Kinetic.Arc = function(config) {
this.___init(config);
};
Kinetic.Arc.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Arc';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var angle = Kinetic.getAngle(this.angle()),
clockwise = this.clockwise();
context.beginPath();
context.arc(0, 0, this.getOuterRadius(), 0, angle, clockwise);
context.arc(0, 0, this.getInnerRadius(), angle, 0, !clockwise);
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Arc, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'innerRadius', 0);
/**
* get/set innerRadius
* @name innerRadius
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} innerRadius
* @returns {Number}
* @example
* // get inner radius
* var innerRadius = arc.innerRadius();
*
* // set inner radius
* arc.innerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'outerRadius', 0);
/**
* get/set outerRadius
* @name outerRadius
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} outerRadius
* @returns {Number}
* @example
* // get outer radius<br>
* var outerRadius = arc.outerRadius();<br><br>
*
* // set outer radius<br>
* arc.outerRadius(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'angle', 0);
/**
* get/set angle in degrees
* @name angle
* @method
* @memberof Kinetic.Arc.prototype
* @param {Number} angle
* @returns {Number}
* @example
* // get angle<br>
* var angle = arc.angle();<br><br>
*
* // set angle<br>
* arc.angle(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'clockwise', false);
/**
* get/set clockwise flag
* @name clockwise
* @method
* @memberof Kinetic.Arc.prototype
* @param {Boolean} clockwise
* @returns {Boolean}
* @example
* // get clockwise flag<br>
* var clockwise = arc.clockwise();<br><br>
*
* // draw arc counter-clockwise<br>
* arc.clockwise(false);<br><br>
*
* // draw arc clockwise<br>
* arc.clockwise(true);
*/
Kinetic.Collection.mapMethods(Kinetic.Arc);
})();
;(function() {
// CONSTANTS
var IMAGE = 'Image';
/**
* Image constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {ImageObject} config.image
* @param {Object} [config.crop]
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* var image = new Kinetic.Image({<br>
* x: 200,<br>
* y: 50,<br>
* image: imageObj,<br>
* width: 100,<br>
* height: 100<br>
* });<br>
* };<br>
* imageObj.src = '/path/to/image.jpg'
*/
Kinetic.Image = function(config) {
this.___init(config);
};
Kinetic.Image.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = IMAGE;
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke();
},
_sceneFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight(),
image = this.getImage(),
crop, cropWidth, cropHeight, params;
if (image) {
crop = this.getCrop();
cropWidth = crop.width;
cropHeight = crop.height;
if (cropWidth && cropHeight) {
params = [image, crop.x, crop.y, cropWidth, cropHeight, 0, 0, width, height];
} else {
params = [image, 0, 0, width, height];
}
}
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
if (image) {
context.drawImage.apply(context, params);
}
},
_hitFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
},
getWidth: function() {
var image = this.getImage();
return this.attrs.width || (image ? image.width : 0);
},
getHeight: function() {
var image = this.getImage();
return this.attrs.height || (image ? image.height : 0);
}
};
Kinetic.Util.extend(Kinetic.Image, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'image');
/**
* set image
* @name setImage
* @method
* @memberof Kinetic.Image.prototype
* @param {ImageObject} image
*/
/**
* get image
* @name getImage
* @method
* @memberof Kinetic.Image.prototype
* @returns {ImageObject}
*/
Kinetic.Factory.addComponentsGetterSetter(Kinetic.Image, 'crop', ['x', 'y', 'width', 'height']);
/**
* get/set crop
* @method
* @name crop
* @memberof Kinetic.Image.prototype
* @param {Object} crop
* @param {Number} crop.x
* @param {Number} crop.y
* @param {Number} crop.width
* @param {Number} crop.height
* @returns {Object}
* @example
* // get crop<br>
* var crop = image.crop();<br><br>
*
* // set crop<br>
* image.crop({<br>
* x: 20,<br>
* y: 20,<br>
* width: 20,<br>
* height: 20<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropX', 0);
/**
* get/set crop x
* @method
* @name cropX
* @memberof Kinetic.Image.prototype
* @param {Number} x
* @returns {Number}
* @example
* // get crop x<br>
* var cropX = image.cropX();<br><br>
*
* // set crop x<br>
* image.cropX(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropY', 0);
/**
* get/set crop y
* @name cropY
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} y
* @returns {Number}
* @example
* // get crop y<br>
* var cropY = image.cropY();<br><br>
*
* // set crop y<br>
* image.cropY(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropWidth', 0);
/**
* get/set crop width
* @name cropWidth
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} width
* @returns {Number}
* @example
* // get crop width<br>
* var cropWidth = image.cropWidth();<br><br>
*
* // set crop width<br>
* image.cropWidth(20);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropHeight', 0);
/**
* get/set crop height
* @name cropHeight
* @method
* @memberof Kinetic.Image.prototype
* @param {Number} height
* @returns {Number}
* @example
* // get crop height<br>
* var cropHeight = image.cropHeight();<br><br>
*
* // set crop height<br>
* image.cropHeight(20);
*/
Kinetic.Collection.mapMethods(Kinetic.Image);
})();
;(function() {
// constants
var AUTO = 'auto',
//CANVAS = 'canvas',
CENTER = 'center',
CHANGE_KINETIC = 'Change.kinetic',
CONTEXT_2D = '2d',
DASH = '-',
EMPTY_STRING = '',
LEFT = 'left',
TEXT = 'text',
TEXT_UPPER = 'Text',
MIDDLE = 'middle',
NORMAL = 'normal',
PX_SPACE = 'px ',
SPACE = ' ',
RIGHT = 'right',
WORD = 'word',
CHAR = 'char',
NONE = 'none',
ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'fontVariant', 'padding', 'align', 'lineHeight', 'text', 'width', 'height', 'wrap'],
// cached variables
attrChangeListLen = ATTR_CHANGE_LIST.length,
dummyContext = Kinetic.Util.createCanvasElement().getContext(CONTEXT_2D);
/**
* Text constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Arial
* @param {Number} [config.fontSize] in pixels. Default is 12
* @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} config.text
* @param {String} [config.align] can be left, center, or right
* @param {Number} [config.padding]
* @param {Number} [config.width] default is auto
* @param {Number} [config.height] default is auto
* @param {Number} [config.lineHeight] default is 1
* @param {String} [config.wrap] can be word, char, or none. Default is word
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var text = new Kinetic.Text({<br>
* x: 10,<br>
* y: 15,<br>
* text: 'Simple Text',<br>
* fontSize: 30,<br>
* fontFamily: 'Calibri',<br>
* fill: 'green'<br>
* });
*/
Kinetic.Text = function(config) {
this.___init(config);
};
function _fillFunc(context) {
context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
context.strokeText(this.partialText, 0, 0);
}
Kinetic.Text.prototype = {
___init: function(config) {
var that = this;
if (config.width === undefined) {
config.width = AUTO;
}
if (config.height === undefined) {
config.height = AUTO;
}
// call super constructor
Kinetic.Shape.call(this, config);
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this.className = TEXT_UPPER;
// update text data for certain attr changes
for(var n = 0; n < attrChangeListLen; n++) {
this.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, that._setTextData);
}
this._setTextData();
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_sceneFunc: function(context) {
var p = this.getPadding(),
textHeight = this.getTextHeight(),
lineHeightPx = this.getLineHeight() * textHeight,
textArr = this.textArr,
textArrLen = textArr.length,
totalWidth = this.getWidth(),
n;
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', MIDDLE);
context.setAttr('textAlign', LEFT);
context.save();
context.translate(p, 0);
context.translate(0, p + textHeight / 2);
// draw text lines
for(n = 0; n < textArrLen; n++) {
var obj = textArr[n],
text = obj.text,
width = obj.width;
// horizontal alignment
context.save();
if(this.getAlign() === RIGHT) {
context.translate(totalWidth - width - p * 2, 0);
}
else if(this.getAlign() === CENTER) {
context.translate((totalWidth - width - p * 2) / 2, 0);
}
this.partialText = text;
context.fillStrokeShape(this);
context.restore();
context.translate(0, lineHeightPx);
}
context.restore();
},
_hitFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillStrokeShape(this);
},
setText: function(text) {
var str = Kinetic.Util._isString(text) ? text : text.toString();
this._setAttr(TEXT, str);
return this;
},
/**
* get width of text area, which includes padding
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getWidth: function() {
return this.attrs.width === AUTO ? this.getTextWidth() + this.getPadding() * 2 : this.attrs.width;
},
/**
* get the height of the text area, which takes into account multi-line text, line heights, and padding
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getHeight: function() {
return this.attrs.height === AUTO ? (this.getTextHeight() * this.textArr.length * this.getLineHeight()) + this.getPadding() * 2 : this.attrs.height;
},
/**
* get text width
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getTextWidth: function() {
return this.textWidth;
},
/**
* get text height
* @method
* @memberof Kinetic.Text.prototype
* @returns {Number}
*/
getTextHeight: function() {
return this.textHeight;
},
_getTextSize: function(text) {
var _context = dummyContext,
fontSize = this.getFontSize(),
metrics;
_context.save();
_context.font = this._getContextFont();
metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(fontSize, 10)
};
},
_getContextFont: function() {
return this.getFontStyle() + SPACE + this.getFontVariant() + SPACE + this.getFontSize() + PX_SPACE + this.getFontFamily();
},
_addTextLine: function (line, width) {
return this.textArr.push({text: line, width: width});
},
_getTextWidth: function (text) {
return dummyContext.measureText(text).width;
},
_setTextData: function () {
var lines = this.getText().split('\n'),
fontSize = +this.getFontSize(),
textWidth = 0,
lineHeightPx = this.getLineHeight() * fontSize,
width = this.attrs.width,
height = this.attrs.height,
fixedWidth = width !== AUTO,
fixedHeight = height !== AUTO,
padding = this.getPadding(),
maxWidth = width - padding * 2,
maxHeightPx = height - padding * 2,
currentHeightPx = 0,
wrap = this.getWrap(),
shouldWrap = wrap !== NONE,
wrapAtWord = wrap !== CHAR && shouldWrap;
this.textArr = [];
dummyContext.save();
dummyContext.font = this._getContextFont();
for (var i = 0, max = lines.length; i < max; ++i) {
var line = lines[i],
lineWidth = this._getTextWidth(line);
if (fixedWidth && lineWidth > maxWidth) {
/*
* if width is fixed and line does not fit entirely
* break the line into multiple fitting lines
*/
while (line.length > 0) {
/*
* use binary search to find the longest substring that
* that would fit in the specified width
*/
var low = 0, high = line.length,
match = '', matchWidth = 0;
while (low < high) {
var mid = (low + high) >>> 1,
substr = line.slice(0, mid + 1),
substrWidth = this._getTextWidth(substr);
if (substrWidth <= maxWidth) {
low = mid + 1;
match = substr;
matchWidth = substrWidth;
} else {
high = mid;
}
}
/*
* 'low' is now the index of the substring end
* 'match' is the substring
* 'matchWidth' is the substring width in px
*/
if (match) {
// a fitting substring was found
if (wrapAtWord) {
// try to find a space or dash where wrapping could be done
var wrapIndex = Math.max(match.lastIndexOf(SPACE),
match.lastIndexOf(DASH)) + 1;
if (wrapIndex > 0) {
// re-cut the substring found at the space/dash position
low = wrapIndex;
match = match.slice(0, low);
matchWidth = this._getTextWidth(match);
}
}
this._addTextLine(match, matchWidth);
textWidth = Math.max(textWidth, matchWidth);
currentHeightPx += lineHeightPx;
if (!shouldWrap ||
(fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx)) {
/*
* stop wrapping if wrapping is disabled or if adding
* one more line would overflow the fixed height
*/
break;
}
line = line.slice(low);
if (line.length > 0) {
// Check if the remaining text would fit on one line
lineWidth = this._getTextWidth(line);
if (lineWidth <= maxWidth) {
// if it does, add the line and break out of the loop
this._addTextLine(line, lineWidth);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
break;
}
}
} else {
// not even one character could fit in the element, abort
break;
}
}
} else {
// element width is automatically adjusted to max line width
this._addTextLine(line, lineWidth);
currentHeightPx += lineHeightPx;
textWidth = Math.max(textWidth, lineWidth);
}
// if element height is fixed, abort if adding one more line would overflow
if (fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx) {
break;
}
}
dummyContext.restore();
this.textHeight = fontSize;
this.textWidth = textWidth;
}
};
Kinetic.Util.extend(Kinetic.Text, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontFamily', 'Arial');
/**
* get/set font family
* @name fontFamily
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontFamily
* @returns {String}
* @example
* // get font family<br>
* var fontFamily = text.fontFamily();<br><br><br>
*
* // set font family<br>
* text.fontFamily('Arial');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontSize', 12);
/**
* get/set font size in pixels
* @name fontSize
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} fontSize
* @returns {Number}
* @example
* // get font size<br>
* var fontSize = text.fontSize();<br><br>
*
* // set font size to 22px<br>
* text.fontSize(22);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontStyle', NORMAL);
/**
* set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default.
* @name fontStyle
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontStyle
* @returns {String}
* @example
* // get font style<br>
* var fontStyle = text.fontStyle();<br><br>
*
* // set font style<br>
* text.fontStyle('bold');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontVariant', NORMAL);
/**
* set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name fontVariant
* @method
* @memberof Kinetic.Text.prototype
* @param {String} fontVariant
* @returns {String}
* @example
* // get font variant<br>
* var fontVariant = text.fontVariant();<br><br>
*
* // set font variant<br>
* text.fontVariant('small-caps');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'padding', 0);
/**
* set padding
* @name padding
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} padding
* @returns {Number}
* @example
* // get padding<br>
* var padding = text.padding();<br><br>
*
* // set padding to 10 pixels<br>
* text.padding(10);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'align', LEFT);
/**
* get/set horizontal align of text. Can be 'left', 'center', or 'right'
* @name align
* @method
* @memberof Kinetic.Text.prototype
* @param {String} align
* @returns {String}
* @example
* // get text align<br>
* var align = text.align();<br><br>
*
* // center text<br>
* text.align('center');<br><br>
*
* // align text to right<br>
* text.align('right');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'lineHeight', 1);
/**
* get/set line height. The default is 1.
* @name lineHeight
* @method
* @memberof Kinetic.Text.prototype
* @param {Number} lineHeight
* @returns {Number}
* @example
* // get line height<br>
* var lineHeight = text.lineHeight();<br><br><br>
*
* // set the line height<br>
* text.lineHeight(2);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Text, 'wrap', WORD);
/**
* get/set wrap. Can be word, char, or none. Default is word.
* @name wrap
* @method
* @memberof Kinetic.Text.prototype
* @param {String} wrap
* @returns {String}
* @example
* // get wrap<br>
* var wrap = text.wrap();<br><br>
*
* // set wrap<br>
* text.wrap('word');
*/
Kinetic.Factory.addGetter(Kinetic.Text, 'text', EMPTY_STRING);
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Text, 'text');
/**
* get/set text
* @name getText
* @method
* @memberof Kinetic.Text.prototype
* @param {String} text
* @returns {String}
* @example
* // get text<br>
* var text = text.text();<br><br>
*
* // set text<br>
* text.text('Hello world!');
*/
Kinetic.Collection.mapMethods(Kinetic.Text);
})();
;(function() {
/**
* Line constructor. Lines are defined by an array of points and
* a tension
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Array} config.points
* @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var line = new Kinetic.Line({<br>
* x: 100,<br>
* y: 50,<br>
* points: [73, 70, 340, 23, 450, 60, 500, 20],<br>
* stroke: 'red',<br>
* tension: 1<br>
* });
*/
Kinetic.Line = function(config) {
this.___init(config);
};
Kinetic.Line.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Line';
this.on('pointsChange.kinetic tensionChange.kinetic closedChange.kinetic', function() {
this._clearCache('tensionPoints');
});
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var points = this.getPoints(),
length = points.length,
tension = this.getTension(),
closed = this.getClosed(),
tp, len, n;
context.beginPath();
context.moveTo(points[0], points[1]);
// tension
if(tension !== 0 && length > 4) {
tp = this.getTensionPoints();
len = tp.length;
n = closed ? 0 : 4;
if (!closed) {
context.quadraticCurveTo(tp[0], tp[1], tp[2], tp[3]);
}
while(n < len - 2) {
context.bezierCurveTo(tp[n++], tp[n++], tp[n++], tp[n++], tp[n++], tp[n++]);
}
if (!closed) {
context.quadraticCurveTo(tp[len-2], tp[len-1], points[length-2], points[length-1]);
}
}
// no tension
else {
for(n = 2; n < length; n+=2) {
context.lineTo(points[n], points[n+1]);
}
}
// closed e.g. polygons and blobs
if (closed) {
context.closePath();
context.fillStrokeShape(this);
}
// open e.g. lines and splines
else {
context.strokeShape(this);
}
},
getTensionPoints: function() {
return this._getCache('tensionPoints', this._getTensionPoints);
},
_getTensionPoints: function() {
if (this.getClosed()) {
return this._getTensionPointsClosed();
}
else {
return Kinetic.Util._expandPoints(this.getPoints(), this.getTension());
}
},
_getTensionPointsClosed: function() {
var p = this.getPoints(),
len = p.length,
tension = this.getTension(),
util = Kinetic.Util,
firstControlPoints = util._getControlPoints(
p[len-2],
p[len-1],
p[0],
p[1],
p[2],
p[3],
tension
),
lastControlPoints = util._getControlPoints(
p[len-4],
p[len-3],
p[len-2],
p[len-1],
p[0],
p[1],
tension
),
middle = Kinetic.Util._expandPoints(p, tension),
tp = [
firstControlPoints[2],
firstControlPoints[3]
]
.concat(middle)
.concat([
lastControlPoints[0],
lastControlPoints[1],
p[len-2],
p[len-1],
lastControlPoints[2],
lastControlPoints[3],
firstControlPoints[0],
firstControlPoints[1],
p[0],
p[1]
]);
return tp;
}
};
Kinetic.Util.extend(Kinetic.Line, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'closed', false);
/**
* get/set closed flag. The default is false
* @name closed
* @method
* @memberof Kinetic.Line.prototype
* @param {Boolean} closed
* @returns {Boolean}
* @example
* // get closed flag<br>
* var closed = line.closed();<br><br>
*
* // close the shape<br>
* line.closed(true);<br><br>
*
* // open the shape<br>
* line.closed(false);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'tension', 0);
/**
* get/set tension
* @name tension
* @method
* @memberof Kinetic.Line.prototype
* @param {Number} Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
* The default is 0
* @returns {Number}
* @example
* // get tension<br>
* var tension = line.tension();<br><br>
*
* // set tension<br>
* line.tension(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Line, 'points');
/**
* get/set points array
* @name points
* @method
* @memberof Kinetic.Line.prototype
* @param {Array} points
* @returns {Array}
* @example
* // get points<br>
* var points = line.points();<br><br>
*
* // set points<br>
* line.points([10, 20, 30, 40, 50, 60]);<br><br>
*
* // push a new point<br>
* line.points(line.points().concat([70, 80]));
*/
Kinetic.Collection.mapMethods(Kinetic.Line);
})();;(function() {
/**
* Sprite constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} config.animation animation key
* @param {Object} config.animations animation map
* @param {Integer} [config.frameIndex] animation frame index
* @param {Image} config.image image object
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var imageObj = new Image();<br>
* imageObj.onload = function() {<br>
* var sprite = new Kinetic.Sprite({<br>
* x: 200,<br>
* y: 100,<br>
* image: imageObj,<br>
* animation: 'standing',<br>
* animations: {<br>
* standing: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 0, 49, 109,<br>
* 52, 0, 49, 109,<br>
* 105, 0, 49, 109,<br>
* 158, 0, 49, 109,<br>
* 210, 0, 49, 109,<br>
* 262, 0, 49, 109<br>
* ],<br>
* kicking: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 109, 45, 98,<br>
* 45, 109, 45, 98,<br>
* 95, 109, 63, 98,<br>
* 156, 109, 70, 98,<br>
* 229, 109, 60, 98,<br>
* 287, 109, 41, 98<br>
* ]<br>
* },<br>
* frameRate: 7,<br>
* frameIndex: 0<br>
* });<br>
* };<br>
* imageObj.src = '/path/to/image.jpg'
*/
Kinetic.Sprite = function(config) {
this.___init(config);
};
Kinetic.Sprite.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Sprite';
this.anim = new Kinetic.Animation();
this.on('animationChange.kinetic', function() {
// reset index when animation changes
this.frameIndex(0);
});
// smooth change for frameRate
this.on('frameRateChange.kinetic', function() {
if (!this.anim.isRunning()) {
return;
}
clearInterval(this.interval);
this._setInterval();
});
this.sceneFunc(this._sceneFunc);
this.hitFunc(this._hitFunc);
},
_sceneFunc: function(context) {
var anim = this.getAnimation(),
index = this.frameIndex(),
ix4 = index * 4,
set = this.getAnimations()[anim],
x = set[ix4 + 0],
y = set[ix4 + 1],
width = set[ix4 + 2],
height = set[ix4 + 3],
image = this.getImage();
if(image) {
context.drawImage(image, x, y, width, height, 0, 0, width, height);
}
},
_hitFunc: function(context) {
var anim = this.getAnimation(),
index = this.frameIndex(),
ix4 = index * 4,
set = this.getAnimations()[anim],
width = set[ix4 + 2],
height = set[ix4 + 3];
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.fillShape(this);
},
_useBufferCanvas: function() {
return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke();
},
_setInterval: function() {
var that = this;
this.interval = setInterval(function() {
that._updateIndex();
}, 1000 / this.getFrameRate());
},
/**
* start sprite animation
* @method
* @memberof Kinetic.Sprite.prototype
*/
start: function() {
var layer = this.getLayer();
/*
* animation object has no executable function because
* the updates are done with a fixed FPS with the setInterval
* below. The anim object only needs the layer reference for
* redraw
*/
this.anim.setLayers(layer);
this._setInterval();
this.anim.start();
},
/**
* stop sprite animation
* @method
* @memberof Kinetic.Sprite.prototype
*/
stop: function() {
this.anim.stop();
clearInterval(this.interval);
},
/**
* determine if animation of sprite is running or not. returns true or false
* @method
* @memberof Kinetic.Animation.prototype
* @returns {Boolean}
*/
isRunning: function() {
return this.anim.isRunning();
},
_updateIndex: function() {
var index = this.frameIndex(),
animation = this.getAnimation(),
animations = this.getAnimations(),
anim = animations[animation],
len = anim.length / 4;
if(index < len - 1) {
this.frameIndex(index + 1);
}
else {
this.frameIndex(0);
}
}
};
Kinetic.Util.extend(Kinetic.Sprite, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animation');
/**
* get/set animation key
* @name animation
* @method
* @memberof Kinetic.Sprite.prototype
* @param {String} anim animation key
* @returns {String}
* @example
* // get animation key<br>
* var animation = sprite.animation();<br><br>
*
* // set animation key<br>
* sprite.animation('kicking');
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animations');
/**
* get/set animations map
* @name animations
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Object} animations
* @returns {Object}
* @example
* // get animations map<br>
* var animations = sprite.animations();<br><br>
*
* // set animations map<br>
* sprite.animations({<br>
* standing: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 0, 49, 109,<br>
* 52, 0, 49, 109,<br>
* 105, 0, 49, 109,<br>
* 158, 0, 49, 109,<br>
* 210, 0, 49, 109,<br>
* 262, 0, 49, 109<br>
* ],<br>
* kicking: [<br>
* // x, y, width, height (6 frames)<br>
* 0, 109, 45, 98,<br>
* 45, 109, 45, 98,<br>
* 95, 109, 63, 98,<br>
* 156, 109, 70, 98,<br>
* 229, 109, 60, 98,<br>
* 287, 109, 41, 98<br>
* ]<br>
* });
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'image');
/**
* get/set image
* @name image
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Image} image
* @returns {Image}
* @example
* // get image
* var image = sprite.image();<br><br>
*
* // set image<br>
* sprite.image(imageObj);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameIndex', 0);
/**
* set/set animation frame index
* @name frameIndex
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Integer} frameIndex
* @returns {Integer}
* @example
* // get animation frame index<br>
* var frameIndex = sprite.frameIndex();<br><br>
*
* // set animation frame index<br>
* sprite.frameIndex(3);
*/
Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameRate', 17);
/**
* get/set frame rate in frames per second. Increase this number to make the sprite
* animation run faster, and decrease the number to make the sprite animation run slower
* The default is 17 frames per second
* @name frameRate
* @method
* @memberof Kinetic.Sprite.prototype
* @param {Integer} frameRate
* @returns {Integer}
* @example
* // get frame rate<br>
* var frameRate = sprite.frameRate();<br><br>
*
* // set frame rate to 2 frames per second<br>
* sprite.frameRate(2);
*/
Kinetic.Factory.backCompat(Kinetic.Sprite, {
index: 'frameIndex',
getIndex: 'getFrameIndex',
setIndex: 'setFrameIndex'
});
Kinetic.Collection.mapMethods(Kinetic.Sprite);
})();
;(function () {
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} config.data SVG data string
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var path = new Kinetic.Path({<br>
* x: 240,<br>
* y: 40,<br>
* data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z',<br>
* fill: 'green',<br>
* scale: 2<br>
* });
*/
Kinetic.Path = function (config) {
this.___init(config);
};
Kinetic.Path.prototype = {
___init: function (config) {
this.dataArray = [];
var that = this;
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Path';
this.dataArray = Kinetic.Path.parsePathData(this.getData());
this.on('dataChange.kinetic', function () {
that.dataArray = Kinetic.Path.parsePathData(this.getData());
});
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var ca = this.dataArray,
closedPath = false;
// context position
context.beginPath();
for (var n = 0; n < ca.length; n++) {
var c = ca[n].command;
var p = ca[n].points;
switch (c) {
case 'L':
context.lineTo(p[0], p[1]);
break;
case 'M':
context.moveTo(p[0], p[1]);
break;
case 'C':
context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]);
break;
case 'Q':
context.quadraticCurveTo(p[0], p[1], p[2], p[3]);
break;
case 'A':
var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7];
var r = (rx > ry) ? rx : ry;
var scaleX = (rx > ry) ? 1 : rx / ry;
var scaleY = (rx > ry) ? ry / rx : 1;
context.translate(cx, cy);
context.rotate(psi);
context.scale(scaleX, scaleY);
context.arc(0, 0, r, theta, theta + dTheta, 1 - fs);
context.scale(1 / scaleX, 1 / scaleY);
context.rotate(-psi);
context.translate(-cx, -cy);
break;
case 'z':
context.closePath();
closedPath = true;
break;
}
}
if (closedPath) {
context.fillStrokeShape(this);
}
else {
context.strokeShape(this);
}
}
};
Kinetic.Util.extend(Kinetic.Path, Kinetic.Shape);
Kinetic.Path.getLineLength = function(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
};
Kinetic.Path.getPointOnLine = function(dist, P1x, P1y, P2x, P2y, fromX, fromY) {
if(fromX === undefined) {
fromX = P1x;
}
if(fromY === undefined) {
fromY = P1y;
}
var m = (P2y - P1y) / ((P2x - P1x) + 0.00000001);
var run = Math.sqrt(dist * dist / (1 + m * m));
if(P2x < P1x) {
run *= -1;
}
var rise = m * run;
var pt;
if (P2x === P1x) { // vertical line
pt = {
x: fromX,
y: fromY + rise
};
} else if((fromY - P1y) / ((fromX - P1x) + 0.00000001) === m) {
pt = {
x: fromX + run,
y: fromY + rise
};
}
else {
var ix, iy;
var len = this.getLineLength(P1x, P1y, P2x, P2y);
if(len < 0.00000001) {
return undefined;
}
var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y)));
u = u / (len * len);
ix = P1x + u * (P2x - P1x);
iy = P1y + u * (P2y - P1y);
var pRise = this.getLineLength(fromX, fromY, ix, iy);
var pRun = Math.sqrt(dist * dist - pRise * pRise);
run = Math.sqrt(pRun * pRun / (1 + m * m));
if(P2x < P1x) {
run *= -1;
}
rise = m * run;
pt = {
x: ix + run,
y: iy + rise
};
}
return pt;
};
Kinetic.Path.getPointOnCubicBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
function CB1(t) {
return t * t * t;
}
function CB2(t) {
return 3 * t * t * (1 - t);
}
function CB3(t) {
return 3 * t * (1 - t) * (1 - t);
}
function CB4(t) {
return (1 - t) * (1 - t) * (1 - t);
}
var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
return {
x: x,
y: y
};
};
Kinetic.Path.getPointOnQuadraticBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y) {
function QB1(t) {
return t * t;
}
function QB2(t) {
return 2 * t * (1 - t);
}
function QB3(t) {
return (1 - t) * (1 - t);
}
var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
return {
x: x,
y: y
};
};
Kinetic.Path.getPointOnEllipticalArc = function(cx, cy, rx, ry, theta, psi) {
var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi);
var pt = {
x: rx * Math.cos(theta),
y: ry * Math.sin(theta)
};
return {
x: cx + (pt.x * cosPsi - pt.y * sinPsi),
y: cy + (pt.x * sinPsi + pt.y * cosPsi)
};
};
/*
* get parsed data array from the data
* string. V, v, H, h, and l data are converted to
* L data for the purpose of high performance Path
* rendering
*/
Kinetic.Path.parsePathData = function(data) {
// Path Data Segment must begin with a moveTo
//m (x y)+ Relative moveTo (subsequent points are treated as lineTo)
//M (x y)+ Absolute moveTo (subsequent points are treated as lineTo)
//l (x y)+ Relative lineTo
//L (x y)+ Absolute LineTo
//h (x)+ Relative horizontal lineTo
//H (x)+ Absolute horizontal lineTo
//v (y)+ Relative vertical lineTo
//V (y)+ Absolute vertical lineTo
//z (closepath)
//Z (closepath)
//c (x1 y1 x2 y2 x y)+ Relative Bezier curve
//C (x1 y1 x2 y2 x y)+ Absolute Bezier curve
//q (x1 y1 x y)+ Relative Quadratic Bezier
//Q (x1 y1 x y)+ Absolute Quadratic Bezier
//t (x y)+ Shorthand/Smooth Relative Quadratic Bezier
//T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier
//s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve
//S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve
//a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc
//A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc
// return early if data is not defined
if(!data) {
return [];
}
// command string
var cs = data;
// command chars
var cc = ['m', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'];
// convert white spaces to commas
cs = cs.replace(new RegExp(' ', 'g'), ',');
// create pipes so that we can split the data
for(var n = 0; n < cc.length; n++) {
cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
}
// create array
var arr = cs.split('|');
var ca = [];
// init context point
var cpx = 0;
var cpy = 0;
for( n = 1; n < arr.length; n++) {
var str = arr[n];
var c = str.charAt(0);
str = str.slice(1);
// remove ,- for consistency
str = str.replace(new RegExp(',-', 'g'), '-');
// add commas so that it's easy to split
str = str.replace(new RegExp('-', 'g'), ',-');
str = str.replace(new RegExp('e,-', 'g'), 'e-');
var p = str.split(',');
if(p.length > 0 && p[0] === '') {
p.shift();
}
// convert strings to floats
for(var i = 0; i < p.length; i++) {
p[i] = parseFloat(p[i]);
}
while(p.length > 0) {
if(isNaN(p[0])) {// case for a trailing comma before next command
break;
}
var cmd = null;
var points = [];
var startX = cpx, startY = cpy;
// Move var from within the switch to up here (jshint)
var prevCmd, ctlPtx, ctlPty; // Ss, Tt
var rx, ry, psi, fa, fs, x1, y1; // Aa
// convert l, H, h, V, and v to L
switch (c) {
// Note: Keep the lineTo's above the moveTo's in this switch
case 'l':
cpx += p.shift();
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'L':
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
// Note: lineTo handlers need to be above this point
case 'm':
var dx = p.shift();
var dy = p.shift();
cpx += dx;
cpy += dy;
cmd = 'M';
// After closing the path move the current position
// to the the first point of the path (if any).
if(ca.length>2 && ca[ca.length-1].command==='z'){
for(var idx=ca.length-2;idx>=0;idx--){
if(ca[idx].command==='M'){
cpx=ca[idx].points[0]+dx;
cpy=ca[idx].points[1]+dy;
break;
}
}
}
points.push(cpx, cpy);
c = 'l';
// subsequent points are treated as relative lineTo
break;
case 'M':
cpx = p.shift();
cpy = p.shift();
cmd = 'M';
points.push(cpx, cpy);
c = 'L';
// subsequent points are treated as absolute lineTo
break;
case 'h':
cpx += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'H':
cpx = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'v':
cpy += p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'V':
cpy = p.shift();
cmd = 'L';
points.push(cpx, cpy);
break;
case 'C':
points.push(p.shift(), p.shift(), p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'c':
points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'S':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 's':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'C') {
ctlPtx = cpx + (cpx - prevCmd.points[2]);
ctlPty = cpy + (cpy - prevCmd.points[3]);
}
points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'C';
points.push(cpx, cpy);
break;
case 'Q':
points.push(p.shift(), p.shift());
cpx = p.shift();
cpy = p.shift();
points.push(cpx, cpy);
break;
case 'q':
points.push(cpx + p.shift(), cpy + p.shift());
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(cpx, cpy);
break;
case 'T':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx = p.shift();
cpy = p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 't':
ctlPtx = cpx;
ctlPty = cpy;
prevCmd = ca[ca.length - 1];
if(prevCmd.command === 'Q') {
ctlPtx = cpx + (cpx - prevCmd.points[0]);
ctlPty = cpy + (cpy - prevCmd.points[1]);
}
cpx += p.shift();
cpy += p.shift();
cmd = 'Q';
points.push(ctlPtx, ctlPty, cpx, cpy);
break;
case 'A':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy;
cpx = p.shift();
cpy = p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
case 'a':
rx = p.shift();
ry = p.shift();
psi = p.shift();
fa = p.shift();
fs = p.shift();
x1 = cpx;
y1 = cpy; cpx += p.shift();
cpy += p.shift();
cmd = 'A';
points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi);
break;
}
ca.push({
command: cmd || c,
points: points,
start: {
x: startX,
y: startY
},
pathLength: this.calcLength(startX, startY, cmd || c, points)
});
}
if(c === 'z' || c === 'Z') {
ca.push({
command: 'z',
points: [],
start: undefined,
pathLength: 0
});
}
}
return ca;
};
Kinetic.Path.calcLength = function(x, y, cmd, points) {
var len, p1, p2, t;
var path = Kinetic.Path;
switch (cmd) {
case 'L':
return path.getLineLength(x, y, points[0], points[1]);
case 'C':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
for( t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'Q':
// Approximates by breaking curve into 100 line segments
len = 0.0;
p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
for( t = 0.01; t <= 1; t += 0.01) {
p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
return len;
case 'A':
// Approximates by breaking curve into line segments
len = 0.0;
var start = points[4];
// 4 = theta
var dTheta = points[5];
// 5 = dTheta
var end = points[4] + dTheta;
var inc = Math.PI / 180.0;
// 1 degree resolution
if(Math.abs(start - end) < inc) {
inc = Math.abs(start - end);
}
// Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
if(dTheta < 0) {// clockwise
for( t = start - inc; t > end; t -= inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
else {// counter-clockwise
for( t = start + inc; t < end; t += inc) {
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0);
len += path.getLineLength(p1.x, p1.y, p2.x, p2.y);
return len;
}
return 0;
};
Kinetic.Path.convertEndpointToCenterParameterization = function(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) {
// Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
var psi = psiDeg * (Math.PI / 180.0);
var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0;
var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0;
var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
if(lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)));
if(fa === fs) {
f *= -1;
}
if(isNaN(f)) {
f = 0;
}
var cxp = f * rx * yp / ry;
var cyp = f * -ry * xp / rx;
var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp;
var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp;
var vMag = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
};
var vRatio = function(u, v) {
return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
};
var vAngle = function(u, v) {
return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
};
var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
var u = [(xp - cxp) / rx, (yp - cyp) / ry];
var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
var dTheta = vAngle(u, v);
if(vRatio(u, v) <= -1) {
dTheta = Math.PI;
}
if(vRatio(u, v) >= 1) {
dTheta = 0;
}
if(fs === 0 && dTheta > 0) {
dTheta = dTheta - 2 * Math.PI;
}
if(fs === 1 && dTheta < 0) {
dTheta = dTheta + 2 * Math.PI;
}
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
};
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Path, 'data');
/**
* set SVG path data string. This method
* also automatically parses the data string
* into a data array. Currently supported SVG data:
* M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z
* @name setData
* @method
* @memberof Kinetic.Path.prototype
* @param {String} SVG path command string
*/
/**
* get SVG path data string
* @name getData
* @method
* @memberof Kinetic.Path.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Path);
})();
;(function() {
var EMPTY_STRING = '',
//CALIBRI = 'Calibri',
NORMAL = 'normal';
/**
* Path constructor.
* @author Jason Follas
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {String} [config.fontFamily] default is Calibri
* @param {Number} [config.fontSize] default is 12
* @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal
* @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
* @param {String} config.text
* @param {String} config.data SVG data string
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var textpath = new Kinetic.TextPath({<br>
* x: 100,<br>
* y: 50,<br>
* fill: '#333',<br>
* fontSize: '24',<br>
* fontFamily: 'Arial',<br>
* text: 'All the world\'s a stage, and all the men and women merely players.',<br>
* data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'<br>
* });
*/
Kinetic.TextPath = function(config) {
this.___init(config);
};
function _fillFunc(context) {
context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
context.strokeText(this.partialText, 0, 0);
}
Kinetic.TextPath.prototype = {
___init: function(config) {
var that = this;
this.dummyCanvas = Kinetic.Util.createCanvasElement();
this.dataArray = [];
// call super constructor
Kinetic.Shape.call(this, config);
// overrides
// TODO: shouldn't this be on the prototype?
this._fillFunc = _fillFunc;
this._strokeFunc = _strokeFunc;
this._fillFuncHit = _fillFunc;
this._strokeFuncHit = _strokeFunc;
this.className = 'TextPath';
this.dataArray = Kinetic.Path.parsePathData(this.attrs.data);
this.on('dataChange.kinetic', function() {
that.dataArray = Kinetic.Path.parsePathData(this.attrs.data);
});
// update text data for certain attr changes
this.on('textChange.kinetic textStroke.kinetic textStrokeWidth.kinetic', that._setTextData);
that._setTextData();
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
context.setAttr('font', this._getContextFont());
context.setAttr('textBaseline', 'middle');
context.setAttr('textAlign', 'left');
context.save();
var glyphInfo = this.glyphInfo;
for(var i = 0; i < glyphInfo.length; i++) {
context.save();
var p0 = glyphInfo[i].p0;
context.translate(p0.x, p0.y);
context.rotate(glyphInfo[i].rotation);
this.partialText = glyphInfo[i].text;
context.fillStrokeShape(this);
context.restore();
//// To assist with debugging visually, uncomment following
// context.beginPath();
// if (i % 2)
// context.strokeStyle = 'cyan';
// else
// context.strokeStyle = 'green';
// var p1 = glyphInfo[i].p1;
// context.moveTo(p0.x, p0.y);
// context.lineTo(p1.x, p1.y);
// context.stroke();
}
context.restore();
},
/**
* get text width in pixels
* @method
* @memberof Kinetic.TextPath.prototype
*/
getTextWidth: function() {
return this.textWidth;
},
/**
* get text height in pixels
* @method
* @memberof Kinetic.TextPath.prototype
*/
getTextHeight: function() {
return this.textHeight;
},
/**
* set text
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} text
*/
setText: function(text) {
Kinetic.Text.prototype.setText.call(this, text);
},
_getTextSize: function(text) {
var dummyCanvas = this.dummyCanvas;
var _context = dummyCanvas.getContext('2d');
_context.save();
_context.font = this._getContextFont();
var metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(this.attrs.fontSize, 10)
};
},
_setTextData: function() {
var that = this;
var size = this._getTextSize(this.attrs.text);
this.textWidth = size.width;
this.textHeight = size.height;
this.glyphInfo = [];
var charArr = this.attrs.text.split('');
var p0, p1, pathCmd;
var pIndex = -1;
var currentT = 0;
var getNextPathSegment = function() {
currentT = 0;
var pathData = that.dataArray;
for(var i = pIndex + 1; i < pathData.length; i++) {
if(pathData[i].pathLength > 0) {
pIndex = i;
return pathData[i];
}
else if(pathData[i].command == 'M') {
p0 = {
x: pathData[i].points[0],
y: pathData[i].points[1]
};
}
}
return {};
};
var findSegmentToFitCharacter = function(c) {
var glyphWidth = that._getTextSize(c).width;
var currLen = 0;
var attempts = 0;
p1 = undefined;
while(Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 && attempts < 25) {
attempts++;
var cumulativePathLength = currLen;
while(pathCmd === undefined) {
pathCmd = getNextPathSegment();
if(pathCmd && cumulativePathLength + pathCmd.pathLength < glyphWidth) {
cumulativePathLength += pathCmd.pathLength;
pathCmd = undefined;
}
}
if(pathCmd === {} || p0 === undefined) {
return undefined;
}
var needNewSegment = false;
switch (pathCmd.command) {
case 'L':
if(Kinetic.Path.getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) {
p1 = Kinetic.Path.getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y);
}
else {
pathCmd = undefined;
}
break;
case 'A':
var start = pathCmd.points[4];
// 4 = theta
var dTheta = pathCmd.points[5];
// 5 = dTheta
var end = pathCmd.points[4] + dTheta;
if(currentT === 0){
currentT = start + 0.00000001;
}
// Just in case start is 0
else if(glyphWidth > currLen) {
currentT += (Math.PI / 180.0) * dTheta / Math.abs(dTheta);
}
else {
currentT -= Math.PI / 360.0 * dTheta / Math.abs(dTheta);
}
// Credit for bug fix: @therth https://github.com/ericdrowell/KineticJS/issues/249
// Old code failed to render text along arc of this path: "M 50 50 a 150 50 0 0 1 250 50 l 50 0"
if(dTheta < 0 && currentT < end || dTheta >= 0 && currentT > end) {
currentT = end;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]);
break;
case 'C':
if(currentT === 0) {
if(glyphWidth > pathCmd.pathLength) {
currentT = 0.00000001;
}
else {
currentT = glyphWidth / pathCmd.pathLength;
}
}
else if(glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength;
}
else {
currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
}
if(currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]);
break;
case 'Q':
if(currentT === 0) {
currentT = glyphWidth / pathCmd.pathLength;
}
else if(glyphWidth > currLen) {
currentT += (glyphWidth - currLen) / pathCmd.pathLength;
}
else {
currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
}
if(currentT > 1.0) {
currentT = 1.0;
needNewSegment = true;
}
p1 = Kinetic.Path.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]);
break;
}
if(p1 !== undefined) {
currLen = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
}
if(needNewSegment) {
needNewSegment = false;
pathCmd = undefined;
}
}
};
for(var i = 0; i < charArr.length; i++) {
// Find p1 such that line segment between p0 and p1 is approx. width of glyph
findSegmentToFitCharacter(charArr[i]);
if(p0 === undefined || p1 === undefined) {
break;
}
var width = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
// Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used.
// Can foresee having a rough pair table built in that the developer can override as needed.
var kern = 0;
// placeholder for future implementation
var midpoint = Kinetic.Path.getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y);
var rotation = Math.atan2((p1.y - p0.y), (p1.x - p0.x));
this.glyphInfo.push({
transposeX: midpoint.x,
transposeY: midpoint.y,
text: charArr[i],
rotation: rotation,
p0: p0,
p1: p1
});
p0 = p1;
}
}
};
// map TextPath methods to Text
Kinetic.TextPath.prototype._getContextFont = Kinetic.Text.prototype._getContextFont;
Kinetic.Util.extend(Kinetic.TextPath, Kinetic.Shape);
// add setters and getters
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontFamily', 'Arial');
/**
* set font family
* @name setFontFamily
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontFamily
*/
/**
* get font family
* @name getFontFamily
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontSize', 12);
/**
* set font size
* @name setFontSize
* @method
* @memberof Kinetic.TextPath.prototype
* @param {int} fontSize
*/
/**
* get font size
* @name getFontSize
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontStyle', NORMAL);
/**
* set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default.
* @name setFontStyle
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontStyle
*/
/**
* get font style
* @name getFontStyle
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontVariant', NORMAL);
/**
* set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
* @name setFontVariant
* @method
* @memberof Kinetic.TextPath.prototype
* @param {String} fontVariant
*/
/**
* @get font variant
* @name getFontVariant
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Factory.addGetter(Kinetic.TextPath, 'text', EMPTY_STRING);
/**
* get text
* @name getText
* @method
* @memberof Kinetic.TextPath.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.TextPath);
})();
;(function() {
/**
* RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc.
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Number} config.sides
* @param {Number} config.radius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var hexagon = new Kinetic.RegularPolygon({<br>
* x: 100,<br>
* y: 200,<br>
* sides: 6,<br>
* radius: 70,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 4<br>
* });
*/
Kinetic.RegularPolygon = function(config) {
this.___init(config);
};
Kinetic.RegularPolygon.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'RegularPolygon';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var sides = this.attrs.sides,
radius = this.attrs.radius,
n, x, y;
context.beginPath();
context.moveTo(0, 0 - radius);
for(n = 1; n < sides; n++) {
x = radius * Math.sin(n * 2 * Math.PI / sides);
y = -1 * radius * Math.cos(n * 2 * Math.PI / sides);
context.lineTo(x, y);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.RegularPolygon, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'radius', 0);
/**
* set radius
* @name setRadius
* @method
* @memberof Kinetic.RegularPolygon.prototype
* @param {Number} radius
*/
/**
* get radius
* @name getRadius
* @method
* @memberof Kinetic.RegularPolygon.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'sides', 0);
/**
* set number of sides
* @name setSides
* @method
* @memberof Kinetic.RegularPolygon.prototype
* @param {int} sides
*/
/**
* get number of sides
* @name getSides
* @method
* @memberof Kinetic.RegularPolygon.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.RegularPolygon);
})();
;(function() {
/**
* Star constructor
* @constructor
* @memberof Kinetic
* @augments Kinetic.Shape
* @param {Object} config
* @param {Integer} config.numPoints
* @param {Number} config.innerRadius
* @param {Number} config.outerRadius
* @param {String} [config.fill] fill color
* @param {Integer} [config.fillRed] set fill red component
* @param {Integer} [config.fillGreen] set fill green component
* @param {Integer} [config.fillBlue] set fill blue component
* @param {Integer} [config.fillAlpha] set fill alpha component
* @param {Image} [config.fillPatternImage] fill pattern image
* @param {Number} [config.fillPatternX]
* @param {Number} [config.fillPatternY]
* @param {Object} [config.fillPatternOffset] object with x and y component
* @param {Number} [config.fillPatternOffsetX]
* @param {Number} [config.fillPatternOffsetY]
* @param {Object} [config.fillPatternScale] object with x and y component
* @param {Number} [config.fillPatternScaleX]
* @param {Number} [config.fillPatternScaleY]
* @param {Number} [config.fillPatternRotation]
* @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
* @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
* @param {Number} [config.fillLinearGradientStartPointX]
* @param {Number} [config.fillLinearGradientStartPointY]
* @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
* @param {Number} [config.fillLinearGradientEndPointX]
* @param {Number} [config.fillLinearGradientEndPointY]
* @param {Array} [config.fillLinearGradientColorStops] array of color stops
* @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
* @param {Number} [config.fillRadialGradientStartPointX]
* @param {Number} [config.fillRadialGradientStartPointY]
* @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
* @param {Number} [config.fillRadialGradientEndPointX]
* @param {Number} [config.fillRadialGradientEndPointY]
* @param {Number} [config.fillRadialGradientStartRadius]
* @param {Number} [config.fillRadialGradientEndRadius]
* @param {Array} [config.fillRadialGradientColorStops] array of color stops
* @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
* @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
* @param {String} [config.stroke] stroke color
* @param {Integer} [config.strokeRed] set stroke red component
* @param {Integer} [config.strokeGreen] set stroke green component
* @param {Integer} [config.strokeBlue] set stroke blue component
* @param {Integer} [config.strokeAlpha] set stroke alpha component
* @param {Number} [config.strokeWidth] stroke width
* @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
* @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
* @param {String} [config.lineJoin] can be miter, round, or bevel. The default
* is miter
* @param {String} [config.lineCap] can be butt, round, or sqare. The default
* is butt
* @param {String} [config.shadowColor]
* @param {Integer} [config.shadowRed] set shadow color red component
* @param {Integer} [config.shadowGreen] set shadow color green component
* @param {Integer} [config.shadowBlue] set shadow color blue component
* @param {Integer} [config.shadowAlpha] set shadow color alpha component
* @param {Number} [config.shadowBlur]
* @param {Object} [config.shadowOffset] object with x and y component
* @param {Number} [config.shadowOffsetX]
* @param {Number} [config.shadowOffsetY]
* @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
* between 0 and 1
* @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
* @param {Array} [config.dash]
* @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* var star = new Kinetic.Star({<br>
* x: 100,<br>
* y: 200,<br>
* numPoints: 5,<br>
* innerRadius: 70,<br>
* outerRadius: 70,<br>
* fill: 'red',<br>
* stroke: 'black',<br>
* strokeWidth: 4<br>
* });
*/
Kinetic.Star = function(config) {
this.___init(config);
};
Kinetic.Star.prototype = {
___init: function(config) {
// call super constructor
Kinetic.Shape.call(this, config);
this.className = 'Star';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var innerRadius = this.innerRadius(),
outerRadius = this.outerRadius(),
numPoints = this.numPoints();
context.beginPath();
context.moveTo(0, 0 - outerRadius);
for(var n = 1; n < numPoints * 2; n++) {
var radius = n % 2 === 0 ? outerRadius : innerRadius;
var x = radius * Math.sin(n * Math.PI / numPoints);
var y = -1 * radius * Math.cos(n * Math.PI / numPoints);
context.lineTo(x, y);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Star, Kinetic.Shape);
// add getters setters
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'numPoints', 5);
/**
* set number of points
* @name setNumPoints
* @method
* @memberof Kinetic.Star.prototype
* @param {Integer} points
*/
/**
* get number of points
* @name getNumPoints
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'innerRadius', 0);
/**
* set inner radius
* @name setInnerRadius
* @method
* @memberof Kinetic.Star.prototype
* @param {Number} radius
*/
/**
* get inner radius
* @name getInnerRadius
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Star, 'outerRadius', 0);
/**
* set outer radius
* @name setOuterRadius
* @method
* @memberof Kinetic.Star.prototype
* @param {Number} radius
*/
/**
* get outer radius
* @name getOuterRadius
* @method
* @memberof Kinetic.Star.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Star);
})();
;(function() {
// constants
var ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'padding', 'lineHeight', 'text'],
CHANGE_KINETIC = 'Change.kinetic',
NONE = 'none',
UP = 'up',
RIGHT = 'right',
DOWN = 'down',
LEFT = 'left',
LABEL = 'Label',
// cached variables
attrChangeListLen = ATTR_CHANGE_LIST.length;
/**
* Label constructor. Labels are groups that contain a Text and Tag shape
* @constructor
* @memberof Kinetic
* @param {Object} config
* @param {Number} [config.x]
* @param {Number} [config.y]
* @param {Number} [config.width]
* @param {Number} [config.height]
* @param {Boolean} [config.visible]
* @param {Boolean} [config.listening] whether or not the node is listening for events
* @param {String} [config.id] unique id
* @param {String} [config.name] non-unique name
* @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
* @param {Object} [config.scale] set scale
* @param {Number} [config.scaleX] set scale x
* @param {Number} [config.scaleY] set scale y
* @param {Number} [config.rotation] rotation in degrees
* @param {Object} [config.offset] offset from center point and rotation point
* @param {Number} [config.offsetX] set offset x
* @param {Number} [config.offsetY] set offset y
* @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
* the entire stage by dragging any portion of the stage
* @param {Number} [config.dragDistance]
* @param {Function} [config.dragBoundFunc]
* @example
* // create label
* var label = new Kinetic.Label({<br>
* x: 100,<br>
* y: 100, <br>
* draggable: true<br>
* });<br><br>
*
* // add a tag to the label<br>
* label.add(new Kinetic.Tag({<br>
* fill: '#bbb',<br>
* stroke: '#333',<br>
* shadowColor: 'black',<br>
* shadowBlur: 10,<br>
* shadowOffset: [10, 10],<br>
* shadowOpacity: 0.2,<br>
* lineJoin: 'round',<br>
* pointerDirection: 'up',<br>
* pointerWidth: 20,<br>
* pointerHeight: 20,<br>
* cornerRadius: 5<br>
* }));<br><br>
*
* // add text to the label<br>
* label.add(new Kinetic.Text({<br>
* text: 'Hello World!',<br>
* fontSize: 50,<br>
* lineHeight: 1.2,<br>
* padding: 10,<br>
* fill: 'green'<br>
* }));
*/
Kinetic.Label = function(config) {
this.____init(config);
};
Kinetic.Label.prototype = {
____init: function(config) {
var that = this;
this.className = LABEL;
Kinetic.Group.call(this, config);
this.on('add.kinetic', function(evt) {
that._addListeners(evt.child);
that._sync();
});
},
/**
* get Text shape for the label. You need to access the Text shape in order to update
* the text properties
* @name getText
* @method
* @memberof Kinetic.Label.prototype
*/
getText: function() {
return this.find('Text')[0];
},
/**
* get Tag shape for the label. You need to access the Tag shape in order to update
* the pointer properties and the corner radius
* @name getTag
* @method
* @memberof Kinetic.Label.prototype
*/
getTag: function() {
return this.find('Tag')[0];
},
_addListeners: function(text) {
var that = this,
n;
var func = function(){
that._sync();
};
// update text data for certain attr changes
for(n = 0; n < attrChangeListLen; n++) {
text.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, func);
}
},
getWidth: function() {
return this.getText().getWidth();
},
getHeight: function() {
return this.getText().getHeight();
},
_sync: function() {
var text = this.getText(),
tag = this.getTag(),
width, height, pointerDirection, pointerWidth, x, y, pointerHeight;
if (text && tag) {
width = text.getWidth();
height = text.getHeight();
pointerDirection = tag.getPointerDirection();
pointerWidth = tag.getPointerWidth();
pointerHeight = tag.getPointerHeight();
x = 0;
y = 0;
switch(pointerDirection) {
case UP:
x = width / 2;
y = -1 * pointerHeight;
break;
case RIGHT:
x = width + pointerWidth;
y = height / 2;
break;
case DOWN:
x = width / 2;
y = height + pointerHeight;
break;
case LEFT:
x = -1 * pointerWidth;
y = height / 2;
break;
}
tag.setAttrs({
x: -1 * x,
y: -1 * y,
width: width,
height: height
});
text.setAttrs({
x: -1 * x,
y: -1 * y
});
}
}
};
Kinetic.Util.extend(Kinetic.Label, Kinetic.Group);
Kinetic.Collection.mapMethods(Kinetic.Label);
/**
* Tag constructor. A Tag can be configured
* to have a pointer element that points up, right, down, or left
* @constructor
* @memberof Kinetic
* @param {Object} config
* @param {String} [config.pointerDirection] can be up, right, down, left, or none; the default
* is none. When a pointer is present, the positioning of the label is relative to the tip of the pointer.
* @param {Number} [config.pointerWidth]
* @param {Number} [config.pointerHeight]
* @param {Number} [config.cornerRadius]
*/
Kinetic.Tag = function(config) {
this.___init(config);
};
Kinetic.Tag.prototype = {
___init: function(config) {
Kinetic.Shape.call(this, config);
this.className = 'Tag';
this.sceneFunc(this._sceneFunc);
},
_sceneFunc: function(context) {
var width = this.getWidth(),
height = this.getHeight(),
pointerDirection = this.getPointerDirection(),
pointerWidth = this.getPointerWidth(),
pointerHeight = this.getPointerHeight();
//cornerRadius = this.getCornerRadius();
context.beginPath();
context.moveTo(0,0);
if (pointerDirection === UP) {
context.lineTo((width - pointerWidth)/2, 0);
context.lineTo(width/2, -1 * pointerHeight);
context.lineTo((width + pointerWidth)/2, 0);
}
context.lineTo(width, 0);
if (pointerDirection === RIGHT) {
context.lineTo(width, (height - pointerHeight)/2);
context.lineTo(width + pointerWidth, height/2);
context.lineTo(width, (height + pointerHeight)/2);
}
context.lineTo(width, height);
if (pointerDirection === DOWN) {
context.lineTo((width + pointerWidth)/2, height);
context.lineTo(width/2, height + pointerHeight);
context.lineTo((width - pointerWidth)/2, height);
}
context.lineTo(0, height);
if (pointerDirection === LEFT) {
context.lineTo(0, (height + pointerHeight)/2);
context.lineTo(-1 * pointerWidth, height/2);
context.lineTo(0, (height - pointerHeight)/2);
}
context.closePath();
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Kinetic.Tag, Kinetic.Shape);
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerDirection', NONE);
/**
* set pointer Direction
* @name setPointerDirection
* @method
* @memberof Kinetic.Tag.prototype
* @param {String} pointerDirection can be up, right, down, left, or none. The
* default is none
*/
/**
* get pointer Direction
* @name getPointerDirection
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerWidth', 0);
/**
* set pointer width
* @name setPointerWidth
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} pointerWidth
*/
/**
* get pointer width
* @name getPointerWidth
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerHeight', 0);
/**
* set pointer height
* @name setPointerHeight
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} pointerHeight
*/
/**
* get pointer height
* @name getPointerHeight
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'cornerRadius', 0);
/**
* set corner radius
* @name setCornerRadius
* @method
* @memberof Kinetic.Tag.prototype
* @param {Number} corner radius
*/
/**
* get corner radius
* @name getCornerRadius
* @method
* @memberof Kinetic.Tag.prototype
*/
Kinetic.Collection.mapMethods(Kinetic.Tag);
})();
|
/*!
* inferno v0.7.3
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Inferno = factory());
}(this, function () { 'use strict';
var babelHelpers = {};
babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
babelHelpers.extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers;
function isNullOrUndefined(obj) {
return obj === void 0 || obj === null;
}
function isAttrAnEvent(attr) {
return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function createBlueprint(shape, childrenType) {
var tag = shape.tag || null;
var tagIsDynamic = tag && tag.arg !== void 0 ? true : false;
var children = !isNullOrUndefined(shape.children) ? shape.children : null;
var childrenIsDynamic = children && children.arg !== void 0 ? true : false;
var attrs = shape.attrs || null;
var attrsIsDynamic = attrs && attrs.arg !== void 0 ? true : false;
var hooks = shape.hooks || null;
var hooksIsDynamic = hooks && hooks.arg !== void 0 ? true : false;
var events = shape.events || null;
var eventsIsDynamic = events && events.arg !== void 0 ? true : false;
var key = shape.key !== void 0 ? shape.key : null;
var keyIsDynamic = !isNullOrUndefined(key) && !isNullOrUndefined(key.arg);
var style = shape.style || null;
var styleIsDynamic = style && style.arg !== void 0 ? true : false;
var className = shape.className !== void 0 ? shape.className : null;
var classNameIsDynamic = className && className.arg !== void 0 ? true : false;
var blueprint = {
lazy: shape.lazy || false,
dom: null,
pools: {
keyed: {},
nonKeyed: []
},
tag: !tagIsDynamic ? tag : null,
className: className !== '' && className ? className : null,
style: style !== '' && style ? style : null,
isComponent: tagIsDynamic,
hasAttrs: attrsIsDynamic || (attrs ? true : false),
hasHooks: hooksIsDynamic,
hasEvents: eventsIsDynamic,
hasStyle: styleIsDynamic || (style !== '' && style ? true : false),
hasClassName: classNameIsDynamic || (className !== '' && className ? true : false),
childrenType: childrenType === void 0 ? children ? 5 : 0 : childrenType,
attrKeys: null,
eventKeys: null,
isSVG: shape.isSVG || false
};
return function () {
var vNode = new VNode(blueprint);
if (tagIsDynamic === true) {
vNode.tag = arguments[tag.arg];
}
if (childrenIsDynamic === true) {
vNode.children = arguments[children.arg];
}
if (attrsIsDynamic === true) {
vNode.attrs = arguments[attrs.arg];
} else {
vNode.attrs = attrs;
}
if (hooksIsDynamic === true) {
vNode.hooks = arguments[hooks.arg];
}
if (eventsIsDynamic === true) {
vNode.events = arguments[events.arg];
}
if (keyIsDynamic === true) {
vNode.key = arguments[key.arg];
}
if (styleIsDynamic === true) {
vNode.style = arguments[style.arg];
} else {
vNode.style = blueprint.style;
}
if (classNameIsDynamic === true) {
vNode.className = arguments[className.arg];
} else {
vNode.className = blueprint.className;
}
return vNode;
};
}
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
// Copy of the util from dom/util, otherwise it makes massive bundles
function documentCreateElement(tag, isSVG) {
var dom = void 0;
if (isSVG === true) {
dom = document.createElementNS('http://www.w3.org/2000/svg', tag);
} else {
dom = document.createElement(tag);
}
return dom;
}
function createUniversalElement(tag, attrs, isSVG) {
if (isBrowser) {
var dom = documentCreateElement(tag, isSVG);
if (attrs) {
createStaticAttributes(attrs, dom);
}
return dom;
}
return null;
}
function createStaticAttributes(attrs, dom) {
var attrKeys = Object.keys(attrs);
for (var i = 0; i < attrKeys.length; i++) {
var attr = attrKeys[i];
var value = attrs[attr];
if (attr === 'className') {
dom.className = value;
} else {
if (value === true) {
dom.setAttribute(attr, attr);
} else if (!isNullOrUndefined(value) && value !== false && !isAttrAnEvent(attr)) {
dom.setAttribute(attr, value);
}
}
}
}
var index = {
createBlueprint: createBlueprint,
createVNode: createVNode,
universal: {
createElement: createUniversalElement
}
};
return index;
})); |
(function () {
/*** Variables ***/
var win = window,
doc = document,
attrProto = {
setAttribute: Element.prototype.setAttribute,
removeAttribute: Element.prototype.removeAttribute
},
hasShadow = Element.prototype.createShadowRoot,
container = doc.createElement('div'),
noop = function(){},
trueop = function(){ return true; },
regexReplaceCommas = /,/g,
regexCamelToDash = /([a-z])([A-Z])/g,
regexPseudoParens = /\(|\)/g,
regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,
regexDigits = /(\d+)/g,
keypseudo = {
action: function (pseudo, event) {
return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null;
}
},
/*
- The prefix object generated here is added to the xtag object as xtag.prefix later in the code
- Prefix provides a variety of prefix variations for the browser in which your code is running
- The 4 variations of prefix are as follows:
* prefix.dom: the correct prefix case and form when used on DOM elements/style properties
* prefix.lowercase: a lowercase version of the prefix for use in various user-code situations
* prefix.css: the lowercase, dashed version of the prefix
* prefix.js: addresses prefixed APIs present in global and non-Element contexts
*/
prefix = (function () {
var styles = win.getComputedStyle(doc.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1];
return {
dom: pre == 'ms' ? 'MS' : pre,
lowercase: pre,
css: '-' + pre + '-',
js: pre == 'ms' ? pre : pre[0].toUpperCase() + pre.substr(1)
};
})(),
matchSelector = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector'];
/*** Functions ***/
// Utilities
/*
This is an enhanced typeof check for all types of objects. Where typeof would normaly return
'object' for many common DOM objects (like NodeLists and HTMLCollections).
- For example: typeOf(document.children) will correctly return 'htmlcollection'
*/
var typeCache = {},
typeString = typeCache.toString,
typeRegexp = /\s([a-zA-Z]+)/;
function typeOf(obj) {
var type = typeString.call(obj);
return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase());
}
function clone(item, type){
var fn = clone[type || typeOf(item)];
return fn ? fn(item) : item;
}
clone.object = function(src){
var obj = {};
for (var key in src) obj[key] = clone(src[key]);
return obj;
};
clone.array = function(src){
var i = src.length, array = new Array(i);
while (i--) array[i] = clone(src[i]);
return array;
};
/*
The toArray() method allows for conversion of any object to a true array. For types that
cannot be converted to an array, the method returns a 1 item array containing the passed-in object.
*/
var unsliceable = { 'undefined': 1, 'null': 1, 'number': 1, 'boolean': 1, 'string': 1, 'function': 1 };
function toArray(obj){
return unsliceable[typeOf(obj)] ? [obj] : Array.prototype.slice.call(obj, 0);
}
// DOM
var str = '';
function query(element, selector){
return (selector || str).length ? toArray(element.querySelectorAll(selector)) : [];
}
// Pseudos
function parsePseudo(fn){fn();}
// Mixins
function mergeOne(source, key, current){
var type = typeOf(current);
if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current);
else source[key] = clone(current, type);
return source;
}
function mergeMixin(tag, original, mixin, name) {
var key, keys = {};
for (var z in original) keys[z.split(':')[0]] = z;
for (z in mixin) {
key = keys[z.split(':')[0]];
if (typeof original[key] == 'function') {
if (!key.match(':mixins')) {
original[key + ':mixins'] = original[key];
delete original[key];
key = key + ':mixins';
}
original[key].__mixin__ = xtag.applyPseudos(z + (z.match(':mixins') ? '' : ':mixins'), mixin[z], tag.pseudos, original[key].__mixin__);
}
else {
original[z] = mixin[z];
delete original[key];
}
}
}
var uniqueMixinCount = 0;
function addMixin(tag, original, mixin){
for (var z in mixin){
original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos);
}
}
function resolveMixins(mixins, output){
var index = mixins.length;
while (index--){
output.unshift(mixins[index]);
if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output);
}
return output;
}
function applyMixins(tag) {
resolveMixins(tag.mixins, []).forEach(function(name){
var mixin = xtag.mixins[name];
for (var type in mixin) {
var item = mixin[type],
original = tag[type];
if (!original) tag[type] = item;
else {
switch (type){
case 'mixins': break;
case 'events': addMixin(tag, original, item); break;
case 'accessors':
case 'prototype':
for (var z in item) {
if (!original[z]) original[z] = item[z];
else mergeMixin(tag, original[z], item[z], name);
}
break;
default: mergeMixin(tag, original, item, name);
}
}
}
});
return tag;
}
// Events
function delegateAction(pseudo, event) {
var match,
target = event.target,
root = event.currentTarget;
while (!match && target && target != root) {
if (target.tagName && matchSelector.call(target, pseudo.value)) match = target;
target = target.parentNode;
}
if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root;
return match ? pseudo.listener = pseudo.listener.bind(match) : null;
}
function touchFilter(event){
return event.button === 0;
}
function writeProperty(key, event, base, desc){
if (desc) event[key] = base[key];
else Object.defineProperty(event, key, {
writable: true,
enumerable: true,
value: base[key]
});
}
var skipProps = {};
for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1;
function inheritEvent(event, base){
var desc = Object.getOwnPropertyDescriptor(event, 'target');
for (var z in base) {
if (!skipProps[z]) writeProperty(z, event, base, desc);
}
event.baseEvent = base;
}
// Accessors
function modAttr(element, attr, name, value, method){
attrProto[method].call(element, name, attr && attr.boolean ? '' : value);
}
function syncAttr(element, attr, name, value, method){
if (attr && (attr.property || attr.selector)) {
var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [],
index = nodes.length;
while (index--) nodes[index][method](name, value);
}
}
function attachProperties(tag, prop, z, accessor, attr, name){
var key = z.split(':'), type = key[0];
if (type == 'get') {
key[0] = prop;
tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]);
}
else if (type == 'set') {
key[0] = prop;
var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){
var old, method = 'setAttribute';
if (attr.boolean){
value = !!value;
old = this.hasAttribute(name);
if (!value) method = 'removeAttribute';
}
else {
value = attr.validate ? attr.validate.call(this, value) : value;
old = this.getAttribute(name);
}
modAttr(this, attr, name, value, method);
accessor[z].call(this, value, old);
syncAttr(this, attr, name, value, method);
} : accessor[z] ? function(value){
accessor[z].call(this, value);
} : null, tag.pseudos, accessor[z]);
if (attr) attr.setter = accessor[z];
}
else tag.prototype[prop][z] = accessor[z];
}
function parseAccessor(tag, prop){
tag.prototype[prop] = {};
var accessor = tag.accessors[prop],
attr = accessor.attribute,
name;
if (attr) {
name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase();
attr.key = prop;
tag.attributes[name] = attr;
}
for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name);
if (attr) {
if (!tag.prototype[prop].get) {
var method = (attr.boolean ? 'has' : 'get') + 'Attribute';
tag.prototype[prop].get = function(){
return this[method](name);
};
}
if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){
value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value;
var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute';
modAttr(this, attr, name, value, method);
syncAttr(this, attr, name, value, method);
};
}
}
var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//;
function parseMultiline(fn){
return typeof fn == 'function' ? unwrapComment.exec(fn.toString())[1] : fn;
}
/*** X-Tag Object Definition ***/
var xtag = {
tags: {},
defaultOptions: {
pseudos: [],
mixins: [],
events: {},
methods: {},
accessors: {},
lifecycle: {},
attributes: {},
'prototype': {
xtag: {
get: function(){
return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} });
}
}
}
},
register: function (name, options) {
var _name;
if (typeof name == 'string') _name = name.toLowerCase();
else throw 'First argument must be a Custom Element string name';
xtag.tags[_name] = options || {};
var basePrototype = options.prototype;
delete options.prototype;
var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options));
var proto = tag.prototype;
var lifecycle = tag.lifecycle;
for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]);
for (z in lifecycle) lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, lifecycle[z], tag.pseudos, lifecycle[z]);
for (z in tag.methods) proto[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true };
for (z in tag.accessors) parseAccessor(tag, z);
if (tag.shadow) tag.shadow = tag.shadow.nodeName ? tag.shadow : xtag.createFragment(tag.shadow);
if (tag.content) tag.content = tag.content.nodeName ? tag.content.innerHTML : parseMultiline(tag.content);
var created = lifecycle.created;
var finalized = lifecycle.finalized;
proto.createdCallback = {
enumerable: true,
value: function(){
var element = this;
if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true));
if (tag.content) this.appendChild(document.createElement('div')).outerHTML = tag.content;
var output = created ? created.apply(this, arguments) : null;
xtag.addEvents(this, tag.events);
for (var name in tag.attributes) {
var attr = tag.attributes[name],
hasAttr = this.hasAttribute(name),
hasDefault = attr.def !== undefined;
if (hasAttr || attr.boolean || hasDefault) {
this[attr.key] = attr.boolean ? hasAttr : !hasAttr && hasDefault ? attr.def : this.getAttribute(name);
}
}
tag.pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
this.xtagComponentReady = true;
if (finalized) finalized.apply(this, arguments);
return output;
}
};
var inserted = lifecycle.inserted;
var removed = lifecycle.removed;
if (inserted || removed) {
proto.attachedCallback = { value: function(){
if (removed) this.xtag.__parentNode__ = this.parentNode;
if (inserted) return inserted.apply(this, arguments);
}, enumerable: true };
}
if (removed) {
proto.detachedCallback = { value: function(){
var args = toArray(arguments);
args.unshift(this.xtag.__parentNode__);
var output = removed.apply(this, args);
delete this.xtag.__parentNode__;
return output;
}, enumerable: true };
}
if (lifecycle.attributeChanged) proto.attributeChangedCallback = { value: lifecycle.attributeChanged, enumerable: true };
proto.setAttribute = {
writable: true,
enumerable: true,
value: function (name, value){
var old;
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
if (attr) {
old = this.getAttribute(_name);
value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value;
}
modAttr(this, attr, _name, value, 'setAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? true : value, old);
syncAttr(this, attr, _name, value, 'setAttribute');
}
}
};
proto.removeAttribute = {
writable: true,
enumerable: true,
value: function (name){
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
var old = this.hasAttribute(_name);
modAttr(this, attr, _name, '', 'removeAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined, old);
syncAttr(this, attr, _name, '', 'removeAttribute');
}
}
};
var definition = {};
var instance = basePrototype instanceof win.HTMLElement;
var extended = tag['extends'] && (definition['extends'] = tag['extends']);
if (basePrototype) Object.getOwnPropertyNames(basePrototype).forEach(function(z){
var prop = proto[z];
var desc = instance ? Object.getOwnPropertyDescriptor(basePrototype, z) : basePrototype[z];
if (prop) {
for (var y in desc) {
if (typeof desc[y] == 'function' && prop[y]) prop[y] = xtag.wrap(desc[y], prop[y]);
else prop[y] = desc[y];
}
}
proto[z] = prop || desc;
});
definition['prototype'] = Object.create(
extended ? Object.create(doc.createElement(extended).constructor).prototype : win.HTMLElement.prototype,
proto
);
return doc.registerElement(_name, definition);
},
/* Exposed Variables */
mixins: {},
prefix: prefix,
captureEvents: { focus: 1, blur: 1, scroll: 1, DOMMouseScroll: 1 },
customEvents: {
animationstart: {
attach: [prefix.dom + 'AnimationStart']
},
animationend: {
attach: [prefix.dom + 'AnimationEnd']
},
transitionend: {
attach: [prefix.dom + 'TransitionEnd']
},
move: {
attach: ['pointermove']
},
enter: {
attach: ['pointerenter']
},
leave: {
attach: ['pointerleave']
},
scrollwheel: {
attach: ['DOMMouseScroll', 'mousewheel'],
condition: function(event){
event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1);
return true;
}
},
tap: {
attach: ['pointerdown', 'pointerup'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
custom.startX = event.clientX;
custom.startY = event.clientY;
}
else if (event.button === 0 &&
Math.abs(custom.startX - event.clientX) < 10 &&
Math.abs(custom.startY - event.clientY) < 10) return true;
}
},
tapstart: {
attach: ['pointerdown'],
condition: touchFilter
},
tapend: {
attach: ['pointerup'],
condition: touchFilter
},
tapmove: {
attach: ['pointerdown'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
var listener = custom.listener.bind(this);
if (!custom.tapmoveListeners) custom.tapmoveListeners = xtag.addEvents(document, {
pointermove: listener,
pointerup: listener,
pointercancel: listener
});
}
else if (event.type == 'pointerup' || event.type == 'pointercancel') {
xtag.removeEvents(document, custom.tapmoveListeners);
custom.tapmoveListeners = null;
}
return true;
}
},
taphold: {
attach: ['pointerdown', 'pointerup'],
condition: function(event, custom){
if (event.type == 'pointerdown') {
(custom.pointers = custom.pointers || {})[event.pointerId] = setTimeout(
xtag.fireEvent.bind(null, this, 'taphold'),
custom.duration || 1000
);
}
else if (event.type == 'pointerup') {
if (custom.pointers) {
clearTimeout(custom.pointers[event.pointerId]);
delete custom.pointers[event.pointerId];
}
}
else return true;
}
}
},
pseudos: {
__mixin__: {},
mixins: {
onCompiled: function(fn, pseudo){
var mixin = pseudo.source && pseudo.source.__mixin__ || pseudo.source;
if (mixin) switch (pseudo.value) {
case null: case '': case 'before': return function(){
mixin.apply(this, arguments);
return fn.apply(this, arguments);
};
case 'after': return function(){
var returns = fn.apply(this, arguments);
mixin.apply(this, arguments);
return returns;
};
case 'none': return fn;
}
else return fn;
}
},
keypass: keypseudo,
keyfail: keypseudo,
delegate: {
action: delegateAction
},
preventable: {
action: function (pseudo, event) {
return !event.defaultPrevented;
}
},
duration: {
onAdd: function(pseudo){
pseudo.source.duration = Number(pseudo.value);
}
},
capture: {
onCompiled: function(fn, pseudo){
if (pseudo.source) pseudo.source.capture = true;
}
}
},
/* UTILITIES */
clone: clone,
typeOf: typeOf,
toArray: toArray,
wrap: function (original, fn) {
return function(){
var output = original.apply(this, arguments);
fn.apply(this, arguments);
return output;
};
},
/*
Recursively merges one object with another. The first argument is the destination object,
all other objects passed in as arguments are merged from right to left, conflicts are overwritten
*/
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
/*
----- This should be simplified! -----
Generates a random ID string
*/
uid: function(){
return Math.random().toString(36).substr(2,10);
},
/* DOM */
query: query,
skipTransition: function(element, fn, bind){
var prop = prefix.js + 'TransitionProperty';
element.style[prop] = element.style.transitionProperty = 'none';
var callback = fn ? fn.call(bind || element) : null;
return xtag.skipFrame(function(){
element.style[prop] = element.style.transitionProperty = '';
if (callback) callback.call(bind || element);
});
},
requestFrame: (function(){
var raf = win.requestAnimationFrame ||
win[prefix.lowercase + 'RequestAnimationFrame'] ||
function(fn){ return win.setTimeout(fn, 20); };
return function(fn){ return raf(fn); };
})(),
cancelFrame: (function(){
var cancel = win.cancelAnimationFrame ||
win[prefix.lowercase + 'CancelAnimationFrame'] ||
win.clearTimeout;
return function(id){ return cancel(id); };
})(),
skipFrame: function(fn){
var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); });
return id;
},
matchSelector: function (element, selector) {
return matchSelector.call(element, selector);
},
set: function (element, method, value) {
element[method] = value;
if (window.CustomElements) CustomElements.upgradeAll(element);
},
innerHTML: function(el, html){
xtag.set(el, 'innerHTML', html);
},
hasClass: function (element, klass) {
return element.className.split(' ').indexOf(klass.trim())>-1;
},
addClass: function (element, klass) {
var list = element.className.trim().split(' ');
klass.trim().split(' ').forEach(function (name) {
if (!~list.indexOf(name)) list.push(name);
});
element.className = list.join(' ').trim();
return element;
},
removeClass: function (element, klass) {
var classes = klass.trim().split(' ');
element.className = element.className.trim().split(' ').filter(function (name) {
return name && !~classes.indexOf(name);
}).join(' ');
return element;
},
toggleClass: function (element, klass) {
return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass);
},
/*
Runs a query on only the children of an element
*/
queryChildren: function (element, selector) {
var id = element.id,
attr = '#' + (element.id = id || 'x_' + xtag.uid()) + ' > ',
parent = element.parentNode || !container.appendChild(element);
selector = attr + (selector + '').replace(regexReplaceCommas, ',' + attr);
var result = element.parentNode.querySelectorAll(selector);
if (!id) element.removeAttribute('id');
if (!parent) container.removeChild(element);
return toArray(result);
},
/*
Creates a document fragment with the content passed in - content can be
a string of HTML, an element, or an array/collection of elements
*/
createFragment: function(content) {
var template = document.createElement('template');
if (content) {
if (content.nodeName) toArray(arguments).forEach(function(e){
template.content.appendChild(e);
});
else template.innerHTML = parseMultiline(content);
}
return document.importNode(template.content, true);
},
/*
Removes an element from the DOM for more performant node manipulation. The element
is placed back into the DOM at the place it was taken from.
*/
manipulate: function(element, fn){
var next = element.nextSibling,
parent = element.parentNode,
returned = fn.call(element) || element;
if (next) parent.insertBefore(returned, next);
else parent.appendChild(returned);
},
/* PSEUDOS */
applyPseudos: function(key, fn, target, source) {
var listener = fn,
pseudos = {};
if (key.match(':')) {
var matches = [],
valueFlag = 0;
key.replace(regexPseudoParens, function(match){
if (match == '(') return ++valueFlag == 1 ? '\u276A' : '(';
return !--valueFlag ? '\u276B' : ')';
}).replace(regexPseudoCapture, function(z, name, value, solo){
matches.push([name || solo, value]);
});
var i = matches.length;
while (i--) parsePseudo(function(){
var name = matches[i][0],
value = matches[i][1];
if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value;
value = (value === '' || typeof value == 'undefined') ? null : value;
var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]);
pseudo.key = key;
pseudo.name = name;
pseudo.value = value;
pseudo['arguments'] = (value || '').split(',');
pseudo.action = pseudo.action || trueop;
pseudo.source = source;
pseudo.onAdd = pseudo.onAdd || noop;
pseudo.onRemove = pseudo.onRemove || noop;
var original = pseudo.listener = listener;
listener = function(){
var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments)));
if (output === null || output === false) return output;
output = pseudo.listener.apply(this, arguments);
pseudo.listener = original;
return output;
};
if (!target) pseudo.onAdd.call(fn, pseudo);
else target.push(pseudo);
});
}
for (var z in pseudos) {
if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener;
}
return listener;
},
removePseudos: function(target, pseudos){
pseudos.forEach(function(obj){
obj.onRemove.call(target, obj);
});
},
/*** Events ***/
parseEvent: function(type, fn) {
var pseudos = type.split(':'),
key = pseudos.shift(),
custom = xtag.customEvents[key],
event = xtag.merge({
type: key,
stack: noop,
condition: trueop,
capture: xtag.captureEvents[key],
attach: [],
_attach: [],
pseudos: '',
_pseudos: [],
onAdd: noop,
onRemove: noop
}, custom || {});
event.attach = toArray(event.base || event.attach);
event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : '');
var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event);
event.stack = function(e){
e.currentTarget = e.currentTarget || this;
var detail = e.detail || {};
if (!detail.__stack__) return stack.apply(this, arguments);
else if (detail.__stack__ == stack) {
e.stopPropagation();
e.cancelBubble = true;
return stack.apply(this, arguments);
}
};
event.listener = function(e){
var args = toArray(arguments),
output = event.condition.apply(this, args.concat([event]));
if (!output) return output;
// The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537
// Remove this when affected browser builds with this regression fall below 5% marketshare
if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) {
xtag.fireEvent(e.target, key, {
baseEvent: e,
detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack }
});
}
else return event.stack.apply(this, args);
};
event.attach.forEach(function(name) {
event._attach.push(xtag.parseEvent(name, event.listener));
});
return event;
},
addEvent: function (element, type, fn, capture) {
var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn;
event._pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
event._attach.forEach(function(obj) {
xtag.addEvent(element, obj.type, obj);
});
event.onAdd.call(element, event, event.listener);
element.addEventListener(event.type, event.stack, capture || event.capture);
return event;
},
addEvents: function (element, obj) {
var events = {};
for (var z in obj) {
events[z] = xtag.addEvent(element, z, obj[z]);
}
return events;
},
removeEvent: function (element, type, event) {
event = event || type;
event.onRemove.call(element, event, event.listener);
xtag.removePseudos(element, event._pseudos);
event._attach.forEach(function(obj) {
xtag.removeEvent(element, obj);
});
element.removeEventListener(event.type, event.stack);
},
removeEvents: function(element, obj){
for (var z in obj) xtag.removeEvent(element, obj[z]);
},
fireEvent: function(element, type, options){
var event = doc.createEvent('CustomEvent');
options = options || {};
event.initCustomEvent(type,
options.bubbles !== false,
options.cancelable !== false,
options.detail
);
if (options.baseEvent) inheritEvent(event, options.baseEvent);
element.dispatchEvent(event);
}
};
if (typeof define === 'function' && define.amd) define(xtag);
else if (typeof module !== 'undefined' && module.exports) module.exports = xtag;
else win.xtag = xtag;
doc.addEventListener('WebComponentsReady', function(){
xtag.fireEvent(doc.body, 'DOMComponentsLoaded');
});
})();
|
/**
* version: 1.1.3
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig').directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope, element, attrs) {
scope.originalHeight = element.outerHeight();
scope.editMode = false;
scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off';
scope.cssPath = scope.cssPath ? scope.cssPath : 'css/ng-wig.css';
scope.toggleEditMode = function() {
scope.editMode = !scope.editMode;
};
scope.execCommand = function (command, options) {
if(command ==='createlink'){
options = prompt('Please enter the URL', 'http://');
}
scope.$emit('execCommand', {command: command, options: options});
};
}
}
}
);
angular.module('ngWig').directive('ngWigEditable', function () {
function init(scope, $element, attrs, ctrl) {
var document = $element[0].ownerDocument;
$element.attr('contenteditable', true);
//model --> view
ctrl.$render = function () {
$element.html(ctrl.$viewValue || '');
};
//view --> model
function viewToModel() {
ctrl.$setViewValue($element.html());
}
$element.bind('blur keyup change paste', viewToModel);
scope.$on('execCommand', function (event, params) {
$element[0].focus();
var ieStyleTextSelection = document.selection,
command = params.command,
options = params.options;
if (ieStyleTextSelection) {
var textRange = ieStyleTextSelection.createRange();
}
document.execCommand(command, false, options);
if (ieStyleTextSelection) {
textRange.collapse(false);
textRange.select();
}
viewToModel();
});
}
return {
restrict: 'A',
require: 'ngModel',
replace: true,
link: init
}
}
);
/**
* No box-sizing, such a shame
*
* 1.Calculate outer height
* @param bool Include margin
* @returns Number Height in pixels
*
* 2. Set outer height
* @param Number Height in pixels
* @param bool Include margin
* @returns angular.element Collection
*/
if (typeof angular.element.prototype.outerHeight !== 'function') {
angular.element.prototype.outerHeight = function() {
function parsePixels(cssString) {
if (cssString.slice(-2) === 'px') {
return parseFloat(cssString.slice(0, -2));
}
return 0;
}
var includeMargin = false, height, $element = this.eq(0), element = $element[0];
if (arguments[0] === true || arguments[0] === false || arguments[0] === undefined) {
if (!$element.length) {
return 0;
}
includeMargin = arguments[0] && true || false;
if (element.outerHeight) {
height = element.outerHeight;
} else {
height = element.offsetHeight;
}
if (includeMargin) {
height += parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom'));
}
return height;
} else {
if (!$element.length) {
return this;
}
height = parseFloat(arguments[0]);
includeMargin = arguments[1] && true || false;
if (includeMargin) {
height -= parsePixels($element.css('marginTop')) + parsePixels($element.css('marginBottom'));
}
height -= parsePixels($element.css('borderTopWidth')) + parsePixels($element.css('borderBottomWidth')) +
parsePixels($element.css('paddingTop')) + parsePixels($element.css('paddingBottom'));
$element.css('height', height + 'px');
return this;
}
};
}
angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']);
angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("ng-wig/views/ng-wig.html",
"<div class=\"ng-wig\">\n" +
" <ul class=\"nw-toolbar\">\n" +
" <li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--header-one\" title=\"Header\" ng-click=\"execCommand('formatblock', '<h1>')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--paragraph\" title=\"Paragraph\" ng-click=\"execCommand('formatblock', '<p>')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" +
" </li>\n" +
" </ul>\n" +
"\n" +
" <div class=\"nw-editor-container\">\n" +
" <div class=\"nw-editor\">\n" +
" <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" +
" <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.1.5
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("./context/context");
var rowNode_1 = require("./entities/rowNode");
var renderedRow_1 = require("./rendering/renderedRow");
var utils_1 = require('./utils');
var SelectionRendererFactory = (function () {
function SelectionRendererFactory() {
}
SelectionRendererFactory.prototype.createSelectionCheckbox = function (rowNode, addRenderedRowEventListener) {
var eCheckbox = document.createElement('input');
eCheckbox.type = "checkbox";
eCheckbox.name = "name";
eCheckbox.className = 'ag-selection-checkbox';
utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected());
eCheckbox.addEventListener('click', function (event) { return event.stopPropagation(); });
eCheckbox.addEventListener('change', function () {
var newValue = eCheckbox.checked;
if (newValue) {
rowNode.setSelected(newValue);
}
else {
rowNode.setSelected(newValue);
}
});
var selectionChangedCallback = function () { return utils_1.Utils.setCheckboxState(eCheckbox, rowNode.isSelected()); };
rowNode.addEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback);
addRenderedRowEventListener(renderedRow_1.RenderedRow.EVENT_RENDERED_ROW_REMOVED, function () {
rowNode.removeEventListener(rowNode_1.RowNode.EVENT_ROW_SELECTED, selectionChangedCallback);
});
return eCheckbox;
};
SelectionRendererFactory = __decorate([
context_1.Bean('selectionRendererFactory'),
__metadata('design:paramtypes', [])
], SelectionRendererFactory);
return SelectionRendererFactory;
})();
exports.SelectionRendererFactory = SelectionRendererFactory;
|
/* Spellbook Class Extension */
if (!Array.prototype.remove) {
Array.prototype.remove = function (obj) {
var self = this;
if (typeof obj !== "object" && !obj instanceof Array) {
obj = [obj];
}
return self.filter(function(e){
if(obj.indexOf(e)<0) {
return e
}
});
};
}
if (!Array.prototype.clear) {
Array.prototype.clear = function() {
this.splice(0, this.length);
};
}
if (!Array.prototype.random) {
Array.prototype.random = function() {
self = this;
var index = Math.floor(Math.random() * (this.length));
return self[index];
};
}
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
}
if (!Array.prototype.first) {
Array.prototype.first = function() {
return this[0];
}
}
if (!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
if (!Array.prototype.inArray) {
Array.prototype.inArray = function (value) {
return !!~this.indexOf(value);
};
}
if (!Array.prototype.contains) {
Array.prototype.contains = function (value) {
return !!~this.indexOf(value);
};
}
if (!Array.prototype.each) {
Array.prototype.each = function (interval, callback, response) {
var self = this;
var i = 0;
if (typeof interval !== "function" ) {
var inter = setInterval(function () {
callback(self[i], i);
i++;
if (i === self.length) {
clearInterval(inter);
if (typeof response === "function") response();
}
}, interval);
} else {
for (var i = 0; i < self.length; i++) {
interval(self[i], i);
if (typeof callback === "function") {
if (i === self.length - 1) callback();
}
}
}
}
}
if (!Array.prototype.eachEnd) {
Array.prototype.eachEnd = function (callback, response) {
var self = this;
var i = 0;
var done = function () {
if (i < self.length -1) {
i++;
callback(self[i], i, done);
} else {
if (typeof response === 'function') {
response();
}
}
}
callback(self[i], i, done);
}
}
if (!Object.prototype.extend) {
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
};
};
};
}
if (!Object.prototype.remove) {
Object.prototype.remove = function(keys) {
var self = this;
if (typeof obj === "object" && obj instanceof Array) {
arr.forEach(function(key){
delete(self[key]);
});
} else {
delete(self[keys]);
};
};
}
if (!Object.prototype.getKeys) {
Object.prototype.getKeys = function(keys) {
var self = this;
if (typeof obj === "object" && obj instanceof Array) {
var obj = {};
keys.forEach(function(key){
obj[key] = self[key];
});
} else {
obj[keys] = self[keys];
}
return obj;
};
}
if (!String.prototype.repeatify) {
String.prototype.repeatify = function(num) {
var strArray = [];
for (var i = 0; i < num; i++) {
strArray.push(this.normalize());
}
return strArray;
};
}
if (!Number.prototype.times) {
Number.prototype.times = function (callback) {
if (this % 1 === 0)
for (var i = 0; i < this; i++) {
callback()
}
};
}
if (!Number.prototype.isInteger) {
Number.prototype.isInteger = function () {
this.isInteger = function (num) {
return num % 1 === 0;
}
}
}
if (!Array.prototype.isArray) {
this.isArray = function () {
return typeof this === "object" && this instanceof Array;
};
}
if (!Function.prototype.isFunction) {
this.isFunction = function () {
return typeof this === 'function';
};
}
if (!Object.prototype.isObject) {
this.isObject = function () {
return typeof this === "object" && (isArray(this) === false );
};
}
if (!String.prototype.isString) {
this.isString = function () {
return typeof this === "string" || this instanceof String;
};
}
if (!Boolean.prototype.isBoolean) {
this.isBoolean = function () {
return typeof this === "boolean";
};
}
/* Spellbook Utils */
var Spellbook = function () {
this.test = function () {
return "Testing Spellbook";
};
this.range = function(a, b, step) {
var A= [];
if(typeof a == 'number'){
A[0]= a;
step = step || 1;
while(a+step<= b) {
A[A.length]= a+= step;
}
} else {
var s = 'abcdefghijklmnopqrstuvwxyz';
if(a=== a.toUpperCase()) {
b=b.toUpperCase();
s= s.toUpperCase();
}
s= s.substring(s.indexOf(a), s.indexOf(b)+ 1);
A= s.split('');
}
return A;
};
this.isFunction = function (fn) {
return typeof fn === 'function';
};
this.isArray = function (obj) {
return typeof obj === "object" && obj instanceof Array;
};
this.isObject = function (obj) {
return typeof obj === "object" && (isArray(obj) === false );
};
this.isNumber = function (obj) {
return typeof obj === "number" || obj instanceof Number;
};
this.isString = function (obj ) {
return typeof obj === "string" || obj instanceof String;
};
this.isBoolean = function (obj) {
return typeof obj === "boolean";
};
this.isInteger = function (obj) {
return obj % 1 === 0;
}
this.random = function (min, max) {
if (typeof min === "number" && typeof max === "number") {
return Math.floor(Math.random() * (max - min)) + min;
} else {
return 0;
}
};
this.clone = function (obj) {
if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
return obj;
var temp = obj.constructor();
for(var key in obj) {
if(Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null;
temp[key] = clone(obj[key]);
delete obj['isActiveClone'];
}
}
return temp;
};
this.assign = function (obj) {
return this.clone(obj);
};
this.remove = function (array, obj) {
if (typeof obj !== "object" && !obj instanceof Array) {
obj = [obj];
}
return array.filter(function(e){
if(obj.indexOf(e)<0) {
return e
}
});
};
this.clear = function (array) {
array.splice(0, array.length);
};
this.inArray = function (a, b) {
return !!~a.indexOf(b);
};
this.contains = function (a, b) {
return !!~a.indexOf(b);
};
this.times = function (number, callback) {
if (typeof number === 'number' && number > 0) {
if ( typeof callback === 'function') {
for (var i = 0; i < number; i++) {
callback();
}
}
}
};
this.each = function (array, interval, callback, response) {
var i = 0;
if (typeof interval !== "function" ) {
var inter = setInterval(function () {
callback(array[i], i);
i++;
if (i === array.length) {
clearInterval(inter);
if (typeof response === "function") response();
}
}, interval);
} else {
for (var i = 0; i < array.length; i++) {
interval(array[i], i);
if (typeof callback === "function") {
if (i === array.length - 1) callback();
}
}
}
}
this.eachEnd = function (array, callback, response) {
var i = 0;
var done = function () {
if (i < array.length -1) {
i++;
callback(array[i], i, done);
} else {
if (typeof response === 'function') {
response();
}
}
}
callback(array[i], i, done);
}
this.checkDate = function (value, userFormat) {
userFormat = userFormat || 'mm/dd/yyyy';
var delimiter = /[^mdy]/.exec(userFormat)[0];
var theFormat = userFormat.split(delimiter);
var theDate = value.split(delimiter);
function isDate(date, format) {
var m, d, y, i = 0, len = format.length, f;
for (i; i < len; i++) {
f = format[i];
if (/m/.test(f)) m = date[i];
if (/d/.test(f)) d = date[i];
if (/y/.test(f)) y = date[i];
}
return (
m > 0 && m < 13 &&
y && y.length === 4 &&
d > 0 &&
d <= (new Date(y, m, 0)).getDate()
);
};
return isDate(theDate, theFormat);
};
this.excerpt = function (str, nwords) {
var words = str.split(' ');
words.splice(nwords, words.length-1);
return words.join(' ');
}
};
if (typeof process === 'object') {
module.exports = new Spellbook;
} else {
Spellbook.prototype.get = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI(url));
xhr.onload = function() {
if (xhr.status === 200) {
callback(false, xhr.responseText);
} else {
callback("Request failed. Returned status of " + status);
}
};
xhr.send();
}
Spellbook.prototype.post = function (url, data, header, callback) {
function param(object) {
var encodedString = '';
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (encodedString.length > 0) {
encodedString += '&';
}
encodedString += encodeURI(prop + '=' + object[prop]);
}
}
return encodedString;
}
if (typeof header === "function") {
callback = header;
header = "application/json";
var finaldata = JSON.stringify(data);
} else {
var finaldata = param(data);
}
xhr = new XMLHttpRequest();
xhr.open('POST', encodeURI(url));
xhr.setRequestHeader('Content-Type', header);
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== undefined) {
callback(null, xhr.responseText);
} else if (xhr.status !== 200) {
callback('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(finaldata);
}
var sb = new Spellbook();
}
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var AsyncAction_1 = require('./AsyncAction');
var AsyncScheduler_1 = require('./AsyncScheduler');
var VirtualTimeScheduler = (function (_super) {
__extends(VirtualTimeScheduler, _super);
function VirtualTimeScheduler(SchedulerAction, maxFrames) {
var _this = this;
if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
_super.call(this, SchedulerAction, function () { return _this.frame; });
this.maxFrames = maxFrames;
this.frame = 0;
this.index = -1;
}
/**
* Prompt the Scheduler to execute all of its queued actions, therefore
* clearing its queue.
* @return {void}
*/
VirtualTimeScheduler.prototype.flush = function () {
var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
var error, action;
while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
if (error = action.execute(action.state, action.delay)) {
break;
}
}
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
};
VirtualTimeScheduler.frameTimeFactor = 10;
return VirtualTimeScheduler;
}(AsyncScheduler_1.AsyncScheduler));
exports.VirtualTimeScheduler = VirtualTimeScheduler;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var VirtualAction = (function (_super) {
__extends(VirtualAction, _super);
function VirtualAction(scheduler, work, index) {
if (index === void 0) { index = scheduler.index += 1; }
_super.call(this, scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.index = index;
this.index = scheduler.index = index;
}
VirtualAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (!this.id) {
return _super.prototype.schedule.call(this, state, delay);
}
// If an action is rescheduled, we save allocations by mutating its state,
// pushing it to the end of the scheduler queue, and recycling the action.
// But since the VirtualTimeScheduler is used for testing, VirtualActions
// must be immutable so they can be inspected later.
var action = new VirtualAction(this.scheduler, this.work);
this.add(action);
return action.schedule(state, delay);
};
VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
this.delay = scheduler.frame + delay;
var actions = scheduler.actions;
actions.push(this);
actions.sort(VirtualAction.sortActions);
return true;
};
VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
return undefined;
};
VirtualAction.sortActions = function (a, b) {
if (a.delay === b.delay) {
if (a.index === b.index) {
return 0;
}
else if (a.index > b.index) {
return 1;
}
else {
return -1;
}
}
else if (a.delay > b.delay) {
return 1;
}
else {
return -1;
}
};
return VirtualAction;
}(AsyncAction_1.AsyncAction));
exports.VirtualAction = VirtualAction;
//# sourceMappingURL=VirtualTimeScheduler.js.map |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":4,"../lib/Shim.IE8":27}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = pathSolver.parseArr(this._index, {
verbose: true
});
queryArr = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":23,"./Shared":26}],3:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatch[joinMatchIndex].query;
joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]);
}
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":26}],4:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":6,"./Metrics.js":10,"./Overload":22,"./Shared":26}],5:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":10,"./Overload":22,"./Shared":26}],7:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":23,"./Shared":26}],8:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":23,"./Shared":26}],9:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":26}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":21,"./Shared":26}],11:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],12:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],13:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":22,"./Serialiser":25}],14:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":22}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check we have a database object to work from
if (!this.db()) {
throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!');
}
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":22}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":23,"./Shared":26}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
Path.prototype.valueOne = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.valueOne(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":26}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":26}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.505',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Tags":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],27:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
import css from './source.css';
__export__ = css;
export default css;
|
/*!
* Platform.js <http://mths.be/platform>
* Copyright 2010-2012 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window) {
/** Backup possible window/global object */
var oldWin = window,
/** Possible global object */
thisBinding = this,
/** Detect free variable `exports` */
freeExports = typeof exports == 'object' && exports,
/** Detect free variable `global` */
freeGlobal = typeof global == 'object' && global && (global == global.global ? (window = global) : global),
/** Used to check for own properties of an object */
hasOwnProperty = {}.hasOwnProperty,
/** Used to resolve a value's internal [[Class]] */
toString = {}.toString,
/** Detect Java environment */
java = /Java/.test(getClassOf(window.java)) && window.java,
/** A character to represent alpha */
alpha = java ? 'a' : '\u03b1',
/** A character to represent beta */
beta = java ? 'b' : '\u03b2',
/** Browser document object */
doc = window.document || {},
/** Browser navigator object */
nav = window.navigator || {},
/** Previous platform object */
old = window.platform,
/** Browser user agent string */
userAgent = nav.userAgent || '',
/**
* Detect Opera browser
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
opera = window.operamini || window.opera,
/** Opera regexp */
reOpera = /Opera/,
/** Opera [[Class]] */
operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null);
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
* @private
* @param {String} string The string to capitalize.
* @returns {String} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* An iteration utility for arrays and objects.
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object.length;
if (length == length >>> 0) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
hasKey(object, key) && callback(object[key], key, object);
}
}
/**
* Trim and conditionally capitalize string values.
* @private
* @param {String} string The string to format.
* @returns {String} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
}
/**
* Gets the internal [[Class]] of a value.
* @private
* @param {Mixed} value The value.
* @returns {String} The [[Class]].
*/
function getClassOf(value) {
return value == null
? capitalize(value)
: toString.call(value).slice(8, -1);
}
/**
* Checks if an object has the specified key as a direct property.
* @private
* @param {Object} object The object to check.
* @param {String} key The key to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
*/
function hasKey() {
// lazy define for others (not as accurate)
hasKey = function(object, key) {
var parent = object != null && (object.constructor || Object).prototype;
return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
};
// for modern browsers
if (getClassOf(hasOwnProperty) == 'Function') {
hasKey = function(object, key) {
return object != null && hasOwnProperty.call(object, key);
};
}
// for Safari 2
else if ({}.__proto__ == Object.prototype) {
hasKey = function(object, key) {
var result = false;
if (object != null) {
object = Object(object);
object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
}
return result;
};
}
return hasKey.apply(this, arguments);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of object, function, or unknown.
* @private
* @param {Mixed} object The owner of the property.
* @param {String} property The property to check.
* @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* A bare-bones` Array#reduce` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} accumulator Initial value of the accumulator.
* @returns {Mixed} The accumulator.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function(value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Prepares a string for use in a RegExp constructor by making hyphens and spaces optional.
* @private
* @param {String} string The string to qualify.
* @returns {String} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* Removes leading and trailing whitespace from a string.
* @private
* @param {String} string The string to trim.
* @returns {String} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
* @memberOf platform
* @param {String} [ua = navigator.userAgent] The user agent string.
* @returns {Object} A platform object.
*/
function parse(ua) {
ua || (ua = userAgent);
/** Temporary variable used over the script's lifetime */
var data,
/** The CPU architecture */
arch = ua,
/** Platform description array */
description = [],
/** Platform alpha/beta indicator */
prerelease = null,
/** A flag to indicate that environment features should be used to resolve the platform */
useFeatures = ua == userAgent,
/** The browser/environment version */
version = useFeatures && opera && typeof opera.version == 'function' && opera.version(),
/* Detectable layout engines (order is important) */
layout = getLayout([
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
'NetFront',
'Tasman',
'Trident',
'KHTML',
'Gecko'
]),
/* Detectable browser names (order is important) */
name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
'Camino',
'Epiphany',
'Fennec',
'Flock',
'Galeon',
'GreenBrowser',
'iCab',
'Iceweasel',
'Iron',
'K-Meleon',
'Konqueror',
'Lunascape',
'Maxthon',
'Midori',
'Nook Browser',
'PhantomJS',
'Raven',
'Rekonq',
'RockMelt',
'SeaMonkey',
{ 'label': 'Silk', 'pattern': '(?:Cloud9|Silk)' },
'Sleipnir',
'SlimBrowser',
'Sunrise',
'Swiftfox',
'WebPositive',
'Opera Mini',
'Opera',
'Chrome',
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]),
/* Detectable products (order is important) */
product = getProduct([
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
'iPad',
'iPod',
'iPhone',
'Kindle',
{ 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk)' },
'Nook',
'PlayBook',
'TouchPad',
'Transformer',
'Xoom'
]),
/* Detectable manufacturers */
manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
'Barnes & Noble': { 'Nook': 1 },
'BlackBerry': { 'PlayBook': 1 },
'HP': { 'TouchPad': 1 },
'LG': { },
'Motorola': { 'Xoom': 1 },
'Nokia': { },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }
}),
/* Detectable OSes (order is important) */
os = getOS([
'Android',
'CentOS',
'Debian',
'Fedora',
'FreeBSD',
'Gentoo',
'Haiku',
'Kubuntu',
'Linux Mint',
'Red Hat',
'SuSE',
'Ubuntu',
'Xubuntu',
'Cygwin',
'Symbian OS',
'hpwOS',
'webOS ',
'webOS',
'Tablet OS',
'Linux',
'Mac OS X',
'Macintosh',
'Mac',
'Windows 98;',
'Windows '
]);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// lookup the manufacturer by product or scan the UA for the manufacturer
return result || (
value[product] ||
value[0/*Opera 9.25 fix*/, /^[a-z]+/i.exec(product)] ||
RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && (key.label || key);
});
}
/**
* Picks the browser name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) {
// platform tokens defined at
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
data = {
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// detect Windows version from platform tokens
if (/^Win/i.test(result) &&
(data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) {
result = 'Windows ' + data;
}
// correct character case and cleanup
result = format(String(result)
.replace(RegExp(pattern, 'i'), guess.label || guess)
.replace(/ ce$/i, ' CE')
.replace(/hpw/i, 'web')
.replace(/Macintosh/, 'Mac OS')
.replace(/_PowerPC/i, ' OS')
.replace(/(OS X) [^ \d]+/i, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/x86\.64/gi, 'x86_64')
.split(' on ')[0]);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// split by forward slash and append product version if needed
if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// correct character case and cleanup
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {String|Null} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/*------------------------------------------------------------------------*/
/**
* Restores a previously overwritten platform object.
* @memberOf platform
* @type Function
* @returns {Object} The current platform object.
*/
function noConflict() {
window['platform'] = old;
return this;
}
/**
* Return platform description when the platform object is coerced to a string.
* @name toString
* @memberOf platform
* @type Function
* @returns {String} The platform description.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// convert layout to an array so we can add extra details
layout && (layout = [layout]);
// detect product names that contain their manufacturer's name
if (manufacturer && !product) {
product = getProduct([manufacturer]);
}
// detect simulators
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
}
// detect iOS
if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua))
? ' ' + data[1].replace(/_/g, '.')
: '');
}
// detect Kubuntu
else if (name == 'Konqueror' && !/buntu/i.test(os)) {
os = 'Kubuntu';
}
// detect Android browsers
else if (name == 'Chrome' && manufacturer) {
name = 'Android Browser';
os = /Android/.test(os) ? os : 'Android';
}
// detect false positives for Firefox/Safari
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) {
// escape the `/` for Firefox 1
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// clear name of false positives
name = null;
}
// reassign a generic name
if ((data = product || manufacturer || os) &&
(product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser';
}
}
// detect non-Opera versions (order is important)
if (!version) {
version = getVersion([
'(?:Cloud9|Opera ?Mini|Raven|Silk)',
'Version',
qualify(name),
'(?:Firefox|Minefield|NetFront)'
]);
}
// detect stubborn layout engines
if (layout == 'iCab' && parseFloat(version) > 3) {
layout = ['WebKit'];
} else if (name == 'Konqueror' && /\bKHTML\b/i.test(ua)) {
layout = ['KHTML'];
} else if (data =
/Opera/.test(name) && 'Presto' ||
/\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' ||
!layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) {
layout = [data];
}
// leverage environment features
if (useFeatures) {
// detect server-side environments
// Rhino has a global function while others have a global object
if (isHostType(thisBinding, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (typeof exports == 'object' && exports) {
// if `thisBinding` is the [ModuleScope]
if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) {
os || (os = data[0].os || null);
try {
data[1] = require('ringo/engine').version;
version = data[1].join('.');
name = 'RingoJS';
} catch(e) {
if (data[0].global == freeGlobal) {
name = 'Narwhal';
}
}
} else if (typeof process == 'object' && (data = process)) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version)[0];
}
} else if (getClassOf(window.environment) == 'Environment') {
name = 'Rhino';
}
}
// detect Adobe AIR
else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
}
// detect PhantomJS
else if (getClassOf(data = window.phantom) == 'RuntimeObject') {
name = 'PhantomJS';
version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch);
}
// detect IE compatibility modes
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// we're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout[1] = '';
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
}
os = os && format(os);
}
// detect prerelease phases
if (version && (data =
/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) ||
/(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) ||
/\bMinefield\b/i.test(ua) && 'a')) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') +
(prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
}
// obscure Maxthon's unreliable version
if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
}
// detect Silk desktop/accelerated modes
else if (name == 'Silk') {
if (!/Mobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
}
// detect Windows Phone desktop mode
else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone OS ' + data + '.x';
description.unshift('desktop mode');
}
// add mobile postfix
else if ((name == 'IE' || name && !product && !/Browser/.test(name)) &&
(os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
}
// detect IE platform preview
else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) {
description.unshift('platform preview');
}
// detect BlackBerry OS version
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if (/BlackBerry/.test(product) && (data =
(RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] ||
version)) {
os = 'Device Software ' + data;
version = null;
}
// detect Opera identifying/masking itself as another browser
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && (
(useFeatures && opera) ||
(/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) ||
(name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) ||
(name == 'IE' && (
(os && !/^Win/.test(os) && version > 5.5) ||
/Windows XP/.test(os) && version > 8 ||
version == 8 && !/Trident/.test(ua)
))
) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) {
// when "indentifying" the UA contains both Opera and the other browser's name
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/IE/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
}
// when "masking" the UA contains only the other browser's name
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/IE/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
}
// detect WebKit Nightly and approximate Chrome/Safari versions
if ((data = (/AppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// nightly builds are postfixed with a `+`
data = [parseFloat(data), data];
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
}
// clear incorrect browser versions
else if (version == data[1] ||
version == (/Safari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) {
version = null;
}
// use the full Chrome version when available
data = [data[0], (/Chrome\/([\d.]+)/i.exec(ua) || 0)[1]];
// detect JavaScriptCore
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) {
layout[1] = 'like Safari';
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5');
} else {
layout[1] = 'like Chrome';
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.5 ? 3 : data < 533 ? 4 : data < 534.3 ? 5 : data < 534.7 ? 6 : data < 534.1 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.3 ? 11 : data < 535.1 ? 12 : data < 535.2 ? '13+' : data < 535.5 ? 15 : data < 535.7 ? 16 : '17');
}
// add the postfix of ".x" or "+" for approximate versions
layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+');
// obscure version for some Safari 1-2 releases
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
}
}
// strip incorrect OS versions
if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 &&
ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
}
// add layout engine
if (layout && !/Avant|Nook/.test(name) && (
/Browser|Lunascape|Maxthon/.test(name) ||
/^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) {
// don't add layout details to description if they are falsey
(data = layout[layout.length - 1]) && description.push(data);
}
// combine contextual information
if (description.length) {
description = ['(' + description.join('; ') + ')'];
}
// append manufacturer
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
}
// append product
if (product) {
description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product);
}
// add browser/OS architecture
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i).test(arch) && !/\bi686\b/i.test(arch)) {
os = os && os + (data.test(os) ? '' : ' 64-bit');
if (name && (/WOW64/i.test(ua) ||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) {
description.unshift('32-bit');
}
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
* @name platform
* @type Object
*/
return {
/**
* The browser/environment version.
* @memberOf platform
* @type String|Null
*/
'version': name && version && (description.unshift(version), version),
/**
* The name of the browser/environment.
* @memberOf platform
* @type String|Null
*/
'name': name && (description.unshift(name), name),
/**
* The name of the operating system.
* @memberOf platform
* @type String|Null
*/
'os': os && (name &&
!(os == os.split(' ')[0] && (os == name.split(' ')[0] || product)) &&
description.push(product ? '(' + os + ')' : 'on ' + os), os),
/**
* The platform description.
* @memberOf platform
* @type String|Null
*/
'description': description.length ? description.join(' ') : ua,
/**
* The name of the browser layout engine.
* @memberOf platform
* @type String|Null
*/
'layout': layout && layout[0],
/**
* The name of the product's manufacturer.
* @memberOf platform
* @type String|Null
*/
'manufacturer': manufacturer,
/**
* The alpha/beta release indicator.
* @memberOf platform
* @type String|Null
*/
'prerelease': prerelease,
/**
* The name of the product hosting the browser.
* @memberOf platform
* @type String|Null
*/
'product': product,
/**
* The browser's user agent string.
* @memberOf platform
* @type String|Null
*/
'ua': ua,
// avoid platform object conflicts in browsers
'noConflict': noConflict,
// parses a user agent string into a platform object
'parse': parse,
// returns the platform description
'toString': toStringPlatform
};
}
/*--------------------------------------------------------------------------*/
// expose platform
// in Narwhal, Node.js, or RingoJS
if (freeExports) {
forOwn(parse(), function(value, key) {
freeExports[key] = value;
});
}
// via curl.js or RequireJS
else if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
define('platform', function() {
return parse();
});
}
// in a browser or Rhino
else {
// use square bracket notation so Closure Compiler won't munge `platform`
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
window['platform'] = parse();
}
}(this)); |
'use strict';
module.exports = function (t, a) {
var x;
a.throws(function () { t(0); }, TypeError, "0");
a.throws(function () { t(false); }, TypeError, "false");
a.throws(function () { t(''); }, TypeError, "''");
a(t(x = {}), x, "Object");
a(t(x = function () {}), x, "Function");
a(t(x = new String('raz')), x, "String object"); //jslint: ignore
a(t(x = new Date()), x, "Date");
a.throws(function () { t(); }, TypeError, "Undefined");
a.throws(function () { t(null); }, TypeError, "null");
};
|
/**
* @license Highcharts JS v4.2.2 (2016-02-04)
*
* (c) 2014 Highsoft AS
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function (H) {
var seriesTypes = H.seriesTypes,
map = H.map,
merge = H.merge,
extend = H.extend,
extendClass = H.extendClass,
defaultOptions = H.getOptions(),
plotOptions = defaultOptions.plotOptions,
noop = function () {
},
each = H.each,
grep = H.grep,
pick = H.pick,
Series = H.Series,
stableSort = H.stableSort,
Color = H.Color,
eachObject = function (list, func, context) {
var key;
context = context || this;
for (key in list) {
if (list.hasOwnProperty(key)) {
func.call(context, list[key], key, list);
}
}
},
reduce = function (arr, func, previous, context) {
context = context || this;
arr = arr || []; // @note should each be able to handle empty values automatically?
each(arr, function (current, i) {
previous = func.call(context, previous, current, i, arr);
});
return previous;
},
// @todo find correct name for this function.
recursive = function (item, func, context) {
var next;
context = context || this;
next = func.call(context, item);
if (next !== false) {
recursive(next, func, context);
}
};
// Define default options
plotOptions.treemap = merge(plotOptions.scatter, {
showInLegend: false,
marker: false,
borderColor: '#E0E0E0',
borderWidth: 1,
dataLabels: {
enabled: true,
defer: false,
verticalAlign: 'middle',
formatter: function () { // #2945
return this.point.name || this.point.id;
},
inside: true
},
tooltip: {
headerFormat: '',
pointFormat: '<b>{point.name}</b>: {point.node.val}</b><br/>'
},
layoutAlgorithm: 'sliceAndDice',
layoutStartingDirection: 'vertical',
alternateStartingDirection: false,
levelIsConstant: true,
states: {
hover: {
borderColor: '#A0A0A0',
brightness: seriesTypes.heatmap ? 0 : 0.1,
shadow: false
}
},
drillUpButton: {
position: {
align: 'right',
x: -10,
y: 10
}
}
});
// Stolen from heatmap
var colorSeriesMixin = {
// mapping between SVG attributes and the corresponding options
pointAttrToOptions: {},
pointArrayMap: ['value'],
axisTypes: seriesTypes.heatmap ? ['xAxis', 'yAxis', 'colorAxis'] : ['xAxis', 'yAxis'],
optionalAxis: 'colorAxis',
getSymbol: noop,
parallelArrays: ['x', 'y', 'value', 'colorValue'],
colorKey: 'colorValue', // Point color option key
translateColors: seriesTypes.heatmap && seriesTypes.heatmap.prototype.translateColors
};
// The Treemap series type
seriesTypes.treemap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'treemap',
trackerGroups: ['group', 'dataLabelsGroup'],
pointClass: extendClass(H.Point, {
setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible
}),
/**
* Creates an object map from parent id to childrens index.
* @param {Array} data List of points set in options.
* @param {string} data[].parent Parent id of point.
* @param {Array} ids List of all point ids.
* @return {Object} Map from parent id to children index in data.
*/
getListOfParents: function (data, ids) {
var listOfParents = reduce(data, function (prev, curr, i) {
var parent = pick(curr.parent, '');
if (prev[parent] === undefined) {
prev[parent] = [];
}
prev[parent].push(i);
return prev;
}, {});
// If parent does not exist, hoist parent to root of tree.
eachObject(listOfParents, function (children, parent, list) {
if ((parent !== '') && (H.inArray(parent, ids) === -1)) {
each(children, function (child) {
list[''].push(child);
});
delete list[parent];
}
});
return listOfParents;
},
/**
* Creates a tree structured object from the series points
*/
getTree: function () {
var tree,
series = this,
allIds = map(this.data, function (d) {
return d.id;
}),
parentList = series.getListOfParents(this.data, allIds);
series.nodeMap = [];
tree = series.buildNode('', -1, 0, parentList, null);
recursive(this.nodeMap[this.rootNode], function (node) {
var next = false,
p = node.parent;
node.visible = true;
if (p || p === '') {
next = series.nodeMap[p];
}
return next;
});
recursive(this.nodeMap[this.rootNode].children, function (children) {
var next = false;
each(children, function (child) {
child.visible = true;
if (child.children.length) {
next = (next || []).concat(child.children);
}
});
return next;
});
this.setTreeValues(tree);
return tree;
},
init: function (chart, options) {
var series = this;
Series.prototype.init.call(series, chart, options);
if (series.options.allowDrillToNode) {
series.drillTo();
}
},
buildNode: function (id, i, level, list, parent) {
var series = this,
children = [],
point = series.points[i],
node,
child;
// Actions
each((list[id] || []), function (i) {
child = series.buildNode(series.points[i].id, i, (level + 1), list, id);
children.push(child);
});
node = {
id: id,
i: i,
children: children,
level: level,
parent: parent,
visible: false // @todo move this to better location
};
series.nodeMap[node.id] = node;
if (point) {
point.node = node;
}
return node;
},
setTreeValues: function (tree) {
var series = this,
options = series.options,
childrenTotal = 0,
children = [],
val,
point = series.points[tree.i];
// First give the children some values
each(tree.children, function (child) {
child = series.setTreeValues(child);
children.push(child);
if (!child.ignore) {
childrenTotal += child.val;
} else {
// @todo Add predicate to avoid looping already ignored children
recursive(child.children, function (children) {
var next = false;
each(children, function (node) {
extend(node, {
ignore: true,
isLeaf: false,
visible: false
});
if (node.children.length) {
next = (next || []).concat(node.children);
}
});
return next;
});
}
});
// Sort the children
stableSort(children, function (a, b) {
return a.sortIndex - b.sortIndex;
});
// Set the values
val = pick(point && point.value, childrenTotal);
extend(tree, {
children: children,
childrenTotal: childrenTotal,
// Ignore this node if point is not visible
ignore: !(pick(point && point.visible, true) && (val > 0)),
isLeaf: tree.visible && !childrenTotal,
levelDynamic: (options.levelIsConstant ? tree.level : (tree.level - series.nodeMap[series.rootNode].level)),
name: pick(point && point.name, ''),
sortIndex: pick(point && point.sortIndex, -val),
val: val
});
return tree;
},
/**
* Recursive function which calculates the area for all children of a node.
* @param {Object} node The node which is parent to the children.
* @param {Object} area The rectangular area of the parent.
*/
calculateChildrenAreas: function (parent, area) {
var series = this,
options = series.options,
level = this.levelMap[parent.levelDynamic + 1],
algorithm = pick((series[level && level.layoutAlgorithm] && level.layoutAlgorithm), options.layoutAlgorithm),
alternate = options.alternateStartingDirection,
childrenValues = [],
children;
// Collect all children which should be included
children = grep(parent.children, function (n) {
return !n.ignore;
});
if (level && level.layoutStartingDirection) {
area.direction = level.layoutStartingDirection === 'vertical' ? 0 : 1;
}
childrenValues = series[algorithm](area, children);
each(children, function (child, index) {
var values = childrenValues[index];
child.values = merge(values, {
val: child.childrenTotal,
direction: (alternate ? 1 - area.direction : area.direction)
});
child.pointValues = merge(values, {
x: (values.x / series.axisRatio),
width: (values.width / series.axisRatio)
});
// If node has children, then call method recursively
if (child.children.length) {
series.calculateChildrenAreas(child, child.values);
}
});
},
setPointValues: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis;
each(series.points, function (point) {
var node = point.node,
values = node.pointValues,
x1,
x2,
y1,
y2;
// Points which is ignored, have no values.
if (values) {
x1 = Math.round(xAxis.translate(values.x, 0, 0, 0, 1));
x2 = Math.round(xAxis.translate(values.x + values.width, 0, 0, 0, 1));
y1 = Math.round(yAxis.translate(values.y, 0, 0, 0, 1));
y2 = Math.round(yAxis.translate(values.y + values.height, 0, 0, 0, 1));
// Set point values
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2);
point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2);
} else {
// Reset visibility
delete point.plotX;
delete point.plotY;
}
});
},
setColorRecursive: function (node, color) {
var series = this,
point,
level;
if (node) {
point = series.points[node.i];
level = series.levelMap[node.levelDynamic];
// Select either point color, level color or inherited color.
color = pick(point && point.options.color, level && level.color, color);
if (point) {
point.color = color;
}
// Do it all again with the children
if (node.children.length) {
each(node.children, function (child) {
series.setColorRecursive(child, color);
});
}
}
},
algorithmGroup: function (h, w, d, p) {
this.height = h;
this.width = w;
this.plot = p;
this.direction = d;
this.startDirection = d;
this.total = 0;
this.nW = 0;
this.lW = 0;
this.nH = 0;
this.lH = 0;
this.elArr = [];
this.lP = {
total: 0,
lH: 0,
nH: 0,
lW: 0,
nW: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
};
this.addElement = function (el) {
this.lP.total = this.elArr[this.elArr.length - 1];
this.total = this.total + el;
if (this.direction === 0) {
// Calculate last point old aspect ratio
this.lW = this.nW;
this.lP.lH = this.lP.total / this.lW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// Calculate last point new aspect ratio
this.nW = this.total / this.height;
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
} else {
// Calculate last point old aspect ratio
this.lH = this.nH;
this.lP.lW = this.lP.total / this.lH;
this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH);
// Calculate last point new aspect ratio
this.nH = this.total / this.width;
this.lP.nW = this.lP.total / this.nH;
this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH);
}
this.elArr.push(el);
};
this.reset = function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
};
},
algorithmCalcPoints: function (directionChange, last, group, childrenArea) {
var pX,
pY,
pW,
pH,
gW = group.lW,
gH = group.lH,
plot = group.plot,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
gH = group.nH;
} else {
keep = group.elArr[group.elArr.length - 1];
}
each(group.elArr, function (p) {
if (last || (i < end)) {
if (group.direction === 0) {
pX = plot.x;
pY = plot.y;
pW = gW;
pH = p / pW;
} else {
pX = plot.x;
pY = plot.y;
pH = gH;
pW = p / pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (group.direction === 0) {
plot.y = plot.y + pH;
} else {
plot.x = plot.x + pW;
}
}
i = i + 1;
});
// Reset variables
group.reset();
if (group.direction === 0) {
group.width = group.width - gW;
} else {
group.height = group.height - gH;
}
plot.y = plot.parent.y + (plot.parent.height - group.height);
plot.x = plot.parent.x + (plot.parent.width - group.width);
if (directionChange) {
group.direction = 1 - group.direction;
}
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
},
algorithmLowAspectRatio: function (directionChange, parent, children) {
var childrenArea = [],
series = this,
pTot,
plot = {
x: parent.x,
y: parent.y,
parent: parent
},
direction = parent.direction,
i = 0,
end = children.length - 1,
group = new this.algorithmGroup(parent.height, parent.width, direction, plot);
// Loop through and calculate all areas
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
series.algorithmCalcPoints(directionChange, false, group, childrenArea, plot);
}
// If last child, then calculate all remaining areas
if (i === end) {
series.algorithmCalcPoints(directionChange, true, group, childrenArea, plot);
}
i = i + 1;
});
return childrenArea;
},
algorithmFill: function (directionChange, parent, children) {
var childrenArea = [],
pTot,
direction = parent.direction,
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
pX,
pY,
pW,
pH;
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
if (direction === 0) {
pH = height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
} else {
pW = width;
pH = pTot / pW;
height = height - pH;
y = y + pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (directionChange) {
direction = 1 - direction;
}
});
return childrenArea;
},
strip: function (parent, children) {
return this.algorithmLowAspectRatio(false, parent, children);
},
squarified: function (parent, children) {
return this.algorithmLowAspectRatio(true, parent, children);
},
sliceAndDice: function (parent, children) {
return this.algorithmFill(true, parent, children);
},
stripes: function (parent, children) {
return this.algorithmFill(false, parent, children);
},
translate: function () {
var pointValues,
seriesArea,
tree,
val;
// Call prototype function
Series.prototype.translate.call(this);
// Assign variables
this.rootNode = pick(this.options.rootId, '');
// Create a object map from level to options
this.levelMap = reduce(this.options.levels, function (arr, item) {
arr[item.level] = item;
return arr;
}, {});
tree = this.tree = this.getTree(); // @todo Only if series.isDirtyData is true
// Calculate plotting values.
this.axisRatio = (this.xAxis.len / this.yAxis.len);
this.nodeMap[''].pointValues = pointValues = { x: 0, y: 0, width: 100, height: 100 };
this.nodeMap[''].values = seriesArea = merge(pointValues, {
width: (pointValues.width * this.axisRatio),
direction: (this.options.layoutStartingDirection === 'vertical' ? 0 : 1),
val: tree.val
});
this.calculateChildrenAreas(tree, seriesArea);
// Logic for point colors
if (this.colorAxis) {
this.translateColors();
} else if (!this.options.colorByPoint) {
this.setColorRecursive(this.tree, undefined);
}
// Update axis extremes according to the root node.
val = this.nodeMap[this.rootNode].pointValues;
this.xAxis.setExtremes(val.x, val.x + val.width, false);
this.yAxis.setExtremes(val.y, val.y + val.height, false);
this.xAxis.setScale();
this.yAxis.setScale();
// Assign values to points.
this.setPointValues();
},
/**
* Extend drawDataLabels with logic to handle custom options related to the treemap series:
* - Points which is not a leaf node, has dataLabels disabled by default.
* - Options set on series.levels is merged in.
* - Width of the dataLabel is set to match the width of the point shape.
*/
drawDataLabels: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
}),
options,
level;
each(points, function (point) {
level = series.levelMap[point.node.levelDynamic];
// Set options to new object to avoid problems with scope
options = { style: {} };
// If not a leaf, then label should be disabled as default
if (!point.node.isLeaf) {
options.enabled = false;
}
// If options for level exists, include them as well
if (level && level.dataLabels) {
options = merge(options, level.dataLabels);
series._hasPointLabels = true;
}
// Set dataLabel width to the width of the point shape.
if (point.shapeArgs) {
options.style.width = point.shapeArgs.width;
}
// Merge custom options with point options
point.dlOptions = merge(options, point.options.dataLabels);
});
Series.prototype.drawDataLabels.call(this);
},
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
/**
* Get presentational attributes
*/
pointAttribs: function (point, state) {
var level = this.levelMap[point.node.levelDynamic] || {},
options = this.options,
attr,
stateOptions = (state && options.states[state]) || {};
// Set attributes by precedence. Point trumps level trumps series. Stroke width uses pick
// because it can be 0.
attr = {
'stroke': point.borderColor || level.borderColor || stateOptions.borderColor || options.borderColor,
'stroke-width': pick(point.borderWidth, level.borderWidth, stateOptions.borderWidth, options.borderWidth),
'dashstyle': point.borderDashStyle || level.borderDashStyle || stateOptions.borderDashStyle || options.borderDashStyle,
'fill': point.color || this.color,
'zIndex': state === 'hover' ? 1 : 0
};
if (point.node.level <= this.nodeMap[this.rootNode].level) {
// Hide levels above the current view
attr.fill = 'none';
attr['stroke-width'] = 0;
} else if (!point.node.isLeaf) {
// If not a leaf, then remove fill
// @todo let users set the opacity
attr.fill = pick(options.interactByLeaf, !options.allowDrillToNode) ? 'none' : Color(attr.fill).setOpacity(state === 'hover' ? 0.75 : 0.15).get();
} else if (state) {
// Brighten and hoist the hover nodes
attr.fill = Color(attr.fill).brighten(stateOptions.brightness).get();
}
return attr;
},
/**
* Extending ColumnSeries drawPoints
*/
drawPoints: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
});
each(points, function (point) {
var groupKey = 'levelGroup-' + point.node.levelDynamic;
if (!series[groupKey]) {
series[groupKey] = series.chart.renderer.g(groupKey)
.attr({
zIndex: 1000 - point.node.levelDynamic // @todo Set the zIndex based upon the number of levels, instead of using 1000
})
.add(series.group);
}
point.group = series[groupKey];
// Preliminary code in prepraration for HC5 that uses pointAttribs for all series
point.pointAttr = {
'': series.pointAttribs(point),
'hover': series.pointAttribs(point, 'hover'),
'select': {}
};
});
// Call standard drawPoints
seriesTypes.column.prototype.drawPoints.call(this);
// If drillToNode is allowed, set a point cursor on clickables & add drillId to point
if (series.options.allowDrillToNode) {
each(points, function (point) {
var cursor,
drillId;
if (point.graphic) {
drillId = point.drillId = series.options.interactByLeaf ? series.drillToByLeaf(point) : series.drillToByGroup(point);
cursor = drillId ? 'pointer' : 'default';
point.graphic.css({ cursor: cursor });
}
});
}
},
/**
* Add drilling on the suitable points
*/
drillTo: function () {
var series = this;
H.addEvent(series, 'click', function (event) {
var point = event.point,
drillId = point.drillId,
drillName;
// If a drill id is returned, add click event and cursor.
if (drillId) {
drillName = series.nodeMap[series.rootNode].name || series.rootNode;
point.setState(''); // Remove hover
series.drillToNode(drillId);
series.showDrillUpButton(drillName);
}
});
},
/**
* Finds the drill id for a parent node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByGroup: function (point) {
var series = this,
drillId = false;
if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.node.isLeaf) {
drillId = point.id;
}
return drillId;
},
/**
* Finds the drill id for a leaf node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByLeaf: function (point) {
var series = this,
drillId = false,
nodeParent;
if ((point.node.parent !== series.rootNode) && (point.node.isLeaf)) {
nodeParent = point.node;
while (!drillId) {
nodeParent = series.nodeMap[nodeParent.parent];
if (nodeParent.parent === series.rootNode) {
drillId = nodeParent.id;
}
}
}
return drillId;
},
drillUp: function () {
var drillPoint = null,
node,
parent;
if (this.rootNode) {
node = this.nodeMap[this.rootNode];
if (node.parent !== null) {
drillPoint = this.nodeMap[node.parent];
} else {
drillPoint = this.nodeMap[''];
}
}
if (drillPoint !== null) {
this.drillToNode(drillPoint.id);
if (drillPoint.id === '') {
this.drillUpButton = this.drillUpButton.destroy();
} else {
parent = this.nodeMap[drillPoint.parent];
this.showDrillUpButton((parent.name || parent.id));
}
}
},
drillToNode: function (id) {
this.options.rootId = id;
this.isDirty = true; // Force redraw
this.chart.redraw();
},
showDrillUpButton: function (name) {
var series = this,
backText = (name || '< Back'),
buttonOptions = series.options.drillUpButton,
attr,
states;
if (buttonOptions.text) {
backText = buttonOptions.text;
}
if (!this.drillUpButton) {
attr = buttonOptions.theme;
states = attr && attr.states;
this.drillUpButton = this.chart.renderer.button(
backText,
null,
null,
function () {
series.drillUp();
},
attr,
states && states.hover,
states && states.select
)
.attr({
align: buttonOptions.position.align,
zIndex: 9
})
.add()
.align(buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox');
} else {
this.drillUpButton.attr({
text: backText
})
.align();
}
},
buildKDTree: noop,
drawLegendSymbol: H.LegendSymbolMixin.drawRectangle,
getExtremes: function () {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.colorValueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
},
getExtremesFromAll: true,
bindAxes: function () {
var treeAxis = {
endOnTick: false,
gridLineWidth: 0,
lineWidth: 0,
min: 0,
dataMin: 0,
minPadding: 0,
max: 100,
dataMax: 100,
maxPadding: 0,
startOnTick: false,
title: null,
tickPositions: []
};
Series.prototype.bindAxes.call(this);
H.extend(this.yAxis.options, treeAxis);
H.extend(this.xAxis.options, treeAxis);
}
}));
}));
|
/*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(string, object, value) {
/* eslint no-return-assign: 0 */
string.split(',').forEach(function (i) { return object[i] = value; });
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var strictProps = {};
var booleanProps = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
screenWidth = window.screen.width;
screenHeight = window.screen.height;
lastScrollTime = performance.now();
};
}
function Lifecycle() {
this._listeners = [];
this.scrollX = null;
this.scrollY = null;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
} else {
throw Error('Inferno Warning: Cannot update state via setState() in componentWillUpdate()');
}
};
Component.prototype.componentDidMount = function componentDidMount () {
};
Component.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
if ( opts === void 0 ) opts = EMPTY$1;
var reg = /(?:\?([^#]*))?(#.*)?$/,
c = url.match(reg),
matches = {},
ret;
if (c && c[1]) {
var p = c[1].split('&');
for (var i = 0; i < p.length; i++) {
var r = p[i].split('=');
matches[decodeURIComponent(r[0])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
function pathRankSort(a, b) {
var aAttr = a.attrs || EMPTY$1,
bAttr = b.attrs || EMPTY$1;
var diff = rank(bAttr.path) - rank(aAttr.path);
return diff || (bAttr.path.length - aAttr.path.length);
}
function rank(url) {
return (strip(url).match(/\/+/g) || '').length;
}
var Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); |
/**
* React Starter Kit (http://www.reactstarterkit.com/)
*
* Copyright © 2014-2015 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import cp from 'child_process';
/**
* Launches Node.js/Express web server in a separate (forked) process.
*/
export default () => new Promise((resolve, reject) => {
console.log('serve');
const server = cp.fork(path.join(__dirname, '../build/server.js'), {
env: Object.assign({NODE_ENV: 'development'}, process.env)
});
server.once('message', message => {
if (message.match(/^online$/)) {
resolve();
}
});
server.once('error', err => reject(error));
process.on('exit', () => server.kill('SIGTERM'));
});
|
/*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map |
/*
AngularJS v1.6.2
(c) 2010-2017 Google, Inc. http://angularjs.org
License: MIT
*/
(function(x,n){'use strict';function s(f,k){var e=!1,a=!1;this.ngClickOverrideEnabled=function(b){return n.isDefined(b)?(b&&!a&&(a=!0,t.$$moduleName="ngTouch",k.directive("ngClick",t),f.decorator("ngClickDirective",["$delegate",function(a){if(e)a.shift();else for(var b=a.length-1;0<=b;){if("ngTouch"===a[b].$$moduleName){a.splice(b,1);break}b--}return a}])),e=b,this):e};this.$get=function(){return{ngClickOverrideEnabled:function(){return e}}}}function v(f,k,e){p.directive(f,["$parse","$swipe",function(a,
b){return function(l,u,g){function h(c){if(!d)return!1;var a=Math.abs(c.y-d.y);c=(c.x-d.x)*k;return r&&75>a&&0<c&&30<c&&.3>a/c}var m=a(g[f]),d,r,c=["touch"];n.isDefined(g.ngSwipeDisableMouse)||c.push("mouse");b.bind(u,{start:function(c,a){d=c;r=!0},cancel:function(c){r=!1},end:function(c,d){h(c)&&l.$apply(function(){u.triggerHandler(e);m(l,{$event:d})})}},c)}}])}var p=n.module("ngTouch",[]);p.provider("$touch",s);s.$inject=["$provide","$compileProvider"];p.factory("$swipe",[function(){function f(a){a=
a.originalEvent||a;var b=a.touches&&a.touches.length?a.touches:[a];a=a.changedTouches&&a.changedTouches[0]||b[0];return{x:a.clientX,y:a.clientY}}function k(a,b){var l=[];n.forEach(a,function(a){(a=e[a][b])&&l.push(a)});return l.join(" ")}var e={mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},touch:{start:"touchstart",move:"touchmove",end:"touchend",cancel:"touchcancel"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup",cancel:"pointercancel"}};return{bind:function(a,b,l){var e,
g,h,m,d=!1;l=l||["mouse","touch","pointer"];a.on(k(l,"start"),function(c){h=f(c);d=!0;g=e=0;m=h;b.start&&b.start(h,c)});var r=k(l,"cancel");if(r)a.on(r,function(c){d=!1;b.cancel&&b.cancel(c)});a.on(k(l,"move"),function(c){if(d&&h){var a=f(c);e+=Math.abs(a.x-m.x);g+=Math.abs(a.y-m.y);m=a;10>e&&10>g||(g>e?(d=!1,b.cancel&&b.cancel(c)):(c.preventDefault(),b.move&&b.move(a,c)))}});a.on(k(l,"end"),function(c){d&&(d=!1,b.end&&b.end(f(c),c))})}}}]);var t=["$parse","$timeout","$rootElement",function(f,k,e){function a(a,
d,b){for(var c=0;c<a.length;c+=2){var g=a[c+1],e=b;if(25>Math.abs(a[c]-d)&&25>Math.abs(g-e))return a.splice(c,c+2),!0}return!1}function b(b){if(!(2500<Date.now()-u)){var d=b.touches&&b.touches.length?b.touches:[b],e=d[0].clientX,d=d[0].clientY;if(!(1>e&&1>d||h&&h[0]===e&&h[1]===d)){h&&(h=null);var c=b.target;"label"===n.lowercase(c.nodeName||c[0]&&c[0].nodeName)&&(h=[e,d]);a(g,e,d)||(b.stopPropagation(),b.preventDefault(),b.target&&b.target.blur&&b.target.blur())}}}function l(a){a=a.touches&&a.touches.length?
a.touches:[a];var b=a[0].clientX,e=a[0].clientY;g.push(b,e);k(function(){for(var a=0;a<g.length;a+=2)if(g[a]===b&&g[a+1]===e){g.splice(a,a+2);break}},2500,!1)}var u,g,h;return function(h,d,k){var c=f(k.ngClick),w=!1,q,p,s,t;d.on("touchstart",function(a){w=!0;q=a.target?a.target:a.srcElement;3===q.nodeType&&(q=q.parentNode);d.addClass("ng-click-active");p=Date.now();a=a.originalEvent||a;a=(a.touches&&a.touches.length?a.touches:[a])[0];s=a.clientX;t=a.clientY});d.on("touchcancel",function(a){w=!1;d.removeClass("ng-click-active")});
d.on("touchend",function(c){var h=Date.now()-p,f=c.originalEvent||c,m=(f.changedTouches&&f.changedTouches.length?f.changedTouches:f.touches&&f.touches.length?f.touches:[f])[0],f=m.clientX,m=m.clientY,v=Math.sqrt(Math.pow(f-s,2)+Math.pow(m-t,2));w&&750>h&&12>v&&(g||(e[0].addEventListener("click",b,!0),e[0].addEventListener("touchstart",l,!0),g=[]),u=Date.now(),a(g,f,m),q&&q.blur(),n.isDefined(k.disabled)&&!1!==k.disabled||d.triggerHandler("click",[c]));w=!1;d.removeClass("ng-click-active")});d.onclick=
function(a){};d.on("click",function(a,b){h.$apply(function(){c(h,{$event:b||a})})});d.on("mousedown",function(a){d.addClass("ng-click-active")});d.on("mousemove mouseup",function(a){d.removeClass("ng-click-active")})}}];v("ngSwipeLeft",-1,"swipeleft");v("ngSwipeRight",1,"swiperight")})(window,window.angular);
//# sourceMappingURL=angular-touch.min.js.map
|
a enum; |
topojson = (function() {
function merge(topology, arcs) {
var arcsByEnd = {},
fragmentByStart = {},
fragmentByEnd = {};
arcs.forEach(function(i) {
var e = ends(i);
(arcsByEnd[e[0]] || (arcsByEnd[e[0]] = [])).push(i);
(arcsByEnd[e[1]] || (arcsByEnd[e[1]] = [])).push(~i);
});
arcs.forEach(function(i) {
var e = ends(i),
start = e[0],
end = e[1],
f, g;
if (f = fragmentByEnd[start]) {
delete fragmentByEnd[f.end];
f.push(i);
f.end = end;
if (g = fragmentByStart[end]) {
delete fragmentByStart[g.start];
var fg = g === f ? f : f.concat(g);
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
} else if (g = fragmentByEnd[end]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByStart[end]) {
delete fragmentByStart[f.start];
f.unshift(i);
f.start = start;
if (g = fragmentByEnd[start]) {
delete fragmentByEnd[g.end];
var gf = g === f ? f : g.concat(f);
fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
} else if (g = fragmentByStart[start]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByStart[start]) {
delete fragmentByStart[f.start];
f.unshift(~i);
f.start = end;
if (g = fragmentByEnd[end]) {
delete fragmentByEnd[g.end];
var gf = g === f ? f : g.concat(f);
fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
} else if (g = fragmentByStart[end]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByEnd[end]) {
delete fragmentByEnd[f.end];
f.push(~i);
f.end = start;
if (g = fragmentByEnd[start]) {
delete fragmentByStart[g.start];
var fg = g === f ? f : f.concat(g);
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
} else if (g = fragmentByStart[start]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else {
f = [i];
fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
}
});
function ends(i) {
var arc = topology.arcs[i], p0 = arc[0], p1 = [0, 0];
arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
return [p0, p1];
}
var fragments = [];
for (var k in fragmentByEnd) fragments.push(fragmentByEnd[k]);
return fragments;
}
function mesh(topology, o, filter) {
var arcs = [];
if (arguments.length > 1) {
var geomsByArc = [],
geom;
function arc(i) {
if (i < 0) i = ~i;
(geomsByArc[i] || (geomsByArc[i] = [])).push(geom);
}
function line(arcs) {
arcs.forEach(arc);
}
function polygon(arcs) {
arcs.forEach(line);
}
function geometry(o) {
if (o.type === "GeometryCollection") o.geometries.forEach(geometry);
else if (o.type in geometryType) {
geom = o;
geometryType[o.type](o.arcs);
}
}
var geometryType = {
LineString: line,
MultiLineString: polygon,
Polygon: polygon,
MultiPolygon: function(arcs) { arcs.forEach(polygon); }
};
geometry(o);
geomsByArc.forEach(arguments.length < 3
? function(geoms, i) { arcs.push([i]); }
: function(geoms, i) { if (filter(geoms[0], geoms[geoms.length - 1])) arcs.push([i]); });
} else {
for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push([i]);
}
return object(topology, {type: "MultiLineString", arcs: merge(topology, arcs)});
}
function object(topology, o) {
var tf = topology.transform,
kx = tf.scale[0],
ky = tf.scale[1],
dx = tf.translate[0],
dy = tf.translate[1],
arcs = topology.arcs;
function arc(i, points) {
if (points.length) points.pop();
for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, x = 0, y = 0, p; k < n; ++k) points.push([
(x += (p = a[k])[0]) * kx + dx,
(y += p[1]) * ky + dy
]);
if (i < 0) reverse(points, n);
}
function point(coordinates) {
return [coordinates[0] * kx + dx, coordinates[1] * ky + dy];
}
function line(arcs) {
var points = [];
for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
if (points.length < 2) points.push(points[0]);
return points;
}
function ring(arcs) {
var points = line(arcs);
while (points.length < 4) points.push(points[0]);
return points;
}
function polygon(arcs) {
return arcs.map(ring);
}
function geometry(o) {
var t = o.type, g = t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
: t in geometryType ? {type: t, coordinates: geometryType[t](o)}
: {type: null};
if ("id" in o) g.id = o.id;
if ("properties" in o) g.properties = o.properties;
return g;
}
var geometryType = {
Point: function(o) { return point(o.coordinates); },
MultiPoint: function(o) { return o.coordinates.map(point); },
LineString: function(o) { return line(o.arcs); },
MultiLineString: function(o) { return o.arcs.map(line); },
Polygon: function(o) { return polygon(o.arcs); },
MultiPolygon: function(o) { return o.arcs.map(polygon); }
};
return geometry(o);
}
function reverse(array, n) {
var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
}
function bisect(a, x) {
var lo = 0, hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (a[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
function neighbors(objects) {
var objectsByArc = [],
neighbors = objects.map(function() { return []; });
function line(arcs, i) {
arcs.forEach(function(a) {
if (a < 0) a = ~a;
var o = objectsByArc[a] || (objectsByArc[a] = []);
if (!o[i]) o.forEach(function(j) {
var n, k;
k = bisect(n = neighbors[i], j); if (n[k] !== j) n.splice(k, 0, j);
k = bisect(n = neighbors[j], i); if (n[k] !== i) n.splice(k, 0, i);
}), o[i] = i;
});
}
function polygon(arcs, i) {
arcs.forEach(function(arc) { line(arc, i); });
}
function geometry(o, i) {
if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
}
var geometryType = {
LineString: line,
MultiLineString: polygon,
Polygon: polygon,
MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
};
objects.forEach(geometry);
return neighbors;
}
return {
version: "0.0.28",
mesh: mesh,
object: object,
neighbors: neighbors
};
})();
|
Package.describe({
summary: "Github OAuth flow",
version: "1.1.4-plugins.0"
});
Package.onUse(function(api) {
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['client', 'server']);
api.use('http', ['server']);
api.use('underscore', 'client');
api.use('templating', 'client');
api.use('random', 'client');
api.use('service-configuration', ['client', 'server']);
api.export('Github');
api.addFiles(
['github_configure.html', 'github_configure.js'],
'client');
api.addFiles('github_server.js', 'server');
api.addFiles('github_client.js', 'client');
});
|
/*! interpolate.js v1.0.0 | (c) 2014 @toddmotto | https://github.com/toddmotto/interpolate */
!function(t,e){"function"==typeof define&&define.amd?define(e):"object"==typeof exports?module.exports=e:t.interpolate=e()}(this,function(){"use strict";function t(t){"String"===e(t)&&(this.template=n(t))}function e(t){return Object.prototype.toString.call(t).slice(8,-1)}function n(t){return t.replace(/\s(?![^}}]*\{\{)/g,"")}return t.prototype.parse=function(t){if("Object"===e(t)){var n=this.template;for(var r in t){var i=new RegExp("{{"+r+"}}","g");i.test(n)&&(n=n.replace(i,t[r]))}return n}},function(e){var n=new t(e);return function(t){return n.parse(t)}}}); |
/*!
* https://github.com/es-shims/es5-shim
* @license es5-shim Copyright 2009-2015 by contributors, MIT License
* see https://github.com/es-shims/es5-shim/blob/master/LICENSE
*/
// vim: ts=4 sts=4 sw=4 expandtab
// Add semicolon to prevent IIFE from being passed as argument to concatenated code.
;
// UMD (Universal Module Definition)
// see https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
'use strict';
/* global define, exports, module */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function () {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally. This also holds a reference to known-good
// functions.
var $Array = Array;
var ArrayPrototype = $Array.prototype;
var $Object = Object;
var ObjectPrototype = $Object.prototype;
var FunctionPrototype = Function.prototype;
var $String = String;
var StringPrototype = $String.prototype;
var $Number = Number;
var NumberPrototype = $Number.prototype;
var array_slice = ArrayPrototype.slice;
var array_splice = ArrayPrototype.splice;
var array_push = ArrayPrototype.push;
var array_unshift = ArrayPrototype.unshift;
var array_concat = ArrayPrototype.concat;
var call = FunctionPrototype.call;
var max = Math.max;
var min = Math.min;
// Having a toString local variable name breaks in Opera so use to_string.
var to_string = ObjectPrototype.toString;
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isCallable; /* inlined from https://npmjs.com/is-callable */ var fnToStr = Function.prototype.toString, tryFunctionObject = function tryFunctionObject(value) { try { fnToStr.call(value); return true; } catch (e) { return false; } }, fnClass = '[object Function]', genClass = '[object GeneratorFunction]'; isCallable = function isCallable(value) { if (typeof value !== 'function') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } var strClass = to_string.call(value); return strClass === fnClass || strClass === genClass; };
var isRegex; /* inlined from https://npmjs.com/is-regex */ var regexExec = RegExp.prototype.exec, tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }, regexClass = '[object RegExp]'; isRegex = function isRegex(value) { if (typeof value !== 'object') { return false; } return hasToStringTag ? tryRegexExec(value) : to_string.call(value) === regexClass; };
var isString; /* inlined from https://npmjs.com/is-string */ var strValue = String.prototype.valueOf, tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }, stringClass = '[object String]'; isString = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : to_string.call(value) === stringClass; };
/* inlined from http://npmjs.com/define-properties */
var defineProperties = (function (has) {
var supportsDescriptors = $Object.defineProperty && (function () {
try {
var obj = {};
$Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
for (var _ in obj) { return false; }
return obj.x === obj;
} catch (e) { /* this is ES3 */
return false;
}
}());
// Define configurable, writable and non-enumerable props
// if they don't exist.
var defineProperty;
if (supportsDescriptors) {
defineProperty = function (object, name, method, forceAssign) {
if (!forceAssign && (name in object)) { return; }
$Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
};
} else {
defineProperty = function (object, name, method, forceAssign) {
if (!forceAssign && (name in object)) { return; }
object[name] = method;
};
}
return function defineProperties(object, map, forceAssign) {
for (var name in map) {
if (has.call(map, name)) {
defineProperty(object, name, map[name], forceAssign);
}
}
};
}(ObjectPrototype.hasOwnProperty));
//
// Util
// ======
//
/* replaceable with https://npmjs.com/package/es-abstract /helpers/isPrimitive */
var isPrimitive = function isPrimitive(input) {
var type = typeof input;
return input === null || (type !== 'object' && type !== 'function');
};
var isActualNaN = $Number.isNaN || function (x) { return x !== x; };
var ES = {
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToInteger */
ToInteger: function ToInteger(num) {
var n = +num;
if (isActualNaN(n)) {
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
},
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToPrimitive */
ToPrimitive: function ToPrimitive(input) {
var val, valueOf, toStr;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (isCallable(valueOf)) {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toStr = input.toString;
if (isCallable(toStr)) {
val = toStr.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
},
// ES5 9.9
// http://es5.github.com/#x9.9
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToObject */
ToObject: function (o) {
/* jshint eqnull: true */
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert " + o + ' to object');
}
return $Object(o);
},
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToUint32 */
ToUint32: function ToUint32(x) {
return x >>> 0;
}
};
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
var Empty = function Empty() {};
defineProperties(FunctionPrototype, {
bind: function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (!isCallable(target)) {
throw new TypeError('Function.prototype.bind called on incompatible ' + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = array_slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound;
var binder = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
array_concat.call(args, array_slice.call(arguments))
);
if ($Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
array_concat.call(args, array_slice.call(arguments))
);
}
};
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
var boundLength = max(0, target.length - args.length);
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
array_push.call(boundArgs, '$' + i);
}
// XXX Build a dynamic function with desired amount of arguments is the only
// way to set the length property of a function.
// In environments where Content Security Policies enabled (Chrome extensions,
// for ex.) all use of eval or Function costructor throws an exception.
// However in all of these environments Function.prototype.bind exists
// and so this code will never be executed.
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
if (target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
// Clean up dangling references.
Empty.prototype = null;
}
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
}
});
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var owns = call.bind(ObjectPrototype.hasOwnProperty);
var toStr = call.bind(ObjectPrototype.toString);
var strSlice = call.bind(StringPrototype.slice);
var strSplit = call.bind(StringPrototype.split);
var strIndexOf = call.bind(StringPrototype.indexOf);
//
// Array
// =====
//
var isArray = $Array.isArray || function isArray(obj) {
return toStr(obj) === '[object Array]';
};
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.13
// Return len+argCount.
// [bugfix, ielt8]
// IE < 8 bug: [].unshift(0) === undefined but should be "1"
var hasUnshiftReturnValueBug = [].unshift(0) !== 1;
defineProperties(ArrayPrototype, {
unshift: function () {
array_unshift.apply(this, arguments);
return this.length;
}
}, hasUnshiftReturnValueBug);
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
defineProperties($Array, { isArray: isArray });
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = $Object('a');
var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
var properlyBoxesContext = function properlyBoxed(method) {
// Check node 0.6.21 bug where third parameter is not boxed
var properlyBoxesNonStrict = true;
var properlyBoxesStrict = true;
if (method) {
method.call('foo', function (_, __, context) {
if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
});
method.call([1], function () {
'use strict';
properlyBoxesStrict = typeof this === 'string';
}, 'x');
}
return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
};
defineProperties(ArrayPrototype, {
forEach: function forEach(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var i = -1;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.forEach callback must be a function');
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
if (typeof T === 'undefined') {
callbackfn(self[i], i, object);
} else {
callbackfn.call(T, self[i], i, object);
}
}
}
}
}, !properlyBoxesContext(ArrayPrototype.forEach));
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
defineProperties(ArrayPrototype, {
map: function map(callbackfn/*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var result = $Array(length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.map callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
if (typeof T === 'undefined') {
result[i] = callbackfn(self[i], i, object);
} else {
result[i] = callbackfn.call(T, self[i], i, object);
}
}
}
return result;
}
}, !properlyBoxesContext(ArrayPrototype.map));
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
defineProperties(ArrayPrototype, {
filter: function filter(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var result = [];
var value;
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.filter callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (typeof T === 'undefined' ? callbackfn(value, i, object) : callbackfn.call(T, value, i, object)) {
array_push.call(result, value);
}
}
}
return result;
}
}, !properlyBoxesContext(ArrayPrototype.filter));
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
defineProperties(ArrayPrototype, {
every: function every(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.every callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self && !(typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
return false;
}
}
return true;
}
}, !properlyBoxesContext(ArrayPrototype.every));
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
defineProperties(ArrayPrototype, {
some: function some(callbackfn/*, thisArg */) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.some callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self && (typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
return true;
}
}
return false;
}
}, !properlyBoxesContext(ArrayPrototype.some));
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
var reduceCoercesToObject = false;
if (ArrayPrototype.reduce) {
reduceCoercesToObject = typeof ArrayPrototype.reduce.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
defineProperties(ArrayPrototype, {
reduce: function reduce(callbackfn /*, initialValue*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.reduce callback must be a function');
}
// no value to return if no initial value and an empty array
if (length === 0 && arguments.length === 1) {
throw new TypeError('reduce of empty array with no initial value');
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError('reduce of empty array with no initial value');
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = callbackfn(result, self[i], i, object);
}
}
return result;
}
}, !reduceCoercesToObject);
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
var reduceRightCoercesToObject = false;
if (ArrayPrototype.reduceRight) {
reduceRightCoercesToObject = typeof ArrayPrototype.reduceRight.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
defineProperties(ArrayPrototype, {
reduceRight: function reduceRight(callbackfn/*, initial*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.reduceRight callback must be a function');
}
// no value to return if no initial value, empty array
if (length === 0 && arguments.length === 1) {
throw new TypeError('reduceRight of empty array with no initial value');
}
var result;
var i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError('reduceRight of empty array with no initial value');
}
} while (true);
}
if (i < 0) {
return result;
}
do {
if (i in self) {
result = callbackfn(result, self[i], i, object);
}
} while (i--);
return result;
}
}, !reduceRightCoercesToObject);
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
var hasFirefox2IndexOfBug = ArrayPrototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
defineProperties(ArrayPrototype, {
indexOf: function indexOf(searchElement /*, fromIndex */) {
var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
var length = ES.ToUint32(self.length);
if (length === 0) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = ES.ToInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === searchElement) {
return i;
}
}
return -1;
}
}, hasFirefox2IndexOfBug);
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
var hasFirefox2LastIndexOfBug = ArrayPrototype.lastIndexOf && [0, 1].lastIndexOf(0, -3) !== -1;
defineProperties(ArrayPrototype, {
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */) {
var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
var length = ES.ToUint32(self.length);
if (length === 0) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = min(i, ES.ToInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && searchElement === self[i]) {
return i;
}
}
return -1;
}
}, hasFirefox2LastIndexOfBug);
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.12
var spliceNoopReturnsEmptyArray = (function () {
var a = [1, 2];
var result = a.splice();
return a.length === 2 && isArray(result) && result.length === 0;
}());
defineProperties(ArrayPrototype, {
// Safari 5.0 bug where .splice() returns undefined
splice: function splice(start, deleteCount) {
if (arguments.length === 0) {
return [];
} else {
return array_splice.apply(this, arguments);
}
}
}, !spliceNoopReturnsEmptyArray);
var spliceWorksWithEmptyObject = (function () {
var obj = {};
ArrayPrototype.splice.call(obj, 0, 0, 1);
return obj.length === 1;
}());
defineProperties(ArrayPrototype, {
splice: function splice(start, deleteCount) {
if (arguments.length === 0) { return []; }
var args = arguments;
this.length = max(ES.ToInteger(this.length), 0);
if (arguments.length > 0 && typeof deleteCount !== 'number') {
args = array_slice.call(arguments);
if (args.length < 2) {
array_push.call(args, this.length - start);
} else {
args[1] = ES.ToInteger(deleteCount);
}
}
return array_splice.apply(this, args);
}
}, !spliceWorksWithEmptyObject);
var spliceWorksWithLargeSparseArrays = (function () {
// Per https://github.com/es-shims/es5-shim/issues/295
// Safari 7/8 breaks with sparse arrays of size 1e5 or greater
var arr = new $Array(1e5);
// note: the index MUST be 8 or larger or the test will false pass
arr[8] = 'x';
arr.splice(1, 1);
// note: this test must be defined *after* the indexOf shim
// per https://github.com/es-shims/es5-shim/issues/313
return arr.indexOf('x') === 7;
}());
var spliceWorksWithSmallSparseArrays = (function () {
// Per https://github.com/es-shims/es5-shim/issues/295
// Opera 12.15 breaks on this, no idea why.
var n = 256;
var arr = [];
arr[n] = 'a';
arr.splice(n + 1, 0, 'b');
return arr[n] === 'a';
}());
defineProperties(ArrayPrototype, {
splice: function splice(start, deleteCount) {
var O = ES.ToObject(this);
var A = [];
var len = ES.ToUint32(O.length);
var relativeStart = ES.ToInteger(start);
var actualStart = relativeStart < 0 ? max((len + relativeStart), 0) : min(relativeStart, len);
var actualDeleteCount = min(max(ES.ToInteger(deleteCount), 0), len - actualStart);
var k = 0;
var from;
while (k < actualDeleteCount) {
from = $String(actualStart + k);
if (owns(O, from)) {
A[k] = O[from];
}
k += 1;
}
var items = array_slice.call(arguments, 2);
var itemCount = items.length;
var to;
if (itemCount < actualDeleteCount) {
k = actualStart;
while (k < (len - actualDeleteCount)) {
from = $String(k + actualDeleteCount);
to = $String(k + itemCount);
if (owns(O, from)) {
O[to] = O[from];
} else {
delete O[to];
}
k += 1;
}
k = len;
while (k > (len - actualDeleteCount + itemCount)) {
delete O[k - 1];
k -= 1;
}
} else if (itemCount > actualDeleteCount) {
k = len - actualDeleteCount;
while (k > actualStart) {
from = $String(k + actualDeleteCount - 1);
to = $String(k + itemCount - 1);
if (owns(O, from)) {
O[to] = O[from];
} else {
delete O[to];
}
k -= 1;
}
}
k = actualStart;
for (var i = 0; i < items.length; ++i) {
O[k] = items[i];
k += 1;
}
O.length = len - actualDeleteCount + itemCount;
return A;
}
}, !spliceWorksWithLargeSparseArrays || !spliceWorksWithSmallSparseArrays);
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var hasStringEnumBug = !owns('x', '0');
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var blacklistedKeys = {
$window: true,
$console: true,
$parent: true,
$self: true,
$frame: true,
$frames: true,
$frameElement: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true
};
var hasAutomationEqualityBug = (function () {
/* globals window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!blacklistedKeys['$' + k] && owns(window, k) && window[k] !== null && typeof window[k] === 'object') {
equalsConstructorPrototype(window[k]);
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (object) {
if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(object); }
try {
return equalsConstructorPrototype(object);
} catch (e) {
return false;
}
};
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var dontEnumsLength = dontEnums.length;
// taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
// can be replaced with require('is-arguments') if we ever use a build process instead
var isStandardArguments = function isArguments(value) {
return toStr(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
!isArray(value) &&
isCallable(value.callee);
};
var isArguments = isStandardArguments(arguments) ? isStandardArguments : isLegacyArguments;
defineProperties($Object, {
keys: function keys(object) {
var isFn = isCallable(object);
var isArgs = isArguments(object);
var isObject = object !== null && typeof object === 'object';
var isStr = isObject && isString(object);
if (!isObject && !isFn && !isArgs) {
throw new TypeError('Object.keys called on a non-object');
}
var theKeys = [];
var skipProto = hasProtoEnumBug && isFn;
if ((isStr && hasStringEnumBug) || isArgs) {
for (var i = 0; i < object.length; ++i) {
array_push.call(theKeys, $String(i));
}
}
if (!isArgs) {
for (var name in object) {
if (!(skipProto && name === 'prototype') && owns(object, name)) {
array_push.call(theKeys, $String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j];
if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) {
array_push.call(theKeys, dontEnum);
}
}
}
return theKeys;
}
});
var keysWorksWithArguments = $Object.keys && (function () {
// Safari 5.0 bug
return $Object.keys(arguments).length === 2;
}(1, 2));
var keysHasArgumentsLengthBug = $Object.keys && (function () {
var argKeys = $Object.keys(arguments);
return arguments.length !== 1 || argKeys.length !== 1 || argKeys[0] !== 1;
}(1));
var originalKeys = $Object.keys;
defineProperties($Object, {
keys: function keys(object) {
if (isArguments(object)) {
return originalKeys(array_slice.call(object));
} else {
return originalKeys(object);
}
}
}, !keysWorksWithArguments || keysHasArgumentsLengthBug);
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
var negativeDate = -62198755200000;
var negativeYearString = '-000001';
var hasNegativeDateBug = Date.prototype.toISOString && new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1;
var hasSafari51DateBug = Date.prototype.toISOString && new Date(-1).toISOString() !== '1969-12-31T23:59:59.999Z';
defineProperties(Date.prototype, {
toISOString: function toISOString() {
var result, length, value, year, month;
if (!isFinite(this)) {
throw new RangeError('Date.prototype.toISOString called on non-finite value.');
}
year = this.getUTCFullYear();
month = this.getUTCMonth();
// see https://github.com/es-shims/es5-shim/issues/111
year += Math.floor(month / 12);
month = (month % 12 + 12) % 12;
// the date time string format is specified in 15.9.1.15.
result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = (
(year < 0 ? '-' : (year > 9999 ? '+' : '')) +
strSlice('00000' + Math.abs(year), (0 <= year && year <= 9999) ? -4 : -6)
);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two
// digits.
if (value < 10) {
result[length] = '0' + value;
}
}
// pad milliseconds to have three digits.
return (
year + '-' + array_slice.call(result, 0, 2).join('-') +
'T' + array_slice.call(result, 2).join(':') + '.' +
strSlice('000' + this.getUTCMilliseconds(), -3) + 'Z'
);
}
}, hasNegativeDateBug || hasSafari51DateBug);
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
var dateToJSONIsSupported = (function () {
try {
return Date.prototype.toJSON &&
new Date(NaN).toJSON() === null &&
new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
Date.prototype.toJSON.call({ // generic
toISOString: function () { return true; }
});
} catch (e) {
return false;
}
}());
if (!dateToJSONIsSupported) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ES.ToPrimitive(O, hint Number).
var O = $Object(this);
var tv = ES.ToPrimitive(O);
// 3. If tv is a Number and is not finite, return null.
if (typeof tv === 'number' && !isFinite(tv)) {
return null;
}
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
var toISO = O.toISOString;
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (!isCallable(toISO)) {
throw new TypeError('toISOString property is not callable');
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return toISO.call(O);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15;
var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')) || !isNaN(Date.parse('2012-12-31T23:59:60.000Z'));
var doesNotParseY2KNewYear = isNaN(Date.parse('2000-01-01T00:00:00.000Z'));
if (doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
/* global Date: true */
/* eslint-disable no-undef */
var maxSafeUnsigned32Bit = Math.pow(2, 31) - 1;
var secondsWithinMaxSafeUnsigned32Bit = Math.floor(maxSafeUnsigned32Bit / 1e3);
var hasSafariSignedIntBug = isActualNaN(new Date(1970, 0, 1, 0, 0, 0, maxSafeUnsigned32Bit + 1).getTime());
Date = (function (NativeDate) {
/* eslint-enable no-undef */
// Date.length === 7
var DateShim = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
var date;
if (this instanceof NativeDate) {
var seconds = s;
var millis = ms;
if (hasSafariSignedIntBug && length >= 7 && ms > maxSafeUnsigned32Bit) {
// work around a Safari 8/9 bug where it treats the seconds as signed
var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
var sToShift = Math.floor(msToShift / 1e3);
seconds += sToShift;
millis -= sToShift * 1e3;
}
date = length === 1 && $String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(DateShim.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, seconds, millis) :
length >= 6 ? new NativeDate(Y, M, D, h, m, seconds) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
} else {
date = NativeDate.apply(this, arguments);
}
if (!isPrimitive(date)) {
// Prevent mixups with unfixed Date object
defineProperties(date, { constructor: DateShim }, true);
}
return date;
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp('^' +
'(\\d{4}|[+-]\\d{6})' + // four-digit year capture or sign +
// 6-digit extended year
'(?:-(\\d{2})' + // optional month capture
'(?:-(\\d{2})' + // optional day capture
'(?:' + // capture hours:minutes:seconds.milliseconds
'T(\\d{2})' + // hours capture
':(\\d{2})' + // minutes capture
'(?:' + // optional :seconds.milliseconds
':(\\d{2})' + // seconds capture
'(?:(\\.\\d{1,}))?' + // milliseconds capture
')?' +
'(' + // capture UTC offset component
'Z|' + // UTC capture
'(?:' + // offset specifier +/-hours:minutes
'([-+])' + // sign capture
'(\\d{2})' + // hours offset capture
':(\\d{2})' + // minutes offset capture
')' +
')?)?)?)?' +
'$');
var months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
var dayFromMonth = function dayFromMonth(year, month) {
var t = month > 1 ? 1 : 0;
return (
months[month] +
Math.floor((year - 1969 + t) / 4) -
Math.floor((year - 1901 + t) / 100) +
Math.floor((year - 1601 + t) / 400) +
365 * (year - 1970)
);
};
var toUTC = function toUTC(t) {
var s = 0;
var ms = t;
if (hasSafariSignedIntBug && ms > maxSafeUnsigned32Bit) {
// work around a Safari 8/9 bug where it treats the seconds as signed
var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
var sToShift = Math.floor(msToShift / 1e3);
s += sToShift;
ms -= sToShift * 1e3;
}
return $Number(new NativeDate(1970, 0, 1, 0, 0, s, ms));
};
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
if (owns(NativeDate, key)) {
DateShim[key] = NativeDate[key];
}
}
// Copy "native" methods explicitly; they may be non-enumerable
defineProperties(DateShim, {
now: NativeDate.now,
UTC: NativeDate.UTC
}, true);
DateShim.prototype = NativeDate.prototype;
defineProperties(DateShim.prototype, {
constructor: DateShim
}, true);
// Upgrade Date.parse to handle simplified ISO 8601 strings
var parseShim = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = $Number(match[1]),
month = $Number(match[2] || 1) - 1,
day = $Number(match[3] || 1) - 1,
hour = $Number(match[4] || 0),
minute = $Number(match[5] || 0),
second = $Number(match[6] || 0),
millisecond = Math.floor($Number(match[7] || 0) * 1000),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
isLocalTime = Boolean(match[4] && !match[8]),
signOffset = match[9] === '-' ? 1 : -1,
hourOffset = $Number(match[10] || 0),
minuteOffset = $Number(match[11] || 0),
result;
var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
if (
hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond;
if (isLocalTime) {
result = toUTC(result);
}
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
};
defineProperties(DateShim, { parse: parseShim });
return DateShim;
}(Date));
/* global Date: false */
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
//
// Number
// ======
//
// ES5.1 15.7.4.5
// http://es5.github.com/#x15.7.4.5
var hasToFixedBugs = NumberPrototype.toFixed && (
(0.00008).toFixed(3) !== '0.000' ||
(0.9).toFixed(0) !== '1' ||
(1.255).toFixed(2) !== '1.25' ||
(1000000000000000128).toFixed(0) !== '1000000000000000128'
);
var toFixedHelpers = {
base: 1e7,
size: 6,
data: [0, 0, 0, 0, 0, 0],
multiply: function multiply(n, c) {
var i = -1;
var c2 = c;
while (++i < toFixedHelpers.size) {
c2 += n * toFixedHelpers.data[i];
toFixedHelpers.data[i] = c2 % toFixedHelpers.base;
c2 = Math.floor(c2 / toFixedHelpers.base);
}
},
divide: function divide(n) {
var i = toFixedHelpers.size, c = 0;
while (--i >= 0) {
c += toFixedHelpers.data[i];
toFixedHelpers.data[i] = Math.floor(c / n);
c = (c % n) * toFixedHelpers.base;
}
},
numToString: function numToString() {
var i = toFixedHelpers.size;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || toFixedHelpers.data[i] !== 0) {
var t = $String(toFixedHelpers.data[i]);
if (s === '') {
s = t;
} else {
s += strSlice('0000000', 0, 7 - t.length) + t;
}
}
}
return s;
},
pow: function pow(x, n, acc) {
return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc)));
},
log: function log(x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
}
return n;
}
};
defineProperties(NumberPrototype, {
toFixed: function toFixed(fractionDigits) {
var f, x, s, m, e, z, j, k;
// Test for NaN and round fractionDigits down
f = $Number(fractionDigits);
f = isActualNaN(f) ? 0 : Math.floor(f);
if (f < 0 || f > 20) {
throw new RangeError('Number.toFixed called with invalid number of decimals');
}
x = $Number(this);
if (isActualNaN(x)) {
return 'NaN';
}
// If it is too big or small, return the string value of the number
if (x <= -1e21 || x >= 1e21) {
return $String(x);
}
s = '';
if (x < 0) {
s = '-';
x = -x;
}
m = '0';
if (x > 1e-21) {
// 1e-21 < x < 1e21
// -70 < log2(x) < 70
e = toFixedHelpers.log(x * toFixedHelpers.pow(2, 69, 1)) - 69;
z = (e < 0 ? x * toFixedHelpers.pow(2, -e, 1) : x / toFixedHelpers.pow(2, e, 1));
z *= 0x10000000000000; // Math.pow(2, 52);
e = 52 - e;
// -18 < e < 122
// x = z / 2 ^ e
if (e > 0) {
toFixedHelpers.multiply(0, z);
j = f;
while (j >= 7) {
toFixedHelpers.multiply(1e7, 0);
j -= 7;
}
toFixedHelpers.multiply(toFixedHelpers.pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
toFixedHelpers.divide(1 << 23);
j -= 23;
}
toFixedHelpers.divide(1 << j);
toFixedHelpers.multiply(1, 1);
toFixedHelpers.divide(2);
m = toFixedHelpers.numToString();
} else {
toFixedHelpers.multiply(0, z);
toFixedHelpers.multiply(1 << (-e), 0);
m = toFixedHelpers.numToString() + strSlice('0.00000000000000000000', 2, 2 + f);
}
}
if (f > 0) {
k = m.length;
if (k <= f) {
m = s + strSlice('0.0000000000000000000', 0, f - k + 2) + m;
} else {
m = s + strSlice(m, 0, k - f) + '.' + strSlice(m, k - f);
}
} else {
m = s + m;
}
return m;
}
}, hasToFixedBugs);
//
// String
// ======
//
// ES5 15.5.4.14
// http://es5.github.com/#x15.5.4.14
// [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
// Many browsers do not split properly with regular expressions or they
// do not perform the split correctly under obscure conditions.
// See http://blog.stevenlevithan.com/archives/cross-browser-split
// I've tested in many browsers and this seems to cover the deviant ones:
// 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
// '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
// 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
// [undefined, "t", undefined, "e", ...]
// ''.split(/.?/) should be [], not [""]
// '.'.split(/()()/) should be ["."], not ["", "", "."]
if (
'ab'.split(/(?:ab)*/).length !== 2 ||
'.'.split(/(.?)(.?)/).length !== 4 ||
'tesst'.split(/(s)*/)[1] === 't' ||
'test'.split(/(?:)/, -1).length !== 4 ||
''.split(/.?/).length ||
'.'.split(/()()/).length > 1
) {
(function () {
var compliantExecNpcg = typeof (/()??/).exec('')[1] === 'undefined'; // NPCG: nonparticipating capturing group
var maxSafe32BitInt = Math.pow(2, 32) - 1;
StringPrototype.split = function (separator, limit) {
var string = this;
if (typeof separator === 'undefined' && limit === 0) {
return [];
}
// If `separator` is not a regex, use native split
if (!isRegex(separator)) {
return strSplit(this, separator, limit);
}
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') + // in ES6
(separator.sticky ? 'y' : ''), // Firefox 3+ and ES6
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
var separatorCopy = new RegExp(separator.source, flags + 'g');
string += ''; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // maxSafe32BitInt
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
var splitLimit = typeof limit === 'undefined' ? maxSafe32BitInt : ES.ToUint32(limit);
match = separatorCopy.exec(string);
while (match) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
array_push.call(output, strSlice(string, lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
/* eslint-disable no-loop-func */
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (typeof arguments[i] === 'undefined') {
match[i] = void 0;
}
}
});
/* eslint-enable no-loop-func */
}
if (match.length > 1 && match.index < string.length) {
array_push.apply(output, array_slice.call(match, 1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= splitLimit) {
break;
}
}
if (separatorCopy.lastIndex === match.index) {
separatorCopy.lastIndex++; // Avoid an infinite loop
}
match = separatorCopy.exec(string);
}
if (lastLastIndex === string.length) {
if (lastLength || !separatorCopy.test('')) {
array_push.call(output, '');
}
} else {
array_push.call(output, strSlice(string, lastLastIndex));
}
return output.length > splitLimit ? strSlice(output, 0, splitLimit) : output;
};
}());
// [bugfix, chrome]
// If separator is undefined, then the result array contains just one String,
// which is the this value (converted to a String). If limit is not undefined,
// then the output array is truncated so that it contains no more than limit
// elements.
// "0".split(undefined, 0) -> []
} else if ('0'.split(void 0, 0).length) {
StringPrototype.split = function split(separator, limit) {
if (typeof separator === 'undefined' && limit === 0) { return []; }
return strSplit(this, separator, limit);
};
}
var str_replace = StringPrototype.replace;
var replaceReportsGroupsCorrectly = (function () {
var groups = [];
'x'.replace(/x(.)?/g, function (match, group) {
array_push.call(groups, group);
});
return groups.length === 1 && typeof groups[0] === 'undefined';
}());
if (!replaceReportsGroupsCorrectly) {
StringPrototype.replace = function replace(searchValue, replaceValue) {
var isFn = isCallable(replaceValue);
var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source);
if (!isFn || !hasCapturingGroups) {
return str_replace.call(this, searchValue, replaceValue);
} else {
var wrappedReplaceValue = function (match) {
var length = arguments.length;
var originalLastIndex = searchValue.lastIndex;
searchValue.lastIndex = 0;
var args = searchValue.exec(match) || [];
searchValue.lastIndex = originalLastIndex;
array_push.call(args, arguments[length - 2], arguments[length - 1]);
return replaceValue.apply(this, args);
};
return str_replace.call(this, searchValue, wrappedReplaceValue);
}
};
}
// ECMA-262, 3rd B.2.3
// Not an ECMAScript standard, although ECMAScript 3rd Edition has a
// non-normative section suggesting uniform semantics and it should be
// normalized across all browsers
// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
var string_substr = StringPrototype.substr;
var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
defineProperties(StringPrototype, {
substr: function substr(start, length) {
var normalizedStart = start;
if (start < 0) {
normalizedStart = max(this.length + start, 0);
}
return string_substr.call(this, normalizedStart, length);
}
}, hasNegativeSubstrBug);
// ES5 15.5.4.20
// whitespace from: http://es5.github.io/#x15.5.4.20
var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' +
'\u2029\uFEFF';
var zeroWidth = '\u200b';
var wsRegexChars = '[' + ws + ']';
var trimBeginRegexp = new RegExp('^' + wsRegexChars + wsRegexChars + '*');
var trimEndRegexp = new RegExp(wsRegexChars + wsRegexChars + '*$');
var hasTrimWhitespaceBug = StringPrototype.trim && (ws.trim() || !zeroWidth.trim());
defineProperties(StringPrototype, {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
trim: function trim() {
if (typeof this === 'undefined' || this === null) {
throw new TypeError("can't convert " + this + ' to object');
}
return $String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
}
}, hasTrimWhitespaceBug);
var hasLastIndexBug = String.prototype.lastIndexOf && 'abcあい'.lastIndexOf('あい', 2) !== -1;
defineProperties(StringPrototype, {
lastIndexOf: function lastIndexOf(searchString) {
if (typeof this === 'undefined' || this === null) {
throw new TypeError("can't convert " + this + ' to object');
}
var S = $String(this);
var searchStr = $String(searchString);
var numPos = arguments.length > 1 ? $Number(arguments[1]) : NaN;
var pos = isActualNaN(numPos) ? Infinity : ES.ToInteger(numPos);
var start = min(max(pos, 0), S.length);
var searchLen = searchStr.length;
var k = start + searchLen;
while (k > 0) {
k = max(0, k - searchLen);
var index = strIndexOf(strSlice(S, k, start + searchLen), searchStr);
if (index !== -1) {
return k + index;
}
}
return -1;
}
}, hasLastIndexBug);
// ES-5 15.1.2.2
if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) {
/* global parseInt: true */
parseInt = (function (origParseInt) {
var hexRegex = /^0[xX]/;
return function parseInt(str, radix) {
var string = $String(str).trim();
var defaultedRadix = $Number(radix) || (hexRegex.test(string) ? 16 : 10);
return origParseInt(string, defaultedRadix);
};
}(parseInt));
}
}));
|
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/BaseTypes/Class.js
*/
/**
* Class: OpenLayers.Protocol
* Abstract vector layer protocol class. Not to be instantiated directly. Use
* one of the protocol subclasses instead.
*/
OpenLayers.Protocol = OpenLayers.Class({
/**
* Property: format
* {<OpenLayers.Format>} The format used by this protocol.
*/
format: null,
/**
* Property: options
* {Object} Any options sent to the constructor.
*/
options: null,
/**
* Property: autoDestroy
* {Boolean} The creator of the protocol can set autoDestroy to false
* to fully control when the protocol is destroyed. Defaults to
* true.
*/
autoDestroy: true,
/**
* Property: defaultFilter
* {<OpenLayers.Filter>} Optional default filter to read requests
*/
defaultFilter: null,
/**
* Constructor: OpenLayers.Protocol
* Abstract class for vector protocols. Create instances of a subclass.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*/
initialize: function(options) {
options = options || {};
OpenLayers.Util.extend(this, options);
this.options = options;
},
/**
* Method: mergeWithDefaultFilter
* Merge filter passed to the read method with the default one
*
* Parameters:
* filter - {<OpenLayers.Filter>}
*/
mergeWithDefaultFilter: function(filter) {
var merged;
if (filter && this.defaultFilter) {
merged = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND,
filters: [this.defaultFilter, filter]
});
} else {
merged = filter || this.defaultFilter || undefined;
}
return merged;
},
/**
* APIMethod: destroy
* Clean up the protocol.
*/
destroy: function() {
this.options = null;
this.format = null;
},
/**
* APIMethod: read
* Construct a request for reading new features.
*
* Parameters:
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
read: function(options) {
options = options || {};
options.filter = this.mergeWithDefaultFilter(options.filter);
},
/**
* APIMethod: create
* Construct a request for writing newly created features.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})} or
* {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
create: function() {
},
/**
* APIMethod: update
* Construct a request updating modified features.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})} or
* {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
update: function() {
},
/**
* APIMethod: delete
* Construct a request deleting a removed feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
"delete": function() {
},
/**
* APIMethod: commit
* Go over the features and for each take action
* based on the feature state. Possible actions are create,
* update and delete.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})}
* options - {Object} Object whose possible keys are "create", "update",
* "delete", "callback" and "scope", the values referenced by the
* first three are objects as passed to the "create", "update", and
* "delete" methods, the value referenced by the "callback" key is
* a function which is called when the commit operation is complete
* using the scope referenced by the "scope" key.
*
* Returns:
* {Array({<OpenLayers.Protocol.Response>})} An array of
* <OpenLayers.Protocol.Response> objects.
*/
commit: function() {
},
/**
* Method: abort
* Abort an ongoing request.
*
* Parameters:
* response - {<OpenLayers.Protocol.Response>}
*/
abort: function(response) {
},
/**
* Method: createCallback
* Returns a function that applies the given public method with resp and
* options arguments.
*
* Parameters:
* method - {Function} The method to be applied by the callback.
* response - {<OpenLayers.Protocol.Response>} The protocol response object.
* options - {Object} Options sent to the protocol method
*/
createCallback: function(method, response, options) {
return OpenLayers.Function.bind(function() {
method.apply(this, [response, options]);
}, this);
},
CLASS_NAME: "OpenLayers.Protocol"
});
/**
* Class: OpenLayers.Protocol.Response
* Protocols return Response objects to their users.
*/
OpenLayers.Protocol.Response = OpenLayers.Class({
/**
* Property: code
* {Number} - OpenLayers.Protocol.Response.SUCCESS or
* OpenLayers.Protocol.Response.FAILURE
*/
code: null,
/**
* Property: requestType
* {String} The type of request this response corresponds to. Either
* "create", "read", "update" or "delete".
*/
requestType: null,
/**
* Property: last
* {Boolean} - true if this is the last response expected in a commit,
* false otherwise, defaults to true.
*/
last: true,
/**
* Property: features
* {Array({<OpenLayers.Feature.Vector>})} or {<OpenLayers.Feature.Vector>}
* The features returned in the response by the server. Depending on the
* protocol's read payload, either features or data will be populated.
*/
features: null,
/**
* Property: data
* {Object}
* The data returned in the response by the server. Depending on the
* protocol's read payload, either features or data will be populated.
*/
data: null,
/**
* Property: reqFeatures
* {Array({<OpenLayers.Feature.Vector>})} or {<OpenLayers.Feature.Vector>}
* The features provided by the user and placed in the request by the
* protocol.
*/
reqFeatures: null,
/**
* Property: priv
*/
priv: null,
/**
* Property: error
* {Object} The error object in case a service exception was encountered.
*/
error: null,
/**
* Constructor: OpenLayers.Protocol.Response
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*/
initialize: function(options) {
OpenLayers.Util.extend(this, options);
},
/**
* Method: success
*
* Returns:
* {Boolean} - true on success, false otherwise
*/
success: function() {
return this.code > 0;
},
CLASS_NAME: "OpenLayers.Protocol.Response"
});
OpenLayers.Protocol.Response.SUCCESS = 1;
OpenLayers.Protocol.Response.FAILURE = 0;
|
(function($){
if(webshims.support.texttrackapi && document.addEventListener){
var trackOptions = webshims.cfg.track;
var trackListener = function(e){
$(e.target).filter('track').each(changeApi);
};
var trackBugs = webshims.bugs.track;
var changeApi = function(){
if(trackBugs || (!trackOptions.override && $.prop(this, 'readyState') == 3)){
trackOptions.override = true;
webshims.reTest('track');
document.removeEventListener('error', trackListener, true);
if(this && $.nodeName(this, 'track')){
webshims.error("track support was overwritten. Please check your vtt including your vtt mime-type");
} else {
webshims.info("track support was overwritten. due to bad browser support");
}
return false;
}
};
var detectTrackError = function(){
document.addEventListener('error', trackListener, true);
if(trackBugs){
changeApi();
} else {
$('track').each(changeApi);
}
if(!trackBugs && !trackOptions.override){
webshims.defineProperty(TextTrack.prototype, 'shimActiveCues', {
get: function(){
return this._shimActiveCues || this.activeCues;
}
});
}
};
if(!trackOptions.override){
$(detectTrackError);
}
}
})(webshims.$);
webshims.register('track-ui', function($, webshims, window, document, undefined){
"use strict";
var options = webshims.cfg.track;
var support = webshims.support;
//descriptions are not really shown, but they are inserted into the dom
var showTracks = {subtitles: 1, captions: 1, descriptions: 1};
var mediaelement = webshims.mediaelement;
var usesNativeTrack = function(){
return !options.override && support.texttrackapi;
};
var trackDisplay = {
update: function(baseData, media){
if(!baseData.activeCues.length){
this.hide(baseData);
} else {
if(!compareArray(baseData.displayedActiveCues, baseData.activeCues)){
baseData.displayedActiveCues = baseData.activeCues;
if(!baseData.trackDisplay){
baseData.trackDisplay = $('<div class="cue-display '+webshims.shadowClass+'"><span class="description-cues" aria-live="assertive" /></div>').insertAfter(media);
this.addEvents(baseData, media);
webshims.docObserve();
}
if(baseData.hasDirtyTrackDisplay){
media.triggerHandler('forceupdatetrackdisplay');
}
this.showCues(baseData);
}
}
},
showCues: function(baseData){
var element = $('<span class="cue-wrapper" />');
$.each(baseData.displayedActiveCues, function(i, cue){
var id = (cue.id) ? 'id="cue-id-'+cue.id +'"' : '';
var cueHTML = $('<span class="cue-line"><span '+ id+ ' class="cue" /></span>').find('span').html(cue.getCueAsHTML()).end();
if(cue.track.kind == 'descriptions'){
setTimeout(function(){
$('span.description-cues', baseData.trackDisplay).html(cueHTML);
}, 0);
} else {
element.prepend(cueHTML);
}
});
$('span.cue-wrapper', baseData.trackDisplay).remove();
baseData.trackDisplay.append(element);
},
addEvents: function(baseData, media){
if(options.positionDisplay){
var timer;
var positionDisplay = function(_force){
if(baseData.displayedActiveCues.length || _force === true){
baseData.trackDisplay.css({display: 'none'});
var uiElement = media.getShadowElement();
var uiHeight = uiElement.innerHeight();
var uiWidth = uiElement.innerWidth();
var position = uiElement.position();
baseData.trackDisplay.css({
left: position.left,
width: uiWidth,
height: uiHeight - 45,
top: position.top,
display: 'block'
});
baseData.trackDisplay.css('fontSize', Math.max(Math.round(uiHeight / 30), 7));
baseData.hasDirtyTrackDisplay = false;
} else {
baseData.hasDirtyTrackDisplay = true;
}
};
var delayed = function(e){
clearTimeout(timer);
timer = setTimeout(positionDisplay, 0);
};
var forceUpdate = function(){
positionDisplay(true);
};
media.on('playerdimensionchange mediaelementapichange updatetrackdisplay updatemediaelementdimensions swfstageresize', delayed);
media.on('forceupdatetrackdisplay', forceUpdate).onWSOff('updateshadowdom', delayed);
forceUpdate();
}
},
hide: function(baseData){
if(baseData.trackDisplay && baseData.displayedActiveCues.length){
baseData.displayedActiveCues = [];
$('span.cue-wrapper', baseData.trackDisplay).remove();
$('span.description-cues', baseData.trackDisplay).empty();
}
}
};
function compareArray(a1, a2){
var ret = true;
var i = 0;
var len = a1.length;
if(len != a2.length){
ret = false;
} else {
for(; i < len; i++){
if(a1[i] != a2[i]){
ret = false;
break;
}
}
}
return ret;
}
mediaelement.trackDisplay = trackDisplay;
if(!mediaelement.createCueList){
var cueListProto = {
getCueById: function(id){
var cue = null;
for(var i = 0, len = this.length; i < len; i++){
if(this[i].id === id){
cue = this[i];
break;
}
}
return cue;
}
};
mediaelement.createCueList = function(){
return $.extend([], cueListProto);
};
}
mediaelement.getActiveCue = function(track, media, time, baseData){
if(!track._lastFoundCue){
track._lastFoundCue = {index: 0, time: 0};
}
if(support.texttrackapi && !options.override && !track._shimActiveCues){
track._shimActiveCues = mediaelement.createCueList();
}
var i = 0;
var len;
var cue;
for(; i < track.shimActiveCues.length; i++){
cue = track.shimActiveCues[i];
if(cue.startTime > time || cue.endTime < time){
track.shimActiveCues.splice(i, 1);
i--;
if(cue.pauseOnExit){
$(media).pause();
}
$(track).triggerHandler('cuechange');
$(cue).triggerHandler('exit');
} else if(track.mode == 'showing' && showTracks[track.kind] && $.inArray(cue, baseData.activeCues) == -1){
baseData.activeCues.push(cue);
}
}
len = track.cues.length;
i = track._lastFoundCue.time < time ? track._lastFoundCue.index : 0;
for(; i < len; i++){
cue = track.cues[i];
if(cue.startTime <= time && cue.endTime >= time && $.inArray(cue, track.shimActiveCues) == -1){
track.shimActiveCues.push(cue);
if(track.mode == 'showing' && showTracks[track.kind]){
baseData.activeCues.push(cue);
}
$(track).triggerHandler('cuechange');
$(cue).triggerHandler('enter');
track._lastFoundCue.time = time;
track._lastFoundCue.index = i;
}
if(cue.startTime > time){
break;
}
}
};
if(usesNativeTrack()){
(function(){
var block;
var triggerDisplayUpdate = function(elem){
block = true;
setTimeout(function(){
$(elem).triggerHandler('updatetrackdisplay');
block = false;
}, 9);
};
var createUpdateFn = function(nodeName, prop, type){
var superType = '_sup'+type;
var desc = {prop: {}};
var superDesc;
desc.prop[type] = function(){
if(!block && usesNativeTrack()){
triggerDisplayUpdate($(this).closest('audio, video'));
}
return superDesc.prop[superType].apply(this, arguments);
};
superDesc = webshims.defineNodeNameProperty(nodeName, prop, desc);
};
createUpdateFn('track', 'track', 'get');
['audio', 'video'].forEach(function(nodeName){
createUpdateFn(nodeName, 'textTracks', 'get');
createUpdateFn('nodeName', 'addTextTrack', 'value');
});
})();
$.propHooks.activeCues = {
get: function(obj){
return obj._shimActiveCues || obj.activeCues;
}
};
}
webshims.addReady(function(context, insertedElement){
$('video, audio', context)
.add(insertedElement.filter('video, audio'))
.filter(function(){
return webshims.implement(this, 'trackui');
})
.each(function(){
var baseData, trackList, updateTimer, updateTimer2;
var elem = $(this);
var getDisplayCues = function(e){
var track;
var time;
if(!trackList || !baseData){
trackList = elem.prop('textTracks');
baseData = webshims.data(elem[0], 'mediaelementBase') || webshims.data(elem[0], 'mediaelementBase', {});
if(!baseData.displayedActiveCues){
baseData.displayedActiveCues = [];
}
}
if (!trackList){return;}
time = elem.prop('currentTime');
if(!time && time !== 0){return;}
baseData.activeCues = [];
for(var i = 0, len = trackList.length; i < len; i++){
track = trackList[i];
if(track.mode != 'disabled' && track.cues && track.cues.length){
mediaelement.getActiveCue(track, elem, time, baseData);
}
}
trackDisplay.update(baseData, elem);
};
var onUpdate = function(e){
clearTimeout(updateTimer);
if(e){
if(e.type == 'timeupdate'){
getDisplayCues();
}
updateTimer2 = setTimeout(onUpdate, 90);
} else {
updateTimer = setTimeout(getDisplayCues, 9);
}
};
var addTrackView = function(){
if(!trackList) {
trackList = elem.prop('textTracks');
}
//as soon as change on trackList is implemented in all browsers we do not need to have 'updatetrackdisplay' anymore
$( [trackList] ).on('change', onUpdate);
elem
.off('.trackview')
.on('play.trackview timeupdate.trackview updatetrackdisplay.trackview', onUpdate)
;
};
elem.on('remove', function(e){
if(!e.originalEvent && baseData && baseData.trackDisplay){
setTimeout(function(){
baseData.trackDisplay.remove();
}, 4);
}
});
if(!usesNativeTrack()){
addTrackView();
} else {
if(elem.hasClass('nonnative-api-active')){
addTrackView();
}
elem
.on('mediaelementapichange trackapichange', function(){
if(!usesNativeTrack() || elem.hasClass('nonnative-api-active')){
addTrackView();
} else {
clearTimeout(updateTimer);
clearTimeout(updateTimer2);
trackList = elem.prop('textTracks');
baseData = webshims.data(elem[0], 'mediaelementBase') || webshims.data(elem[0], 'mediaelementBase', {});
$.each(trackList, function(i, track){
if(track._shimActiveCues){
delete track._shimActiveCues;
}
});
trackDisplay.hide(baseData);
elem.off('.trackview');
}
})
;
}
})
;
});
});
|
/*
Highcharts JS v5.0.13 (2017-07-27)
(c) 2009-2017 Highsoft AS
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?module.exports=a:a(Highcharts)})(function(a){a.theme={colors:["#FDD089","#FF7F79","#A0446E","#251535"],colorAxis:{maxColor:"#60042E",minColor:"#FDD089"},plotOptions:{map:{nullColor:"#fefefc"}},navigator:{series:{color:"#FF7F79",lineColor:"#A0446E"}}};a.setOptions(a.theme)});
|
/*! lazysizes - v1.2.3-rc1 */
!function(a){"use strict";var b,c,d,e;a.addEventListener&&(b=a.lazySizes&&lazySizes.cfg||a.lazySizesConfig||{},c=b.lazyClass||"lazyload",d=function(){var b,d;if("string"==typeof c&&(c=document.getElementsByClassName(c)),a.lazySizes)for(b=0,d=c.length;d>b;b++)lazySizes.loader.unveil(c[b])},addEventListener("beforeprint",d,!1),!("onbeforeprint"in a)&&a.matchMedia&&(e=matchMedia("print"))&&e.addListener&&e.addListener(function(){e.matches&&d()}))}(window); |
/**
* A date picker component which shows a Date Picker on the screen. This class extends from {@link Ext.picker.Picker}
* and {@link Ext.Sheet} so it is a popup.
*
* This component has no required configurations.
*
* ## Examples
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date');
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You may want to adjust the {@link #yearFrom} and {@link #yearTo} properties:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* yearFrom: 2000,
* yearTo : 2015
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You can set the value of the {@link Ext.picker.Date} to the current date using `new Date()`:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* value: new Date()
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* And you can hide the titles from each of the slots by using the {@link #useTitles} configuration:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* useTitles: false
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*/
Ext.define('Ext.picker.Date', {
extend: 'Ext.picker.Picker',
xtype: 'datepicker',
alternateClassName: 'Ext.DatePicker',
requires: ['Ext.DateExtras', 'Ext.util.InputBlocker'],
/**
* @event change
* Fired when the value of this picker has changed and the done button is pressed.
* @param {Ext.picker.Date} this This Picker
* @param {Date} value The date value
*/
config: {
/**
* @cfg {Number} yearFrom
* The start year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearFrom: 1980,
/**
* @cfg {Number} [yearTo=new Date().getFullYear()]
* The last year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearTo: new Date().getFullYear(),
/**
* @cfg {String} monthText
* The label to show for the month column.
* @accessor
*/
monthText: 'Month',
/**
* @cfg {String} dayText
* The label to show for the day column.
* @accessor
*/
dayText: 'Day',
/**
* @cfg {String} yearText
* The label to show for the year column.
* @accessor
*/
yearText: 'Year',
/**
* @cfg {Array} slotOrder
* An array of strings that specifies the order of the slots.
* @accessor
*/
slotOrder: ['month', 'day', 'year'],
/**
* @cfg {Object/Date} value
* Default value for the field and the internal {@link Ext.picker.Date} component. Accepts an object of 'year',
* 'month' and 'day' values, all of which should be numbers, or a {@link Date}.
*
* Examples:
*
* - `{year: 1989, day: 1, month: 5}` = 1st May 1989
* - `new Date()` = current date
* @accessor
*/
/**
* @cfg {Array} slots
* @hide
* @accessor
*/
/**
* @cfg {String/Mixed} doneButton
* Can be either:
*
* - A {String} text to be used on the Done button.
* - An {Object} as config for {@link Ext.Button}.
* - `false` or `null` to hide it.
* @accessor
*/
doneButton: true
},
platformConfig: [{
theme: ['Windows'],
doneButton: {
iconCls: 'check2',
ui: 'round',
text: ''
}
}],
initialize: function() {
this.callParent();
this.on({
scope: this,
delegate: '> slot',
slotpick: this.onSlotPick
});
this.on({
scope: this,
show: this.onSlotPick
});
},
setValue: function(value, animated) {
if (Ext.isDate(value)) {
value = {
day : value.getDate(),
month: value.getMonth() + 1,
year : value.getFullYear()
};
}
this.callParent([value, animated]);
this.onSlotPick();
},
getValue: function(useDom) {
var values = {},
items = this.getItems().items,
ln = items.length,
daysInMonth, day, month, year, item, i;
for (i = 0; i < ln; i++) {
item = items[i];
if (item instanceof Ext.picker.Slot) {
values[item.getName()] = item.getValue(useDom);
}
}
//if all the slots return null, we should not return a date
if (values.year === null && values.month === null && values.day === null) {
return null;
}
year = Ext.isNumber(values.year) ? values.year : 1;
month = Ext.isNumber(values.month) ? values.month : 1;
day = Ext.isNumber(values.day) ? values.day : 1;
if (month && year && month && day) {
daysInMonth = this.getDaysInMonth(month, year);
}
day = (daysInMonth) ? Math.min(day, daysInMonth): day;
return new Date(year, month - 1, day);
},
/**
* Updates the yearFrom configuration
*/
updateYearFrom: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the yearTo configuration
*/
updateYearTo: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the monthText configuration
*/
updateMonthText: function(newMonthText, oldMonthText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldMonthText) || (item.title.html == oldMonthText)) {
item.setTitle(newMonthText);
}
}
}
},
/**
* Updates the {@link #dayText} configuration.
*/
updateDayText: function(newDayText, oldDayText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldDayText) || (item.title.html == oldDayText)) {
item.setTitle(newDayText);
}
}
}
},
/**
* Updates the yearText configuration
*/
updateYearText: function(yearText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if (item.title == this.yearText) {
item.setTitle(yearText);
}
}
}
},
// @private
constructor: function() {
this.callParent(arguments);
this.createSlots();
},
/**
* Generates all slots for all years specified by this component, and then sets them on the component
* @private
*/
createSlots: function() {
var me = this,
slotOrder = me.getSlotOrder(),
yearsFrom = me.getYearFrom(),
yearsTo = me.getYearTo(),
years = [],
days = [],
months = [],
reverse = yearsFrom > yearsTo,
ln, i, daysInMonth;
while (yearsFrom) {
years.push({
text : yearsFrom,
value : yearsFrom
});
if (yearsFrom === yearsTo) {
break;
}
if (reverse) {
yearsFrom--;
} else {
yearsFrom++;
}
}
daysInMonth = me.getDaysInMonth(1, new Date().getFullYear());
for (i = 0; i < daysInMonth; i++) {
days.push({
text : i + 1,
value : i + 1
});
}
for (i = 0, ln = Ext.Date.monthNames.length; i < ln; i++) {
months.push({
text : Ext.Date.monthNames[i],
value : i + 1
});
}
var slots = [];
slotOrder.forEach(function (item) {
slots.push(me.createSlot(item, days, months, years));
});
me.setSlots(slots);
},
/**
* Returns a slot config for a specified date.
* @private
*/
createSlot: function(name, days, months, years) {
switch (name) {
case 'year':
return {
name: 'year',
align: 'center',
data: years,
title: this.getYearText(),
flex: 3
};
case 'month':
return {
name: name,
align: 'right',
data: months,
title: this.getMonthText(),
flex: 4
};
case 'day':
return {
name: 'day',
align: 'center',
data: days,
title: this.getDayText(),
flex: 2
};
}
},
onSlotPick: function() {
var value = this.getValue(true),
slot = this.getDaySlot(),
year = value.getFullYear(),
month = value.getMonth(),
days = [],
daysInMonth, i;
if (!value || !Ext.isDate(value) || !slot) {
return;
}
this.callParent(arguments);
//get the new days of the month for this new date
daysInMonth = this.getDaysInMonth(month + 1, year);
for (i = 0; i < daysInMonth; i++) {
days.push({
text: i + 1,
value: i + 1
});
}
// We don't need to update the slot days unless it has changed
if (slot.getStore().getCount() == days.length) {
return;
}
slot.getStore().setData(days);
// Now we have the correct amount of days for the day slot, lets update it
var store = slot.getStore(),
viewItems = slot.getViewItems(),
valueField = slot.getValueField(),
index, item;
index = store.find(valueField, value.getDate());
if (index == -1) {
return;
}
item = Ext.get(viewItems[index]);
slot.selectedIndex = index;
slot.scrollToItem(item);
slot.setValue(slot.getValue(true));
},
getDaySlot: function() {
var innerItems = this.getInnerItems(),
ln = innerItems.length,
i, slot;
if (this.daySlot) {
return this.daySlot;
}
for (i = 0; i < ln; i++) {
slot = innerItems[i];
if (slot.isSlot && slot.getName() == "day") {
this.daySlot = slot;
return slot;
}
}
return null;
},
// @private
getDaysInMonth: function(month, year) {
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return month == 2 && this.isLeapYear(year) ? 29 : daysInMonth[month-1];
},
// @private
isLeapYear: function(year) {
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
},
onDoneButtonTap: function() {
var oldValue = this._value,
newValue = this.getValue(true),
testValue = newValue;
if (Ext.isDate(newValue)) {
testValue = newValue.toDateString();
}
if (Ext.isDate(oldValue)) {
oldValue = oldValue.toDateString();
}
if (testValue != oldValue) {
this.fireEvent('change', this, newValue);
}
this.hide();
Ext.util.InputBlocker.unblockInputs();
}
}); |
function acosh (arg) {
// http://kevin.vanzonneveld.net
// + original by: Onno Marsman
// * example 1: acosh(8723321.4);
// * returns 1: 16.674657798418625
return Math.log(arg + Math.sqrt(arg * arg - 1));
}
|
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('router', function (Y, NAME) {
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
@module app
@submodule router
@since 3.4.0
**/
var HistoryHash = Y.HistoryHash,
QS = Y.QueryString,
YArray = Y.Array,
YLang = Y.Lang,
YObject = Y.Object,
win = Y.config.win,
// Holds all the active router instances. This supports the static
// `dispatch()` method which causes all routers to dispatch.
instances = [],
// We have to queue up pushState calls to avoid race conditions, since the
// popstate event doesn't actually provide any info on what URL it's
// associated with.
saveQueue = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
History event handle for the `history:change` or `hashchange` event
subscription.
@property _historyEvents
@type EventHandle
@protected
**/
/**
Cached copy of the `html5` attribute for internal use.
@property _html5
@type Boolean
@protected
**/
/**
Map which holds the registered param handlers in the form:
`name` -> RegExp | Function.
@property _params
@type Object
@protected
@since 3.12.0
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to break up a URL string around the URL's path.
Subpattern captures:
1. Origin, everything before the URL's path-part.
2. The URL's path-part.
3. The URL's query.
4. The URL's hash fragment.
@property _regexURL
@type RegExp
@protected
@since 3.5.0
**/
_regexURL: /^((?:[^\/#?:]+:\/\/|\/\/)[^\/]*)?([^?#]*)(\?[^#]*)?(#.*)?$/,
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
/**
Collection of registered routes.
@property _routes
@type Array
@protected
**/
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._html5 = self.get('html5');
self._params = {};
self._routes = [];
self._url = self._getURL();
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Set up a history instance or hashchange listener.
if (self._html5) {
self._history = new Y.HistoryHTML5({force: true});
self._historyEvents =
Y.after('history:change', self._afterHistoryChange, self);
} else {
self._historyEvents =
Y.on('hashchange', self._afterHistoryChange, win, self);
}
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish, then for window.onload, and then an
// additional 20ms to allow the browser to fire a useless initial
// `popstate` event if it wants to (and Chrome always wants to).
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
Y.once('load', function () {
setTimeout(function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
}, 20);
});
});
// Store this router in the collection of all active router instances.
instances.push(this);
},
destructor: function () {
var instanceIndex = YArray.indexOf(instances, this);
// Remove this router from the collection of active router instances.
if (instanceIndex > -1) {
instances.splice(instanceIndex, 1);
}
if (this._historyEvents) {
this._historyEvents.detach();
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function () {
this.once(EVT_READY, function () {
var req, res;
this._ready = true;
if (!this.upgrade()) {
req = this._getRequest('dispatch');
res = this._getResponse(req);
this._dispatch(req, res);
}
});
return this;
},
/**
Gets the current route path.
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this._getPath();
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise. This also checks that any named `param`
handlers also accept app param values in the `url`.
This method enforces the same-origin security constraint on the specified
`url`; any URL which is not from the same origin as the current URL will
always return `false`.
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url) {
var path, routePath, routes;
if (!this._hasSameOrigin(url)) {
return false;
}
if (!this._html5) {
url = this._upgradeURL(url);
}
// Get just the path portion of the specified `url`. The `match()`
// method does some special checking that the `path` is within the root.
path = this.removeQuery(url.replace(this._regexUrlOrigin, ''));
routes = this.match(path);
if (!routes.length) {
return false;
}
routePath = this.removeRoot(path);
// Check that there's at least one route whose param handlers also
// accept all the param values.
return !!YArray.filter(routes, function (route) {
// Get the param values for the route and path to see whether the
// param handlers accept or reject the param values. Include any
// route whose named param handlers accept *all* param values. This
// will return `false` if a param handler rejects a param value.
return this._getParamValues(route, routePath);
}, this).length;
},
/**
Returns an array of route objects that match the specified URL path.
If this router has a `root`, then the specified `path` _must_ be
semantically within the `root` path to match any routes.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match. This should be an absolute path that
starts with a slash: "/".
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path) {
var root = this.get('root');
if (root) {
// The `path` must be semantically within this router's `root` path
// or mount point, if it's not then no routes should be considered a
// match.
if (!this._pathHasRoot(root, path)) {
return [];
}
// Remove this router's `root` from the `path` before checking the
// routes for any matches.
path = this.removeRoot(path);
}
return YArray.filter(this._routes, function (route) {
return path.search(route.regex) > -1;
});
},
/**
Adds a handler for a route param specified by _name_.
Param handlers can be registered via this method and are used to
validate/format values of named params in routes before dispatching to the
route's handler functions. Using param handlers allows routes to defined
using string paths which allows for `req.params` to use named params, but
still applying extra validation or formatting to the param values parsed
from the URL.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped. All
other return values will be used in place of the original param value parsed
from the URL.
@example
router.param('postId', function (value) {
return parseInt(value, 10);
});
router.param('username', /^\w+$/);
router.route('/posts/:postId', function (req) {
});
router.route('/users/:username', function (req) {
// `req.params.username` is an array because the result of calling
// `exec()` on the regex is assigned as the param's value.
});
router.route('*', function () {
});
// URLs which match routes:
router.save('/posts/1'); // => "Post: 1"
router.save('/users/ericf'); // => "User: ericf"
// URLs which do not match routes because params fail validation:
router.save('/posts/a'); // => "Catch-all no routes matched!"
router.save('/users/ericf,rgrove'); // => "Catch-all no routes matched!"
@method param
@param {String} name Name of the param used in route paths.
@param {Function|RegExp} handler Function to invoke or regular expression to
`exec()` during route dispatching whose return value is used as the new
param value. Values of `false`, `null`, `undefined`, or `NaN` will cause
the current route to not match and be skipped. When a function is
specified, it will be invoked in the context of this instance with the
following parameters:
@param {String} handler.value The current param value parsed from the URL.
@param {String} handler.name The name of the param.
@chainable
@since 3.12.0
**/
param: function (name, handler) {
this._params[name] = handler;
return this;
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root'),
path;
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
// Return the host-less URL if there's no `root` path to further remove.
if (!root) {
return url;
}
path = this.removeQuery(url);
// Remove the `root` from the `url` if it's the same or its path is
// semantically within the root path.
if (path === root || this._pathHasRoot(root, path)) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Removes a query string from the end of the _url_ (if one exists) and returns
the result.
@method removeQuery
@param {String} url URL.
@return {String} Queryless path.
**/
removeQuery: function (url) {
return url.replace(/\?.*$/, '');
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._queue(url, true);
},
/**
Adds a route handler for the specified `route`.
The `route` parameter may be a string or regular expression to represent a
URL path, or a route object. If it's a string (which is most common), it may
contain named parameters: `:param` will match any single part of a URL path
(not including `/` characters), and `*param` will match any number of parts
of a URL path (including `/` characters). These named parameters will be
made available as keys on the `req.params` object that's passed to route
handlers.
If the `route` parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Alternatively, an object can be provided to represent the route and it may
contain a `path` property which is a string or regular expression which
causes the route to be process as described above. If the route object
already contains a `regex` or `regexp` property, the route will be
considered fully-processed and will be associated with any `callacks`
specified on the object and those specified as parameters to this method.
**Note:** Any additional data contained on the route object will be
preserved.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
**Middleware**: Routes also support an arbitrary number of callback
functions. This allows you to easily reuse parts of your route-handling code
with different route. This method is liberal in how it processes the
specified `callbacks`, you can specify them as separate arguments, or as
arrays, or both.
If multiple route match a given URL, they will be executed in the order they
were added. The first route that was added will be the first to be executed.
**Passing Control**: Invoking the `next()` function within a route callback
will pass control to the next callback function (if any) or route handler
(if any). If a value is passed to `next()`, it's assumed to be an error,
therefore stopping the dispatch chain, unless that value is: `"route"`,
which is special case and dispatching will skip to the next route handler.
This allows middleware to skip any remaining middleware for a particular
route.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
});
// Using middleware.
router.findUser = function (req, res, next) {
req.user = this.get('users').findById(req.params.user);
next();
};
router.route('/users/:user', 'findUser', function (req, res, next) {
// The `findUser` middleware puts the `user` object on the `req`.
});
@method route
@param {String|RegExp|Object} route Route to match. May be a string or a
regular expression, or a route object.
@param {Array|Function|String} callbacks* Callback functions to call
whenever this route is triggered. These can be specified as separate
arguments, or in arrays, or both. If a callback is specified as a
string, the named function will be called on this router instance.
@param {Object} callbacks.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callbacks.req.params Captured parameters matched
by the route path specification. If a string path was used and
contained named parameters, then this will be a key/value hash mapping
parameter names to their matched values. If a regex path was used,
this will be an array of subpattern matches starting at index 0 for
the full match, then 1 for the first subpattern match, and so on.
@param {String} callbacks.req.path The current URL path.
@param {Number} callbacks.req.pendingCallbacks Number of remaining
callbacks the route handler has after this one in the dispatch chain.
@param {Number} callbacks.req.pendingRoutes Number of matching routes
after this one in the dispatch chain.
@param {Object} callbacks.req.query Query hash representing the URL
query string, if any. Parameter names are keys, and are mapped to
parameter values.
@param {Object} callbacks.req.route Reference to the current route
object whose callbacks are being dispatched.
@param {Object} callbacks.req.router Reference to this router instance.
@param {String} callbacks.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate". When the `dispath()` method is
called, the `src` will be `"dispatch"`.
@param {String} callbacks.req.url The full URL.
@param {Object} callbacks.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callbacks.res.req Reference to the request object.
@param {Function} callbacks.next Function to pass control to the next
callback or the next matching route if no more callbacks (middleware)
exist for the current route handler. If you don't call this function,
then no further callbacks or route handlers will be executed, even if
there are more that match. If you do call this function, then the next
callback (if any) or matching route handler (if any) will be called.
All of these functions will receive the same `req` and `res` objects
that were passed to this route (so you can use these objects to pass
data along to subsequent callbacks and routes).
@param {String} [callbacks.next.err] Optional error which will stop the
dispatch chaining for this `req`, unless the value is `"route"`, which
is special cased to jump skip past any callbacks for the current route
and pass control the next route handler.
@chainable
**/
route: function (route, callbacks) {
// Grab callback functions from var-args.
callbacks = YArray(arguments, 1, true);
var keys, regex;
// Supports both the `route(path, callbacks)` and `route(config)` call
// signatures, allowing for fully-processed route configs to be passed.
if (typeof route === 'string' || YLang.isRegExp(route)) {
// Flatten `callbacks` into a single dimension array.
callbacks = YArray.flatten(callbacks);
keys = [];
regex = this._getRegex(route, keys);
route = {
callbacks: callbacks,
keys : keys,
path : route,
regex : regex
};
} else {
// Look for any configured `route.callbacks` and fallback to
// `route.callback` for back-compat, append var-arg `callbacks`,
// then flatten the entire collection to a single dimension array.
callbacks = YArray.flatten(
[route.callbacks || route.callback || []].concat(callbacks)
);
// Check for previously generated regex, also fallback to `regexp`
// for greater interop.
keys = route.keys;
regex = route.regex || route.regexp;
// Generates the route's regex if it doesn't already have one.
if (!regex) {
keys = [];
regex = this._getRegex(route.path, keys);
}
// Merge specified `route` config object with processed data.
route = Y.merge(route, {
callbacks: callbacks,
keys : keys,
path : route.path || regex,
regex : regex
});
}
this._routes.push(route);
return this;
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
save: function (url) {
return this._queue(url);
},
/**
Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
browsers, this method is a noop.
@method upgrade
@return {Boolean} `true` if the URL was upgraded, `false` otherwise.
**/
upgrade: function () {
if (!this._html5) {
return false;
}
// Get the resolve hash path.
var hashPath = this._getHashPath();
if (hashPath) {
// This is an HTML5 browser and we have a hash-based path in the
// URL, so we need to upgrade the URL to a non-hash URL. This
// will trigger a `history:change` event, which will in turn
// trigger a dispatch.
this.once(EVT_READY, function () {
this.replace(hashPath);
});
return true;
}
return false;
},
// -- Protected Methods ----------------------------------------------------
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Shifts the topmost `_save()` call off the queue and executes it. Does
nothing if the queue is empty.
@method _dequeue
@chainable
@see _queue
@protected
**/
_dequeue: function () {
var self = this,
fn;
// If window.onload hasn't yet fired, wait until it has before
// dequeueing. This will ensure that we don't call pushState() before an
// initial popstate event has fired.
if (!YUI.Env.windowLoaded) {
Y.once('load', function () {
self._dequeue();
});
return this;
}
fn = saveQueue.shift();
return fn ? fn() : this;
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {object} req Request object.
@param {String} res Response object.
@chainable
@protected
**/
_dispatch: function (req, res) {
var self = this,
routes = self.match(req.path),
callbacks = [],
routePath, paramValues;
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
routePath = self.removeRoot(req.path);
function next(err) {
var callback, name, route;
if (err) {
// Special case "route" to skip to the next route handler
// avoiding any additional callbacks for the current route.
if (err === 'route') {
callbacks = [];
next();
} else {
Y.error(err);
}
} else if ((callback = callbacks.shift())) {
if (typeof callback === 'string') {
name = callback;
callback = self[name];
if (!callback) {
Y.error('Router: Callback not found: ' + name, null, 'router');
}
}
// Allow access to the number of remaining callbacks for the
// route.
req.pendingCallbacks = callbacks.length;
callback.call(self, req, res, next);
} else if ((route = routes.shift())) {
paramValues = self._getParamValues(route, routePath);
if (!paramValues) {
// Skip this route because one of the param handlers
// rejected a param value in the `routePath`.
next('route');
return;
}
// Expose the processed param values.
req.params = paramValues;
// Allow access to current route and the number of remaining
// routes for this request.
req.route = route;
req.pendingRoutes = routes.length;
// Make a copy of this route's `callbacks` so the original array
// is preserved.
callbacks = route.callbacks.concat();
// Execute this route's `callbacks`.
next();
}
}
next();
self._dispatching = false;
return self._dequeue();
},
/**
Returns the resolved path from the hash fragment, or an empty string if the
hash is not path-like.
@method _getHashPath
@param {String} [hash] Hash fragment to resolve into a path. By default this
will be the hash from the current URL.
@return {String} Current hash path, or an empty string if the hash is empty.
@protected
**/
_getHashPath: function (hash) {
hash || (hash = HistoryHash.getHash());
// Make sure the `hash` is path-like.
if (hash && hash.charAt(0) === '/') {
return this._joinURL(hash);
}
return '';
},
/**
Gets the location origin (i.e., protocol, host, and port) as a URL.
@example
http://example.com
@method _getOrigin
@return {String} Location origin (i.e., protocol, host, and port).
@protected
**/
_getOrigin: function () {
var location = Y.getLocation();
return location.origin || (location.protocol + '//' + location.host);
},
/**
Getter for the `params` attribute.
@method _getParams
@return {Object} Mapping of param handlers: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_getParams: function () {
return Y.merge(this._params);
},
/**
Gets the param values for the specified `route` and `path`, suitable to use
form `req.params`.
**Note:** This method will return `false` if a named param handler rejects a
param value.
@method _getParamValues
@param {Object} route The route to get param values for.
@param {String} path The route path (root removed) that provides the param
values.
@return {Boolean|Array|Object} The collection of processed param values.
Either a hash of `name` -> `value` for named params processed by this
router's param handlers, or an array of matches for a route with unnamed
params. If a named param handler rejects a value, then `false` will be
returned.
@protected
@since 3.16.0
**/
_getParamValues: function (route, path) {
var matches, paramsMatch, paramValues;
// Decode each of the path params so that the any URL-encoded path
// segments are decoded in the `req.params` object.
matches = YArray.map(route.regex.exec(path) || [], function (match) {
// Decode matches, or coerce `undefined` matches to an empty
// string to match expectations of working with `req.params`
// in the context of route dispatching, and normalize
// browser differences in their handling of regex NPCGs:
// https://github.com/yui/yui3/issues/1076
return (match && this._decode(match)) || '';
}, this);
// Simply return the array of decoded values when the route does *not*
// use named parameters.
if (matches.length - 1 !== route.keys.length) {
return matches;
}
// Remove the first "match" from the param values, because it's just the
// `path` processed by the route's regex, and map the values to the keys
// to create the name params collection.
paramValues = YArray.hash(route.keys, matches.slice(1));
// Pass each named param value to its handler, if there is one, for
// validation/processing. If a param value is rejected by a handler,
// then the params don't match and a falsy value is returned.
paramsMatch = YArray.every(route.keys, function (name) {
var paramHandler = this._params[name],
value = paramValues[name];
if (paramHandler && value && typeof value === 'string') {
// Check if `paramHandler` is a RegExp, because this
// is true in Android 2.3 and other browsers!
// `typeof /.*/ === 'function'`
value = YLang.isRegExp(paramHandler) ?
paramHandler.exec(value) :
paramHandler.call(this, value, name);
if (value !== false && YLang.isValue(value)) {
// Update the named param to the value from the handler.
paramValues[name] = value;
return true;
}
// Consider the param value as rejected by the handler.
return false;
}
return true;
}, this);
if (paramsMatch) {
return paramValues;
}
// Signal that a param value was rejected by a named param handler.
return false;
},
/**
Gets the current route path.
@method _getPath
@return {String} Current route path.
@protected
**/
_getPath: function () {
var path = (!this._html5 && this._getHashPath()) ||
Y.getLocation().pathname;
return this.removeQuery(path);
},
/**
Returns the current path root after popping off the last path segment,
making it useful for resolving other URL paths against.
The path root will always begin and end with a '/'.
@method _getPathRoot
@return {String} The URL's path root.
@protected
@since 3.5.0
**/
_getPathRoot: function () {
var slash = '/',
path = Y.getLocation().pathname,
segments;
if (path.charAt(path.length - 1) === slash) {
return path;
}
segments = path.split(slash);
segments.pop();
return segments.join(slash) + slash;
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function () {
var location = Y.getLocation(),
hash, matches;
if (this._html5) {
return location.search.substring(1);
}
hash = HistoryHash.getHash();
matches = hash.match(this._regexUrlQuery);
return hash && matches ? matches[1] : location.search.substring(1);
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (YLang.isRegExp(path)) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/#?]+)';
});
return new RegExp('^' + path + '$');
},
/**
Gets a request object that can be passed to a route handler.
@method _getRequest
@param {String} src What initiated the URL change and need for the request.
@return {Object} Request object.
@protected
**/
_getRequest: function (src) {
return {
path : this._getPath(),
query : this._parseQuery(this._getQuery()),
url : this._getURL(),
router: this,
src : src
};
},
/**
Gets a response object that can be passed to a route handler.
@method _getResponse
@param {Object} req Request object.
@return {Object} Response Object.
@protected
**/
_getResponse: function (req) {
return {req: req};
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Gets the current full URL.
@method _getURL
@return {String} URL.
@protected
**/
_getURL: function () {
var url = Y.getLocation().toString();
if (!this._html5) {
url = this._upgradeURL(url);
}
return url;
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
// Causes `url` to _always_ begin with a "/".
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Returns a normalized path, ridding it of any '..' segments and properly
handling leading and trailing slashes.
@method _normalizePath
@param {String} path URL path to normalize.
@return {String} Normalized path.
@protected
@since 3.5.0
**/
_normalizePath: function (path) {
var dots = '..',
slash = '/',
i, len, normalized, segments, segment, stack;
if (!path || path === slash) {
return slash;
}
segments = path.split(slash);
stack = [];
for (i = 0, len = segments.length; i < len; ++i) {
segment = segments[i];
if (segment === dots) {
stack.pop();
} else if (segment) {
stack.push(segment);
}
}
normalized = slash + stack.join(slash);
// Append trailing slash if necessary.
if (normalized !== slash && path.charAt(path.length - 1) === slash) {
normalized += slash;
}
return normalized;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Returns `true` when the specified `path` is semantically within the
specified `root` path.
If the `root` does not end with a trailing slash ("/"), one will be added
before the `path` is evaluated against the root path.
@example
this._pathHasRoot('/app', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/'); // => true
this._pathHasRoot('/app', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/app'); // => false
this._pathHasRoot('/app', '/app'); // => false
@method _pathHasRoot
@param {String} root Root path used to evaluate whether the specificed
`path` is semantically within. A trailing slash ("/") will be added if
it does not already end with one.
@param {String} path Path to evaluate for containing the specified `root`.
@return {Boolean} Whether or not the `path` is semantically within the
`root` path.
@protected
@since 3.13.0
**/
_pathHasRoot: function (root, path) {
var rootPath = root.charAt(root.length - 1) === '/' ? root : root + '/';
return path.indexOf(rootPath) === 0;
},
/**
Queues up a `_save()` call to run after all previously-queued calls have
finished.
This is necessary because if we make multiple `_save()` calls before the
first call gets dispatched, then both calls will dispatch to the last call's
URL.
All arguments passed to `_queue()` will be passed on to `_save()` when the
queued function is executed.
@method _queue
@chainable
@see _dequeue
@protected
**/
_queue: function () {
var args = arguments,
self = this;
saveQueue.push(function () {
if (self._html5) {
if (Y.UA.ios && Y.UA.ios < 5) {
// iOS <5 has buggy HTML5 history support, and needs to be
// synchronous.
self._save.apply(self, args);
} else {
// Wrapped in a timeout to ensure that _save() calls are
// always processed asynchronously. This ensures consistency
// between HTML5- and hash-based history.
setTimeout(function () {
self._save.apply(self, args);
}, 1);
}
} else {
self._dispatching = true; // otherwise we'll dequeue too quickly
self._save.apply(self, args);
}
return self;
});
return !this._dispatching ? this._dequeue() : this;
},
/**
Returns the normalized result of resolving the `path` against the current
path. Falsy values for `path` will return just the current path.
@method _resolvePath
@param {String} path URL path to resolve.
@return {String} Resolved path.
@protected
@since 3.5.0
**/
_resolvePath: function (path) {
if (!path) {
return Y.getLocation().pathname;
}
if (path.charAt(0) !== '/') {
path = this._getPathRoot() + path;
}
return this._normalizePath(path);
},
/**
Resolves the specified URL against the current URL.
This method resolves URLs like a browser does and will always return an
absolute URL. When the specified URL is already absolute, it is assumed to
be fully resolved and is simply returned as is. Scheme-relative URLs are
prefixed with the current protocol. Relative URLs are giving the current
URL's origin and are resolved and normalized against the current path root.
@method _resolveURL
@param {String} url URL to resolve.
@return {String} Resolved URL.
@protected
@since 3.5.0
**/
_resolveURL: function (url) {
var parts = url && url.match(this._regexURL),
origin, path, query, hash, resolved;
if (!parts) {
return Y.getLocation().toString();
}
origin = parts[1];
path = parts[2];
query = parts[3];
hash = parts[4];
// Absolute and scheme-relative URLs are assumed to be fully-resolved.
if (origin) {
// Prepend the current scheme for scheme-relative URLs.
if (origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return origin + (path || '/') + (query || '') + (hash || '');
}
// Will default to the current origin and current path.
resolved = this._getOrigin() + this._resolvePath(path);
// A path or query for the specified URL trumps the current URL's.
if (path || query) {
return resolved + (query || '') + (hash || '');
}
query = this._getQuery();
return resolved + (query ? ('?' + query) : '') + (hash || '');
},
/**
Saves a history entry using either `pushState()` or the location hash.
This method enforces the same-origin security constraint; attempting to save
a `url` that is not from the same origin as the current URL will result in
an error.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
**/
_save: function (url, replace) {
var urlIsString = typeof url === 'string',
currentPath, root, hash;
// Perform same-origin check on the specified URL.
if (urlIsString && !this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Joins the `url` with the `root`.
if (urlIsString) {
url = this._joinURL(url);
}
// Force _ready to true to ensure that the history change is handled
// even if _save is called before the `ready` event fires.
this._ready = true;
if (this._html5) {
this._history[replace ? 'replace' : 'add'](null, {url: url});
} else {
currentPath = Y.getLocation().pathname;
root = this.get('root');
hash = HistoryHash.getHash();
if (!urlIsString) {
url = hash;
}
// Determine if the `root` already exists in the current location's
// `pathname`, and if it does then we can exclude it from the
// hash-based path. No need to duplicate the info in the URL.
if (root === currentPath || root === this._getPathRoot()) {
url = this.removeRoot(url);
}
// The `hashchange` event only fires when the new hash is actually
// different. This makes sure we'll always dequeue and dispatch
// _all_ router instances, mimicking the HTML5 behavior.
if (url === hash) {
Y.Router.dispatch();
} else {
HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
}
}
return this;
},
/**
Setter for the `params` attribute.
@method _setParams
@param {Object} params Map in the form: `name` -> RegExp | Function.
@return {Object} The map of params: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_setParams: function (params) {
this._params = {};
YObject.each(params, function (regex, name) {
this.param(name, regex);
}, this);
return Y.merge(this._params);
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
YArray.each(routes, function (route) {
this.route(route);
}, this);
return this._routes.concat();
},
/**
Upgrades a hash-based URL to a full-path URL, if necessary.
The specified `url` will be upgraded if its of the same origin as the
current URL and has a path-like hash. URLs that don't need upgrading will be
returned as-is.
@example
app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
@method _upgradeURL
@param {String} url The URL to upgrade from hash-based to full-path.
@return {String} The upgraded URL, or the specified URL untouched.
@protected
@since 3.5.0
**/
_upgradeURL: function (url) {
// We should not try to upgrade paths for external URLs.
if (!this._hasSameOrigin(url)) {
return url;
}
var hash = (url.match(/#(.*)$/) || [])[1] || '',
hashPrefix = Y.HistoryHash.hashPrefix,
hashPath;
// Strip any hash prefix, like hash-bangs.
if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
hash = hash.replace(hashPrefix, '');
}
// If the hash looks like a URL path, assume it is, and upgrade it!
if (hash) {
hashPath = this._getHashPath(hash);
if (hashPath) {
return this._resolveURL(hashPath);
}
}
return url;
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `history:change` and `hashchange` events.
@method _afterHistoryChange
@param {EventFacade} e
@protected
**/
_afterHistoryChange: function (e) {
var self = this,
src = e.src,
prevURL = self._url,
currentURL = self._getURL(),
req, res;
self._url = currentURL;
// Handles the awkwardness that is the `popstate` event. HTML5 browsers
// fire `popstate` right before they fire `hashchange`, and Chrome fires
// `popstate` on page load. If this router is not ready or the previous
// and current URLs only differ by their hash, then we want to ignore
// this `popstate` event.
if (src === 'popstate' &&
(!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
return;
}
req = self._getRequest(src);
res = self._getResponse(req);
self._dispatch(req, res);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Map of params handlers in the form: `name` -> RegExp | Function.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped.
All other return values will be used in place of the original param
value parsed from the URL.
This attribute is intended to be used to set params at init time, or to
completely reset all params after init. To add params after init without
resetting all existing params, use the `param()` method.
@attribute params
@type Object
@default `{}`
@see param
@since 3.12.0
**/
params: {
value : {},
getter: '_getParams',
setter: '_setParams'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@example
router.set('root', '/myapp');
router.route('/foo', function () { ... });
// Updates the URL to: "/myapp/foo"
router.save('/foo');
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties
in order to be processed by the router:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callbacks`: Function or a string representing the name of a
function on this router instance that should be called when the
route is triggered. An array of functions and/or strings may also be
provided. See the docs for the `route()` method for more details.
If a route object contains a `regex` or `regexp` property, or if its
`path` is a regular express, then the route will be considered to be
fully-processed. Any fully-processed routes may contain the following
properties:
* `regex`: The regular expression representing the path to match, this
property may also be named `regexp` for greater compatibility.
* `keys`: Array of named path parameters used to populate `req.params`
objects when dispatching to route handlers.
Any additional data contained on these route objects will be retained.
This is useful to store extra metadata about a route; e.g., a `name` to
give routes logical names.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// Used as the default value for the `html5` attribute, and for testing.
html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3),
// To make this testable.
_instances: instances,
/**
Dispatches to the first route handler that matches the specified `path` for
all active router instances.
This provides a mechanism to cause all active router instances to dispatch
to their route handlers without needing to change the URL or fire the
`history:change` or `hashchange` event.
@method dispatch
@static
@since 3.6.0
**/
dispatch: function () {
var i, len, router, req, res;
for (i = 0, len = instances.length; i < len; i += 1) {
router = instances[i];
if (router) {
req = router._getRequest('dispatch');
res = router._getResponse(req);
router._dispatch(req, res);
}
}
}
});
/**
The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
`Router` class. Use that class instead. This alias will be removed in a future
version of YUI.
@class Controller
@constructor
@extends Base
@deprecated Use `Router` instead.
@see Router
**/
Y.Controller = Y.Router;
}, '3.16.0', {"optional": ["querystring-parse"], "requires": ["array-extras", "base-build", "history"]});
|
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
/**
* List compiled by mystix on the extjs.com forums.
* Thank you Mystix!
*/
/* Slovak Translation by Michal Thomka
* 14 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Nahrávam...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.GridPanel){
Ext.grid.GridPanel.prototype.ddText = "{0} označených riadkov";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "Zavrieť túto záložku";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "Hodnota v tomto poli je nesprávna";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "Nahrávam...";
}
Date.monthNames = [
"Január",
"Február",
"Marec",
"Apríl",
"Máj",
"Jún",
"Júl",
"August",
"September",
"Október",
"November",
"December"
];
Date.dayNames = [
"Nedeľa",
"Pondelok",
"Utorok",
"Streda",
"Štvrtok",
"Piatok",
"Sobota"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "OK",
cancel : "Zrušiť",
yes : "Áno",
no : "Nie"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "d.m.Y");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "Dnes",
minText : "Tento dátum je menší ako minimálny možný dátum",
maxText : "Tento dátum je väčší ako maximálny možný dátum",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'Ďalší Mesiac (Control+Doprava)',
prevText : 'Predch. Mesiac (Control+Doľava)',
monthYearText : 'Vyberte Mesiac (Control+Hore/Dole pre posun rokov)',
todayTip : "{0} (Medzerník)",
format : "d.m.Y"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "Strana",
afterPageText : "z {0}",
firstText : "Prvá Strana",
prevText : "Predch. Strana",
nextText : "Ďalšia Strana",
lastText : "Posledná strana",
refreshText : "Obnoviť",
displayMsg : "Zobrazujem {0} - {1} z {2}",
emptyMsg : 'iadne dáta'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "Minimálna dĺžka pre toto pole je {0}",
maxLengthText : "Maximálna dĺžka pre toto pole je {0}",
blankText : "Toto pole je povinné",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "Minimálna hodnota pre toto pole je {0}",
maxText : "Maximálna hodnota pre toto pole je {0}",
nanText : "{0} je nesprávne číslo"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "Zablokované",
disabledDatesText : "Zablokované",
minText : "Dátum v tomto poli musí byť až po {0}",
maxText : "Dátum v tomto poli musí byť pred {0}",
invalidText : "{0} nie je správny dátum - musí byť vo formáte {1}",
format : "d.m.Y"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "Nahrávam...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'Toto pole musí byť e-mailová adresa vo formáte "[email protected]"',
urlText : 'Toto pole musí byť URL vo formáte "http:/'+'/www.example.com"',
alphaText : 'Toto pole može obsahovať iba písmená a znak _',
alphanumText : 'Toto pole može obsahovať iba písmená, čísla a znak _'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "Zoradiť vzostupne",
sortDescText : "Zoradiť zostupne",
lockText : "Zamknúť stľpec",
unlockText : "Odomknúť stľpec",
columnsText : "Stľpce"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "Názov",
valueText : "Hodnota",
dateFormat : "d.m.Y"
});
}
if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "Potiahnite pre zmenu rozmeru",
collapsibleSplitTip : "Potiahnite pre zmenu rozmeru. Dvojklikom schováte."
});
}
|
import {Parser} from "./state"
import {SourceLocation} from "./locutil"
export class Node {
constructor(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
}
}
// Start an AST node, attaching a start offset.
const pp = Parser.prototype
pp.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class IgnorePlugin {
constructor(resourceRegExp, contextRegExp) {
this.resourceRegExp = resourceRegExp;
this.contextRegExp = contextRegExp;
this.checkIgnore = this.checkIgnore.bind(this);
}
/*
* Only returns true if a "resourceRegExp" exists
* and the resource given matches the regexp.
*/
checkResource(resource) {
if(!this.resourceRegExp) {
return false;
}
return this.resourceRegExp.test(resource);
}
/*
* Returns true if contextRegExp does not exist
* or if context matches the given regexp.
*/
checkContext(context) {
if(!this.contextRegExp) {
return true;
}
return this.contextRegExp.test(context);
}
/*
* Returns true if result should be ignored.
* false if it shouldn't.
*
* Not that if "contextRegExp" is given, both the "resourceRegExp"
* and "contextRegExp" have to match.
*/
checkResult(result) {
if(!result) {
return true;
}
return this.checkResource(result.request) && this.checkContext(result.context);
}
checkIgnore(result, callback) {
// check if result is ignored
if(this.checkResult(result)) {
return callback();
}
return callback(null, result);
}
apply(compiler) {
compiler.plugin("normal-module-factory", (nmf) => {
nmf.plugin("before-resolve", this.checkIgnore);
});
compiler.plugin("context-module-factory", (cmf) => {
cmf.plugin("before-resolve", this.checkIgnore);
});
}
}
module.exports = IgnorePlugin;
|
/*!
* Connect - cookieParser
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('./../utils')
, cookie = require('cookie');
/**
* Cookie parser:
*
* Parse _Cookie_ header and populate `req.cookies`
* with an object keyed by the cookie names. Optionally
* you may enabled signed cookie support by passing
* a `secret` string, which assigns `req.secret` so
* it may be used by other middleware.
*
* Examples:
*
* connect()
* .use(connect.cookieParser('optional secret string'))
* .use(function(req, res, next){
* res.end(JSON.stringify(req.cookies));
* })
*
* @param {String} secret
* @return {Function}
* @api public
*/
module.exports = function cookieParser(secret){
return function cookieParser(req, res, next) {
if (req.cookies) return next();
var cookies = req.headers.cookie;
req.secret = secret;
req.cookies = {};
req.signedCookies = {};
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
next();
};
};
|
YUI.add("lang/datatype-date-format_es-EC",function(a){a.Intl.add("datatype-date-format","es-EC",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %H:%M:%S %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%d/%m/%y","X":"%H:%M:%S"});},"@VERSION@"); |
/*! jQuery UI - v1.9.2 - 2012-11-23
* http://jqueryui.com
* Includes: jquery.ui.datepicker-ro.js
* Copyright 2012 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.ro={closeText:"Închide",prevText:"« Luna precedentă",nextText:"Luna următoare »",currentText:"Azi",monthNames:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"],monthNamesShort:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Duminică","Luni","Marţi","Miercuri","Joi","Vineri","Sâmbătă"],dayNamesShort:["Dum","Lun","Mar","Mie","Joi","Vin","Sâm"],dayNamesMin:["Du","Lu","Ma","Mi","Jo","Vi","Sâ"],weekHeader:"Săpt",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ro)}); |
/**
* @module Ink.UI.DatePicker_1
* @version 1
* Date selector
*/
Ink.createModule('Ink.UI.DatePicker', '1', ['Ink.UI.Common_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.Date_1', 'Ink.Dom.Browser_1'], function(Common, Event, Css, InkElement, Selector, InkArray, InkDate ) {
'use strict';
// Repeat a string. Long version of (new Array(n)).join(str);
function strRepeat(n, str) {
var ret = '';
for (var i = 0; i < n; i++) {
ret += str;
}
return ret;
}
// Clamp a number into a min/max limit
function clamp(n, min, max) {
if (n > max) { n = max; }
if (n < min) { n = min; }
return n;
}
function dateishFromYMDString(YMD) {
var split = YMD.split('-');
return dateishFromYMD(+split[0], +split[1] - 1, +split[2]);
}
function dateishFromYMD(year, month, day) {
return {_year: year, _month: month, _day: day};
}
function dateishFromDate(date) {
return {_year: date.getFullYear(), _month: date.getMonth(), _day: date.getDate()};
}
/**
* @class Ink.UI.DatePicker
* @constructor
* @version 1
*
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Boolean} [options.autoOpen] Flag to automatically open the datepicker.
* @param {String} [options.cleanText] Text for the clean button. Defaults to 'Limpar'.
* @param {String} [options.closeText] Text for the close button. Defaults to 'Fechar'.
* @param {String} [options.cssClass] CSS class to be applied on the datepicker
* @param {String} [options.dateRange] Enforce limits to year, month and day for the Date, ex: '1990-08-25:2020-11'
* @param {Boolean} [options.displayInSelect] Flag to display the component in a select element.
* @param {String|DOMElement} [options.dayField] (if using options.displayInSelect) `select` field with days.
* @param {String|DOMElement} [options.monthField] (if using options.displayInSelect) `select` field with months.
* @param {String|DOMElement} [options.yearField] (if using options.displayInSelect) `select` field with years.
* @param {String} [options.format] Date format string
* @param {String} [options.instance] Unique id for the datepicker
* @param {Object} [options.month] Hash of month names. Defaults to portuguese month names. January is 1.
* @param {String} [options.nextLinkText] Text for the previous button. Defaults to '«'.
* @param {String} [options.ofText] Text to show between month and year. Defaults to ' of '.
* @param {Boolean} [options.onFocus] If the datepicker should open when the target element is focused. Defaults to true.
* @param {Function} [options.onMonthSelected] Callback to execute when the month is selected.
* @param {Function} [options.onSetDate] Callback to execute when the date is set.
* @param {Function} [options.onYearSelected] Callback to execute when the year is selected.
* @param {String} [options.position] Position for the datepicker. Either 'right' or 'bottom'. Defaults to 'right'.
* @param {String} [options.prevLinkText] Text for the previous button. Defaults to '«'.
* @param {Boolean} [options.showClean] If the clean button should be visible. Defaults to true.
* @param {Boolean} [options.showClose] If the close button should be visible. Defaults to true.
* @param {Boolean} [options.shy] If the datepicker should start automatically. Defaults to true.
* @param {String} [options.startDate] Date to define initial month. Must be in yyyy-mm-dd format.
* @param {Number} [options.startWeekDay] First day of the week. Sunday is zero. Defaults to 1 (Monday).
* @param {Function} [options.validYearFn] Callback to execute when 'rendering' the month (in the month view)
* @param {Function} [options.validMonthFn] Callback to execute when 'rendering' the month (in the month view)
* @param {Function} [options.validDayFn] Callback to execute when 'rendering' the day (in the month view)
* @param {Function} [options.nextValidDateFn] Function to calculate the next valid date, given the current. Useful when there's invalid dates or time frames.
* @param {Function} [options.prevValidDateFn] Function to calculate the previous valid date, given the current. Useful when there's invalid dates or time frames.
* @param {Object} [options.wDay] Hash of weekdays. Defaults to portuguese names. Sunday is 0.
* @param {String} [options.yearRange] Enforce limits to year for the Date, ex: '1990:2020' (deprecated)
*
* @sample Ink_UI_DatePicker_1.html
*/
var DatePicker = function(selector, options) {
this._element = selector &&
Common.elOrSelector(selector, '[Ink.UI.DatePicker_1]: selector argument');
this._options = Common.options('Ink.UI.DatePicker_1', {
autoOpen: ['Boolean', false],
cleanText: ['String', 'Clear'],
closeText: ['String', 'Close'],
containerElement:['Element', null],
cssClass: ['String', 'ink-calendar bottom'],
dateRange: ['String', null],
// use this in a <select>
displayInSelect: ['Boolean', false],
dayField: ['Element', null],
monthField: ['Element', null],
yearField: ['Element', null],
format: ['String', 'yyyy-mm-dd'],
instance: ['String', 'scdp_' + Math.round(99999 * Math.random())],
nextLinkText: ['String', '»'],
ofText: ['String', ' de '],
onFocus: ['Boolean', true],
onMonthSelected: ['Function', null],
onSetDate: ['Function', null],
onYearSelected: ['Function', null],
position: ['String', 'right'],
prevLinkText: ['String', '«'],
showClean: ['Boolean', true],
showClose: ['Boolean', true],
shy: ['Boolean', true],
startDate: ['String', null], // format yyyy-mm-dd,
startWeekDay: ['Number', 1],
// Validation
validDayFn: ['Function', null],
validMonthFn: ['Function', null],
validYearFn: ['Function', null],
nextValidDateFn: ['Function', null],
prevValidDateFn: ['Function', null],
yearRange: ['String', null],
// Text
month: ['Object', {
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
}],
wDay: ['Object', {
0:'Sunday',
1:'Monday',
2:'Tuesday',
3:'Wednesday',
4:'Thursday',
5:'Friday',
6:'Saturday'
}]
}, options || {}, this._element);
this._options.format = this._dateParsers[ this._options.format ] || this._options.format;
this._hoverPicker = false;
this._picker = this._options.pickerField &&
Common.elOrSelector(this._options.pickerField, 'pickerField');
this._setMinMax( this._options.dateRange || this._options.yearRange );
if(this._options.startDate) {
this.setDate( this._options.startDate );
} else if (this._element && this._element.value) {
this.setDate( this._element.value );
} else {
var today = new Date();
this._day = today.getDate( );
this._month = today.getMonth( );
this._year = today.getFullYear( );
}
if (this._options.startWeekDay < 0 || this._options.startWeekDay > 6) {
Ink.warn('Ink.UI.DatePicker_1: option "startWeekDay" must be between 0 (sunday) and 6 (saturday)');
this._options.startWeekDay = clamp(this._options.startWeekDay, 0, 6);
}
if(this._options.displayInSelect &&
!(this._options.dayField && this._options.monthField && this._options.yearField)){
throw new Error(
'Ink.UI.DatePicker: displayInSelect option enabled.'+
'Please specify dayField, monthField and yearField selectors.');
}
this._init();
};
DatePicker.prototype = {
version: '0.1',
/**
* Initialization function. Called by the constructor and receives the same parameters.
*
* @method _init
* @private
*/
_init: function(){
Ink.extendObj(this._options,this._lang || {});
this._render();
this._listenToContainerObjectEvents();
Common.registerInstance(this, this._containerObject, 'datePicker');
},
/**
* Renders the DatePicker's markup.
*
* @method _render
* @private
*/
_render: function() {
this._containerObject = document.createElement('div');
this._containerObject.id = this._options.instance;
this._containerObject.className = this._options.cssClass + ' ink-datepicker-calendar hide-all';
this._renderSuperTopBar();
var calendarTop = document.createElement("div");
calendarTop.className = 'ink-calendar-top';
this._monthDescContainer = document.createElement("div");
this._monthDescContainer.className = 'ink-calendar-month_desc';
this._monthPrev = document.createElement('div');
this._monthPrev.className = 'ink-calendar-prev';
this._monthPrev.innerHTML ='<a href="#prev" class="change_month_prev">' + this._options.prevLinkText + '</a>';
this._monthNext = document.createElement('div');
this._monthNext.className = 'ink-calendar-next';
this._monthNext.innerHTML ='<a href="#next" class="change_month_next">' + this._options.nextLinkText + '</a>';
calendarTop.appendChild(this._monthPrev);
calendarTop.appendChild(this._monthDescContainer);
calendarTop.appendChild(this._monthNext);
this._monthContainer = document.createElement("div");
this._monthContainer.className = 'ink-calendar-month';
this._containerObject.appendChild(calendarTop);
this._containerObject.appendChild(this._monthContainer);
this._monthSelector = this._renderMonthSelector();
this._containerObject.appendChild(this._monthSelector);
this._yearSelector = document.createElement('ul');
this._yearSelector.className = 'ink-calendar-year-selector';
this._containerObject.appendChild(this._yearSelector);
if(!this._options.onFocus || this._options.displayInSelect){
if(!this._options.pickerField){
this._picker = document.createElement('a');
this._picker.href = '#open_cal';
this._picker.innerHTML = 'open';
this._element.parentNode.appendChild(this._picker);
this._picker.className = 'ink-datepicker-picker-field';
} else {
this._picker = Common.elOrSelector(this._options.pickerField, 'pickerField');
}
}
this._appendDatePickerToDom();
this._renderMonth();
this._monthChanger = document.createElement('a');
this._monthChanger.href = '#monthchanger';
this._monthChanger.className = 'ink-calendar-link-month';
this._monthChanger.innerHTML = this._options.month[this._month + 1];
this._ofText = document.createElement('span');
this._ofText.innerHTML = this._options.ofText;
this._yearChanger = document.createElement('a');
this._yearChanger.href = '#yearchanger';
this._yearChanger.className = 'ink-calendar-link-year';
this._yearChanger.innerHTML = this._year;
this._monthDescContainer.innerHTML = '';
this._monthDescContainer.appendChild(this._monthChanger);
this._monthDescContainer.appendChild(this._ofText);
this._monthDescContainer.appendChild(this._yearChanger);
if (!this._options.inline) {
this._addOpenCloseEvents();
} else {
this.show();
}
this._addDateChangeHandlersToInputs();
},
_addDateChangeHandlersToInputs: function () {
var fields = this._element;
if (this._options.displayInSelect) {
fields = [
this._options.dayField,
this._options.monthField,
this._options.yearField];
}
Event.observeMulti(fields ,'change', Ink.bindEvent(function(){
this._updateDate( );
this._showDefaultView( );
this.setDate( );
if ( !this._inline && !this._hoverPicker ) {
this._hide(true);
}
},this));
},
/**
* Shows the calendar.
*
* @method show
**/
show: function () {
this._updateDate();
this._renderMonth();
Css.removeClassName(this._containerObject, 'hide-all');
},
_addOpenCloseEvents: function () {
var opener = this._picker || this._element;
Event.observe(opener, 'click', Ink.bindEvent(function(e){
Event.stop(e);
this.show();
},this));
if (this._options.autoOpen) {
this.show();
}
if(!this._options.displayInSelect){
Event.observe(opener, 'blur', Ink.bindEvent(function() {
if ( !this._hoverPicker ) {
this._hide(true);
}
},this));
}
if (this._options.shy) {
// Close the picker when clicking elsewhere.
Event.observe(document,'click',Ink.bindEvent(function(e){
var target = Event.element(e);
// "elsewhere" is outside any of these elements:
var cannotBe = [
this._options.dayField,
this._options.monthField,
this._options.yearField,
this._picker,
this._element
];
for (var i = 0, len = cannotBe.length; i < len; i++) {
if (cannotBe[i] && InkElement.descendantOf(cannotBe[i], target)) {
return;
}
}
this._hide(true);
},this));
}
},
/**
* Creates the markup of the view with months.
*
* @method _renderMonthSelector
* @private
*/
_renderMonthSelector: function () {
var selector = document.createElement('ul');
selector.className = 'ink-calendar-month-selector';
var ulSelector = document.createElement('ul');
for(var mon=1; mon<=12; mon++){
ulSelector.appendChild(this._renderMonthButton(mon));
if (mon % 4 === 0) {
selector.appendChild(ulSelector);
ulSelector = document.createElement('ul');
}
}
return selector;
},
/**
* Renders a single month button.
*/
_renderMonthButton: function (mon) {
var liMonth = document.createElement('li');
var aMonth = document.createElement('a');
aMonth.setAttribute('data-cal-month', mon);
aMonth.innerHTML = this._options.month[mon].substring(0,3);
liMonth.appendChild(aMonth);
return liMonth;
},
_appendDatePickerToDom: function () {
if(this._options.containerElement) {
var appendTarget =
Ink.i(this._options.containerElement) || // [2.3.0] maybe id; small backwards compatibility thing
Common.elOrSelector(this._options.containerElement);
appendTarget.appendChild(this._containerObject);
}
if (InkElement.findUpwardsBySelector(this._element, '.ink-form .control-group .control') === this._element.parentNode) {
// [3.0.0] Check if the <input> must be a direct child of .control, and if not, remove this block.
this._wrapper = this._element.parentNode;
this._wrapperIsControl = true;
} else {
this._wrapper = InkElement.create('div', { className: 'ink-datepicker-wrapper' });
InkElement.wrap(this._element, this._wrapper);
}
InkElement.insertAfter(this._containerObject, this._element);
},
/**
* Render the topmost bar with the "close" and "clear" buttons.
*/
_renderSuperTopBar: function () {
if((!this._options.showClose) || (!this._options.showClean)){ return; }
this._superTopBar = document.createElement("div");
this._superTopBar.className = 'ink-calendar-top-options';
if(this._options.showClean){
this._superTopBar.appendChild(InkElement.create('a', {
className: 'clean',
setHTML: this._options.cleanText
}));
}
if(this._options.showClose){
this._superTopBar.appendChild(InkElement.create('a', {
className: 'close',
setHTML: this._options.closeText
}));
}
this._containerObject.appendChild(this._superTopBar);
},
_listenToContainerObjectEvents: function () {
Event.observe(this._containerObject,'mouseover',Ink.bindEvent(function(e){
Event.stop( e );
this._hoverPicker = true;
},this));
Event.observe(this._containerObject,'mouseout',Ink.bindEvent(function(e){
Event.stop( e );
this._hoverPicker = false;
},this));
Event.observe(this._containerObject,'click',Ink.bindEvent(this._onClick, this));
},
_onClick: function(e){
var elem = Event.element(e);
if (Css.hasClassName(elem, 'ink-calendar-off')) {
Event.stopDefault(e);
return null;
}
Event.stop(e);
// Relative changers
this._onRelativeChangerClick(elem);
// Absolute changers
this._onAbsoluteChangerClick(elem);
// Mode changers
if (Css.hasClassName(elem, 'ink-calendar-link-month')) {
this._showMonthSelector();
} else if (Css.hasClassName(elem, 'ink-calendar-link-year')) {
this._showYearSelector();
} else if(Css.hasClassName(elem, 'clean')){
this._clean();
} else if(Css.hasClassName(elem, 'close')){
this._hide(false);
}
this._updateDescription();
},
/**
* Handles click events on a changer (« ») for next/prev year/month
* @method _onChangerClick
* @private
**/
_onRelativeChangerClick: function (elem) {
var changeYear = {
change_year_next: 1,
change_year_prev: -1
};
var changeMonth = {
change_month_next: 1,
change_month_prev: -1
};
if( elem.className in changeMonth ) {
this._updateCal(changeMonth[elem.className]);
} else if( elem.className in changeYear ) {
this._showYearSelector(changeYear[elem.className]);
}
},
/**
* Handles click events on an atom-changer (day button, month button, year button)
*
* @method _onAbsoluteChangerClick
* @private
*/
_onAbsoluteChangerClick: function (elem) {
var elemData = InkElement.data(elem);
if( Number(elemData.calDay) ){
this.setDate( [this._year, this._month + 1, elemData.calDay].join('-') );
this._hide();
} else if( Number(elemData.calMonth) ) {
this._month = Number(elemData.calMonth) - 1;
this._showDefaultView();
this._updateCal();
} else if( Number(elemData.calYear) ){
this._changeYear(Number(elemData.calYear));
}
},
_changeYear: function (year) {
year = +year;
if(year){
this._year = year;
if( typeof this._options.onYearSelected === 'function' ){
this._options.onYearSelected(this, {
'year': this._year
});
}
this._showMonthSelector();
}
},
_clean: function () {
if(this._options.displayInSelect){
this._options.yearField.selectedIndex = 0;
this._options.monthField.selectedIndex = 0;
this._options.dayField.selectedIndex = 0;
} else {
this._element.value = '';
}
},
/**
* Hides the DatePicker.
* If the component is shy (options.shy), behaves differently.
*
* @method _hide
* @param {Boolean} [blur] If false, forces hiding even if the component is shy.
*/
_hide: function(blur) {
blur = blur === undefined ? true : blur;
if (blur === false || (blur && this._options.shy)) {
Css.addClassName(this._containerObject, 'hide-all');
}
},
/**
* Sets the range of dates allowed to be selected in the Date Picker
*
* @method _setMinMax
* @param {String} dateRange Two dates separated by a ':'. Example: 2013-01-01:2013-12-12
* @private
*/
_setMinMax: function( dateRange ) {
var self = this;
var noMinLimit = {
_year: -Number.MAX_VALUE,
_month: 0,
_day: 1
};
var noMaxLimit = {
_year: Number.MAX_VALUE,
_month: 11,
_day: 31
};
function noLimits() {
self._min = noMinLimit;
self._max = noMaxLimit;
}
if (!dateRange) { return noLimits(); }
var dates = dateRange.split( ':' );
var rDate = /^(\d{4})((\-)(\d{1,2})((\-)(\d{1,2}))?)?$/;
InkArray.each([
{name: '_min', date: dates[0], noLim: noMinLimit},
{name: '_max', date: dates[1], noLim: noMaxLimit}
], Ink.bind(function (data) {
var lim = data.noLim;
if ( data.date.toUpperCase() === 'NOW' ) {
var now = new Date();
lim = dateishFromDate(now);
} else if (data.date.toUpperCase() === 'EVER') {
lim = data.noLim;
} else if ( rDate.test( data.date ) ) {
lim = dateishFromYMDString(data.date);
lim._month = clamp(lim._month, 0, 11);
lim._day = clamp(lim._day, 1, this._daysInMonth( lim._year, lim._month + 1 ));
}
this[data.name] = lim;
}, this));
// Should be equal, or min should be smaller
var valid = this._dateCmp(this._max, this._min) !== -1;
if (!valid) {
noLimits();
}
},
/**
* Checks if a date is between the valid range.
* Starts by checking if the date passed is valid. If not, will fallback to the 'today' date.
* Then checks if the all params are inside of the date range specified. If not, it will fallback to the nearest valid date (either Min or Max).
*
* @method _fitDateToRange
* @param {Number} year Year with 4 digits (yyyy)
* @param {Number} month Month
* @param {Number} day Day
* @return {Array} Array with the final processed date.
* @private
*/
_fitDateToRange: function( date ) {
if ( !this._isValidDate( date ) ) {
date = dateishFromDate(new Date());
}
if (this._dateCmp(date, this._min) === -1) {
return Ink.extendObj({}, this._min);
} else if (this._dateCmp(date, this._max) === 1) {
return Ink.extendObj({}, this._max);
}
return Ink.extendObj({}, date); // date is okay already, just copy it.
},
/**
* Checks whether a date is within the valid date range
* @method _dateWithinRange
* @param year
* @param month
* @param day
* @return {Boolean}
* @private
*/
_dateWithinRange: function (date) {
if (!arguments.length) {
date = this;
}
return (!this._dateAboveMax(date) &&
(!this._dateBelowMin(date)));
},
_dateAboveMax: function (date) {
return this._dateCmp(date, this._max) === 1;
},
_dateBelowMin: function (date) {
return this._dateCmp(date, this._min) === -1;
},
_dateCmp: function (self, oth) {
return this._dateCmpUntil(self, oth, '_day');
},
/**
* _dateCmp with varied precision. You can compare down to the day field, or, just to the month.
* // the following two dates are considered equal because we asked
* // _dateCmpUntil to just check up to the years.
*
* _dateCmpUntil({_year: 2000, _month: 10}, {_year: 2000, _month: 11}, '_year') === 0
*/
_dateCmpUntil: function (self, oth, depth) {
var props = ['_year', '_month', '_day'];
var i = -1;
do {
i++;
if (self[props[i]] > oth[props[i]]) { return 1; }
else if (self[props[i]] < oth[props[i]]) { return -1; }
} while (props[i] !== depth &&
self[props[i + 1]] !== undefined && oth[props[i + 1]] !== undefined);
return 0;
},
/**
* Sets the markup in the default view mode (showing the days).
* Also disables the previous and next buttons in case they don't meet the range requirements.
*
* @method _showDefaultView
* @private
*/
_showDefaultView: function(){
this._yearSelector.style.display = 'none';
this._monthSelector.style.display = 'none';
this._monthPrev.childNodes[0].className = 'change_month_prev';
this._monthNext.childNodes[0].className = 'change_month_next';
if ( !this._getPrevMonth() ) {
this._monthPrev.childNodes[0].className = 'action_inactive';
}
if ( !this._getNextMonth() ) {
this._monthNext.childNodes[0].className = 'action_inactive';
}
this._monthContainer.style.display = 'block';
},
/**
* Updates the date shown on the datepicker
*
* @method _updateDate
* @private
*/
_updateDate: function(){
var dataParsed;
if(!this._options.displayInSelect && this._element.value){
dataParsed = this._parseDate(this._element.value);
} else if (this._options.displayInSelect) {
dataParsed = {
_year: this._options.yearField[this._options.yearField.selectedIndex].value,
_month: this._options.monthField[this._options.monthField.selectedIndex].value - 1,
_day: this._options.dayField[this._options.dayField.selectedIndex].value
};
}
if (dataParsed) {
dataParsed = this._fitDateToRange(dataParsed);
this._year = dataParsed._year;
this._month = dataParsed._month;
this._day = dataParsed._day;
}
this.setDate();
this._updateDescription();
this._renderMonth();
},
/**
* Updates the date description shown at the top of the datepicker
*
* EG "12 de November"
*
* @method _updateDescription
* @private
*/
_updateDescription: function(){
this._monthChanger.innerHTML = this._options.month[ this._month + 1 ];
this._ofText.innerHTML = this._options.ofText;
this._yearChanger.innerHTML = this._year;
},
/**
* Renders the year selector view of the datepicker
*
* @method _showYearSelector
* @private
*/
_showYearSelector: function(inc){
this._incrementViewingYear(inc);
var firstYear = this._year - (this._year % 10);
var thisYear = firstYear - 1;
var str = "<li><ul>";
if (thisYear > this._min._year) {
str += '<li><a href="#year_prev" class="change_year_prev">' + this._options.prevLinkText + '</a></li>';
} else {
str += '<li> </li>';
}
for (var i=1; i < 11; i++){
if (i % 4 === 0){
str+='</ul><ul>';
}
thisYear = firstYear + i - 1;
str += this._getYearButtonHtml(thisYear);
}
if( thisYear < this._max._year){
str += '<li><a href="#year_next" class="change_year_next">' + this._options.nextLinkText + '</a></li>';
} else {
str += '<li> </li>';
}
str += "</ul></li>";
this._yearSelector.innerHTML = str;
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._monthSelector.style.display = 'none';
this._monthContainer.style.display = 'none';
this._yearSelector.style.display = 'block';
},
/**
* For the year selector.
*
* Update this._year, to find the next decade or use nextValidDateFn to find it.
*/
_incrementViewingYear: function (inc) {
if (!inc) { return; }
var year = +this._year + inc*10;
year = year - year % 10;
if ( year > this._max._year || year + 9 < this._min._year){
return;
}
this._year = +this._year + inc*10;
},
_getYearButtonHtml: function (thisYear) {
if ( this._acceptableYear({_year: thisYear}) ){
var className = (thisYear === this._year) ? ' class="ink-calendar-on"' : '';
return '<li><a href="#" data-cal-year="' + thisYear + '"' + className + '>' + thisYear +'</a></li>';
} else {
return '<li><a href="#" class="ink-calendar-off">' + thisYear +'</a></li>';
}
},
/**
* Show the month selector (happens when you click a year, or the "month" link.
* @method _showMonthSelector
* @private
*/
_showMonthSelector: function () {
this._yearSelector.style.display = 'none';
this._monthContainer.style.display = 'none';
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._addMonthClassNames();
this._monthSelector.style.display = 'block';
},
/**
* This function returns the given date in the dateish format
*
* @method _parseDate
* @param {String} dateStr A date on a string.
* @private
*/
_parseDate: function(dateStr){
var date = InkDate.set( this._options.format , dateStr );
if (date) {
return dateishFromDate(date);
}
return null;
},
/**
* Checks if a date is valid
*
* @method _isValidDate
* @param {Dateish} date
* @private
* @return {Boolean} True if the date is valid, false otherwise
*/
_isValidDate: function(date){
var yearRegExp = /^\d{4}$/;
var validOneOrTwo = /^\d{1,2}$/;
return (
yearRegExp.test(date._year) &&
validOneOrTwo.test(date._month) &&
validOneOrTwo.test(date._day) &&
+date._month + 1 >= 1 &&
+date._month + 1 <= 12 &&
+date._day >= 1 &&
+date._day <= this._daysInMonth(date._year, date._month + 1)
);
},
/**
* Checks if a given date is an valid format.
*
* @method _isDate
* @param {String} format A date format.
* @param {String} dateStr A date on a string.
* @private
* @return {Boolean} True if the given date is valid according to the given format
*/
_isDate: function(format, dateStr){
try {
if (typeof format === 'undefined'){
return false;
}
var date = InkDate.set( format , dateStr );
if( date && this._isValidDate( dateishFromDate(date) )) {
return true;
}
} catch (ex) {}
return false;
},
_acceptableDay: function (date) {
return this._acceptableDateComponent(date, 'validDayFn');
},
_acceptableMonth: function (date) {
return this._acceptableDateComponent(date, 'validMonthFn');
},
_acceptableYear: function (date) {
return this._acceptableDateComponent(date, 'validYearFn');
},
/** DRY base for the above 2 functions */
_acceptableDateComponent: function (date, userCb) {
if (this._options[userCb]) {
return this._callUserCallbackBool(this._options[userCb], date);
} else {
return this._dateWithinRange(date);
}
},
/**
* This method returns the date written with the format specified on the options
*
* @method _writeDateInFormat
* @private
* @return {String} Returns the current date of the object in the specified format
*/
_writeDateInFormat:function(){
return InkDate.get( this._options.format , this.getDate());
},
/**
* This method allows the user to set the DatePicker's date on run-time.
*
* @method setDate
* @param {String} dateString A date string in yyyy-mm-dd format.
* @public
*/
setDate: function( dateString ) {
if ( /\d{4}-\d{1,2}-\d{1,2}/.test( dateString ) ) {
var auxDate = dateString.split( '-' );
this._year = +auxDate[ 0 ];
this._month = +auxDate[ 1 ] - 1;
this._day = +auxDate[ 2 ];
}
this._setDate( );
},
/**
* Gets the current date as a JavaScript date.
*
* @method getDate
*/
getDate: function () {
if (!this._day) {
throw 'Ink.UI.DatePicker: Still picking a date. Cannot getDate now!';
}
return new Date(this._year, this._month, this._day);
},
/**
* Sets the chosen date on the target input field
*
* @method _setDate
* @param {DOMElement} objClicked Clicked object inside the DatePicker's calendar.
* @private
*/
_setDate : function( objClicked ) {
if (objClicked) {
var data = InkElement.data(objClicked);
this._day = (+data.calDay) || this._day;
}
var dt = this._fitDateToRange(this);
this._year = dt._year;
this._month = dt._month;
this._day = dt._day;
if(!this._options.displayInSelect){
this._element.value = this._writeDateInFormat();
} else {
this._options.dayField.value = this._day;
this._options.monthField.value = this._month + 1;
this._options.yearField.value = this._year;
}
if(this._options.onSetDate) {
this._options.onSetDate( this , { date : this.getDate() } );
}
},
/**
* Makes the necessary work to update the calendar
* when choosing a different month
*
* @method _updateCal
* @param {Number} inc Indicates previous or next month
* @private
*/
_updateCal: function(inc){
if( typeof this._options.onMonthSelected === 'function' ){
this._options.onMonthSelected(this, {
'year': this._year,
'month' : this._month
});
}
if (inc && this._updateMonth(inc) === null) {
return;
}
this._renderMonth();
},
/**
* Function that returns the number of days on a given month on a given year
*
* @method _daysInMonth
* @param {Number} _y - year
* @param {Number} _m - month
* @private
* @return {Number} The number of days on a given month on a given year
*/
_daysInMonth: function(_y,_m){
var exceptions = {
2: ((_y % 400 === 0) || (_y % 4 === 0 && _y % 100 !== 0)) ? 29 : 28,
4: 30,
6: 30,
9: 30,
11: 30
};
return exceptions[_m] || 31;
},
/**
* Updates the calendar when a different month is chosen
*
* @method _updateMonth
* @param {Number} incValue - indicates previous or next month
* @private
*/
_updateMonth: function(incValue){
var date;
if (incValue > 0) {
date = this._getNextMonth();
} else if (incValue < 0) {
date = this._getPrevMonth();
}
if (!date) { return null; }
this._year = date._year;
this._month = date._month;
this._day = date._day;
},
/**
* Get the next month we can show.
*/
_getNextMonth: function (date) {
return this._tryLeap( date, 'Month', 'next', function (d) {
d._month += 1;
if (d._month > 11) {
d._month = 0;
d._year += 1;
}
return d;
});
},
/**
* Get the previous month we can show.
*/
_getPrevMonth: function (date) {
return this._tryLeap( date, 'Month', 'prev', function (d) {
d._month -= 1;
if (d._month < 0) {
d._month = 11;
d._year -= 1;
}
return d;
});
},
/**
* Get the next year we can show.
*/
_getPrevYear: function (date) {
return this._tryLeap( date, 'Year', 'prev', function (d) {
d._year -= 1;
return d;
});
},
/**
* Get the next year we can show.
*/
_getNextYear: function (date) {
return this._tryLeap( date, 'Year', 'next', function (d) {
d._year += 1;
return d;
});
},
/**
* DRY base for a function which tries to get the next or previous valid year or month.
*
* It checks if we can go forward by using _dateCmp with atomic
* precision (this means, {_year} for leaping years, and
* {_year, month} for leaping months), then it tries to get the
* result from the user-supplied callback (nextDateFn or prevDateFn),
* and when this is not present, advance the date forward using the
* `advancer` callback.
*/
_tryLeap: function (date, atomName, directionName, advancer) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var maxOrMin = directionName === 'prev' ? '_min' : '_max';
var boundary = this[maxOrMin];
// Check if we're by the boundary of min/max year/month
if (this._dateCmpUntil(date, boundary, atomName) === 0) {
return null; // We're already at the boundary. Bail.
}
var leapUserCb = this._options[directionName + 'ValidDateFn'];
if (leapUserCb) {
return this._callUserCallbackDate(leapUserCb, date);
} else {
date = advancer(date);
}
date = this._fitDateToRange(date);
return this['_acceptable' + atomName](date) ? date : null;
},
_getNextDecade: function (date) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var decade = this._getCurrentDecade(date);
if (decade + 10 > this._max._year) { return null; }
return decade + 10;
},
_getPrevDecade: function (date) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var decade = this._getCurrentDecade(date);
if (decade - 10 < this._min._year) { return null; }
return decade - 10;
},
/** Returns the decade given a date or year*/
_getCurrentDecade: function (year) {
year = year ? (year._year || year) : this._year;
return Math.floor(year / 10) * 10; // Round to first place
},
_callUserCallbackBase: function (cb, date) {
return cb.call(this, date._year, date._month + 1, date._day);
},
_callUserCallbackBool: function (cb, date) {
return !!this._callUserCallbackBase(cb, date);
},
_callUserCallbackDate: function (cb, date) {
var ret = this._callUserCallbackBase(cb, date);
return ret ? dateishFromDate(ret) : null;
},
/**
* Key-value object that (for a given key) points to the correct parsing format for the DatePicker
* @property _dateParsers
* @type {Object}
* @readOnly
*/
_dateParsers: {
'yyyy-mm-dd' : 'Y-m-d' ,
'yyyy/mm/dd' : 'Y/m/d' ,
'yy-mm-dd' : 'y-m-d' ,
'yy/mm/dd' : 'y/m/d' ,
'dd-mm-yyyy' : 'd-m-Y' ,
'dd/mm/yyyy' : 'd/m/Y' ,
'dd-mm-yy' : 'd-m-y' ,
'dd/mm/yy' : 'd/m/y' ,
'mm/dd/yyyy' : 'm/d/Y' ,
'mm-dd-yyyy' : 'm-d-Y'
},
/**
* Renders the current month
*
* @method _renderMonth
* @private
*/
_renderMonth: function(){
var month = this._month;
var year = this._year;
this._showDefaultView();
var html = '';
html += this._getMonthCalendarHeaderHtml(this._options.startWeekDay);
var counter = 0;
html+='<ul>';
var emptyHtml = '<li class="ink-calendar-empty"> </li>';
var firstDayIndex = this._getFirstDayIndex(year, month);
// Add padding if the first day of the month is not monday.
if(firstDayIndex > 0) {
counter += firstDayIndex;
html += strRepeat(firstDayIndex, emptyHtml);
}
html += this._getDayButtonsHtml(year, month);
html += '</ul>';
this._monthContainer.innerHTML = html;
},
/**
* Figure out where the first day of a month lies
* in the first row of the calendar.
*
* having options.startWeekDay === 0
*
* Su Mo Tu We Th Fr Sa
* 1 <- The "1" is in the 7th day. return 6.
* 2 3 4 5 6 7 8
* 9 10 11 12 13 14 15
* 16 17 18 19 20 21 22
* 23 24 25 26 27 28 29
* 30 31
*
* This obviously changes according to the user option "startWeekDay"
**/
_getFirstDayIndex: function (year, month) {
var wDayFirst = (new Date( year , month , 1 )).getDay(); // Sunday=0
var startWeekDay = this._options.startWeekDay || 0; // Sunday=0
var result = wDayFirst - startWeekDay;
result %= 7;
if (result < 0) {
result += 6;
}
return result;
},
_getDayButtonsHtml: function (year, month) {
var counter = this._getFirstDayIndex(year, month);
var daysInMonth = this._daysInMonth(year, month + 1);
var ret = '';
for (var day = 1; day <= daysInMonth; day++) {
if (counter === 7){ // new week
counter=0;
ret += '<ul>';
}
ret += this._getDayButtonHtml(year, month, day);
counter++;
if(counter === 7){
ret += '</ul>';
}
}
return ret;
},
/**
* Get the HTML markup for a single day in month view, given year, month, day.
*
* @method _getDayButtonHtml
* @private
*/
_getDayButtonHtml: function (year, month, day) {
var attrs = ' ';
var date = dateishFromYMD(year, month, day);
if (!this._acceptableDay(date)) {
attrs += 'class="ink-calendar-off"';
} else {
attrs += 'data-cal-day="' + day + '"';
}
if (this._day && this._dateCmp(date, this) === 0) {
attrs += 'class="ink-calendar-on" data-cal-day="' + day + '"';
}
return '<li><a href="#" ' + attrs + '>' + day + '</a></li>';
},
/** Write the top bar of the calendar (M T W T F S S) */
_getMonthCalendarHeaderHtml: function (startWeekDay) {
var ret = '<ul class="ink-calendar-header">';
var wDay;
for(var i=0; i<7; i++){
wDay = (startWeekDay + i) % 7;
ret += '<li>' +
this._options.wDay[wDay].substring(0,1) +
'</li>';
}
return ret + '</ul>';
},
/**
* This method adds class names to month buttons, to visually distinguish.
*
* @method _addMonthClassNames
* @param {DOMElement} parent DOMElement where all the months are.
* @private
*/
_addMonthClassNames: function(parent){
InkArray.forEach(
(parent || this._monthSelector).getElementsByTagName('a'),
Ink.bindMethod(this, '_addMonthButtonClassNames'));
},
/**
* Add the ink-calendar-on className if the given button is the current month,
* otherwise add the ink-calendar-off className if the given button refers to
* an unacceptable month (given dateRange and validMonthFn)
*/
_addMonthButtonClassNames: function (btn) {
var data = InkElement.data(btn);
if (!data.calMonth) { throw 'not a calendar month button!'; }
var month = +data.calMonth - 1;
if ( month === this._month ) {
Css.addClassName( btn, 'ink-calendar-on' ); // This month
Css.removeClassName( btn, 'ink-calendar-off' );
} else {
Css.removeClassName( btn, 'ink-calendar-on' ); // Not this month
var toDisable = !this._acceptableMonth({_year: this._year, _month: month});
Css.addRemoveClassName( btn, 'ink-calendar-off', toDisable);
}
},
/**
* Prototype's method to allow the 'i18n files' to change all objects' language at once.
* @param {Object} options Object with the texts' configuration.
* @param {String} options.closeText Text of the close anchor
* @param {String} options.cleanText Text of the clean text anchor
* @param {String} options.prevLinkText "Previous" link's text
* @param {String} options.nextLinkText "Next" link's text
* @param {String} options.ofText The text "of", present in 'May of 2013'
* @param {Object} options.month An object with keys from 1 to 12 for the full months' names
* @param {Object} options.wDay An object with keys from 0 to 6 for the full weekdays' names
* @public
*/
lang: function( options ){
this._lang = options;
},
/**
* This calls the rendering of the selected month. (Deprecated: use show() instead)
*
*/
showMonth: function(){
this._renderMonth();
},
/**
* Checks if the calendar screen is in 'select day' mode
*
* @return {Boolean} True if the calendar screen is in 'select day' mode
* @public
*/
isMonthRendered: function(){
var header = Selector.select('.ink-calendar-header', this._containerObject)[0];
return ((Css.getStyle(header.parentNode,'display') !== 'none') &&
(Css.getStyle(header.parentNode.parentNode,'display') !== 'none') );
},
/**
* Destroys this datepicker, removing it from the page.
*
* @public
**/
destroy: function () {
InkElement.unwrap(this._element);
InkElement.remove(this._wrapper);
InkElement.remove(this._containerObject);
Common.unregisterInstance.call(this);
}
};
return DatePicker;
}); |
let arr = [];
for(let i = 0; i < 10; i++) {
for (let i = 0; i < 10; i++) {
arr.push(() => i);
}
}
|
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="node" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var baseIndexOf = require('./baseIndexOf'),
cacheIndexOf = require('./cacheIndexOf'),
createCache = require('./createCache'),
getArray = require('./getArray'),
largeArraySize = require('./largeArraySize'),
releaseArray = require('./releaseArray'),
releaseObject = require('./releaseObject');
/**
* The base implementation of `_.uniq` without support for callback shorthands
* or `thisArg` binding.
*
* @private
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function} [callback] The function called per iteration.
* @returns {Array} Returns a duplicate-value-free array.
*/
function baseUniq(array, isSorted, callback) {
var index = -1,
indexOf = baseIndexOf,
length = array ? array.length : 0,
result = [];
var isLarge = !isSorted && length >= largeArraySize,
seen = (callback || isLarge) ? getArray() : result;
if (isLarge) {
var cache = createCache(seen);
indexOf = cacheIndexOf;
seen = cache;
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
if (isLarge) {
releaseArray(seen.array);
releaseObject(seen);
} else if (callback) {
releaseArray(seen);
}
return result;
}
module.exports = baseUniq;
|
/**
* @license AngularJS v1.0.6
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngResource
* @description
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* # Installation
* To use $resource make sure you have included the `angular-resource.js` that comes in Angular
* package. You can also find this file on Google CDN, bower as well as at
* {@link http://code.angularjs.org/ code.angularjs.org}.
*
* Finally load the module in your application:
*
* angular.module('app', ['ngResource']);
*
* and you are ready to get started!
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`. If you are using a URL with a port number (e.g.
* `http://example.com:8080/api`), you'll need to escape the colon character before the port
* number, like this: `$resource('http://example.com\\:8080/api')`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?},
* action2: {method:?, params:?, isArray:?},
* ...}
*
* Where:
*
* - `action` – {string} – The name of action. This name becomes the name of the method on your
* resource object.
* - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSONP`
* - `params` – {object=} – Optional set of pre-bound parameters for this action.
* - isArray – {boolean=} – If true then the returned object for this action is an array, see
* `returns` section.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
* read, update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div ng-repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction,
getter = function(obj, path) {
return $parse(path)(obj);
};
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) {
urlParams[param] = true;
}
});
this.template = template.replace(/\\:/g, ':');
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
val,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
if (angular.isDefined(val) && val !== null) {
encodedVal = encodeUriSegment(val);
url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1");
} else {
url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match,
leadingSlashes, tail) {
if (tail.charAt(0) == '/') {
return tail;
} else {
return leadingSlashes + tail;
}
});
}
});
url = url.replace(/\/?#$/, '');
var query = [];
forEach(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
query.sort();
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data, actionParams){
var ids = {};
actionParams = extend({}, paramDefaults, actionParams);
forEach(actionParams, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name) {
action.method = angular.uppercase(action.method);
var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH';
Resource[name] = function(a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
$http({
method: action.method,
url: route.url(extend({}, extractParams(data, action.params || {}), params)),
data: data
}).then(function(response) {
var data = response.data;
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
(success||noop)(value, response.headers);
}, error);
return value;
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = hasBody ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
Resource.bind = function(additionalParamDefaults){
return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
return Resource;
}
return ResourceFactory;
}]);
})(window, window.angular);
|
import { Duration, isDuration } from './constructor';
import toInt from '../utils/to-int';
import hasOwnProp from '../utils/has-own-prop';
import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants';
import { cloneWithOffset } from '../units/offset';
import { createLocal } from '../create/local';
// ASP.NET json date format regex
var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/;
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
export function createDuration (input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms : input._milliseconds,
d : input._days,
M : input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : 0,
d : toInt(match[DATE]) * sign,
h : toInt(match[HOUR]) * sign,
m : toInt(match[MINUTE]) * sign,
s : toInt(match[SECOND]) * sign,
ms : toInt(match[MILLISECOND]) * sign
};
} else if (!!(match = isoRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : parseIso(match[2], sign),
M : parseIso(match[3], sign),
w : parseIso(match[4], sign),
d : parseIso(match[5], sign),
h : parseIso(match[6], sign),
m : parseIso(match[7], sign),
s : parseIso(match[8], sign)
};
} else if (duration == null) {// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
}
createDuration.fn = Duration.prototype;
function parseIso (inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return {milliseconds: 0, months: 0};
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
|
/* jshint -W100 */
/* jslint maxlen: 86 */
define(function () {
// Farsi (Persian)
return {
errorLoading: function () {
return 'امکان بارگذاری نتایج وجود ندارد.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'لطفاً ' + overChars + ' کاراکتر را حذف نمایید';
return message;
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
var message = 'لطفاً تعداد ' + remainingChars + ' کاراکتر یا بیشتر وارد نمایید';
return message;
},
loadingMore: function () {
return 'در حال بارگذاری نتایج بیشتر...';
},
maximumSelected: function (args) {
var message = 'شما تنها میتوانید ' + args.maximum + ' آیتم را انتخاب نمایید';
return message;
},
noResults: function () {
return 'هیچ نتیجهای یافت نشد';
},
searching: function () {
return 'در حال جستجو...';
}
};
});
|
//! moment.js locale configuration
//! locale : Chinese (Hong Kong) [zh-hk]
//! author : Ben : https://github.com/ben-lin
//! author : Chris Lam : https://github.com/hehachris
//! author : Konstantin : https://github.com/skfd
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
var zhHk = moment.defineLocale('zh-hk', {
months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'),
weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'YYYY年MMMD日',
LL : 'YYYY年MMMD日',
LLL : 'YYYY年MMMD日 HH:mm',
LLLL : 'YYYY年MMMD日dddd HH:mm',
l : 'YYYY年MMMD日',
ll : 'YYYY年MMMD日',
lll : 'YYYY年MMMD日 HH:mm',
llll : 'YYYY年MMMD日dddd HH:mm'
},
meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
meridiemHour : function (hour, meridiem) {
if (hour === 12) {
hour = 0;
}
if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
return hour;
} else if (meridiem === '中午') {
return hour >= 11 ? hour : hour + 12;
} else if (meridiem === '下午' || meridiem === '晚上') {
return hour + 12;
}
},
meridiem : function (hour, minute, isLower) {
var hm = hour * 100 + minute;
if (hm < 600) {
return '凌晨';
} else if (hm < 900) {
return '早上';
} else if (hm < 1130) {
return '上午';
} else if (hm < 1230) {
return '中午';
} else if (hm < 1800) {
return '下午';
} else {
return '晚上';
}
},
calendar : {
sameDay : '[今天]LT',
nextDay : '[明天]LT',
nextWeek : '[下]ddddLT',
lastDay : '[昨天]LT',
lastWeek : '[上]ddddLT',
sameElse : 'L'
},
dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
ordinal : function (number, period) {
switch (period) {
case 'd' :
case 'D' :
case 'DDD' :
return number + '日';
case 'M' :
return number + '月';
case 'w' :
case 'W' :
return number + '週';
default :
return number;
}
},
relativeTime : {
future : '%s內',
past : '%s前',
s : '幾秒',
m : '1 分鐘',
mm : '%d 分鐘',
h : '1 小時',
hh : '%d 小時',
d : '1 天',
dd : '%d 天',
M : '1 個月',
MM : '%d 個月',
y : '1 年',
yy : '%d 年'
}
});
return zhHk;
})));
|
var assert = require('assert');
var cookie = require('..');
suite('parse');
test('basic', function() {
assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar'));
assert.deepEqual({ foo: '123' }, cookie.parse('foo=123'));
});
test('ignore spaces', function() {
assert.deepEqual({ FOO: 'bar', baz: 'raz' },
cookie.parse('FOO = bar; baz = raz'));
});
test('escaping', function() {
assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' },
cookie.parse('foo="bar=123456789&name=Magic+Mouse"'));
assert.deepEqual({ email: ' ",;/' },
cookie.parse('email=%20%22%2c%3b%2f'));
});
test('ignore escaping error and return original value', function() {
assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar'));
});
|
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.explode = explode;
exports.verify = verify;
exports.merge = merge;
var _virtualTypes = require("./path/lib/virtual-types");
var virtualTypes = _interopRequireWildcard(_virtualTypes);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explode(visitor) {
if (visitor._exploded) return visitor;
visitor._exploded = true;
for (var nodeType in visitor) {
if (shouldIgnoreKey(nodeType)) continue;
var parts = nodeType.split("|");
if (parts.length === 1) continue;
var fns = visitor[nodeType];
delete visitor[nodeType];
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var part = _ref;
visitor[part] = fns;
}
}
verify(visitor);
delete visitor.__esModule;
ensureEntranceObjects(visitor);
ensureCallbackArrays(visitor);
for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _nodeType3 = _ref2;
if (shouldIgnoreKey(_nodeType3)) continue;
var wrapper = virtualTypes[_nodeType3];
if (!wrapper) continue;
var _fns2 = visitor[_nodeType3];
for (var type in _fns2) {
_fns2[type] = wrapCheck(wrapper, _fns2[type]);
}
delete visitor[_nodeType3];
if (wrapper.types) {
for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var _type = _ref4;
if (visitor[_type]) {
mergePair(visitor[_type], _fns2);
} else {
visitor[_type] = _fns2;
}
}
} else {
mergePair(visitor, _fns2);
}
}
for (var _nodeType in visitor) {
if (shouldIgnoreKey(_nodeType)) continue;
var _fns = visitor[_nodeType];
var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType];
var deprecratedKey = t.DEPRECATED_KEYS[_nodeType];
if (deprecratedKey) {
console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey);
aliases = [deprecratedKey];
}
if (!aliases) continue;
delete visitor[_nodeType];
for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var alias = _ref3;
var existing = visitor[alias];
if (existing) {
mergePair(existing, _fns);
} else {
visitor[alias] = (0, _clone2.default)(_fns);
}
}
}
for (var _nodeType2 in visitor) {
if (shouldIgnoreKey(_nodeType2)) continue;
ensureCallbackArrays(visitor[_nodeType2]);
}
return visitor;
}
function verify(visitor) {
if (visitor._verified) return;
if (typeof visitor === "function") {
throw new Error(messages.get("traverseVerifyRootFunction"));
}
for (var nodeType in visitor) {
if (nodeType === "enter" || nodeType === "exit") {
validateVisitorMethods(nodeType, visitor[nodeType]);
}
if (shouldIgnoreKey(nodeType)) continue;
if (t.TYPES.indexOf(nodeType) < 0) {
throw new Error(messages.get("traverseVerifyNodeType", nodeType));
}
var visitors = visitor[nodeType];
if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") {
for (var visitorKey in visitors) {
if (visitorKey === "enter" || visitorKey === "exit") {
validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]);
} else {
throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey));
}
}
}
}
visitor._verified = true;
}
function validateVisitorMethods(path, val) {
var fns = [].concat(val);
for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var fn = _ref5;
if (typeof fn !== "function") {
throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn)));
}
}
}
function merge(visitors) {
var states = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
var wrapper = arguments[2];
var rootVisitor = {};
for (var i = 0; i < visitors.length; i++) {
var visitor = visitors[i];
var state = states[i];
explode(visitor);
for (var type in visitor) {
var visitorType = visitor[type];
if (state || wrapper) {
visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper);
}
var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {};
mergePair(nodeVisitor, visitorType);
}
}
return rootVisitor;
}
function wrapWithStateOrWrapper(oldVisitor, state, wrapper) {
var newVisitor = {};
var _loop = function _loop(key) {
var fns = oldVisitor[key];
if (!Array.isArray(fns)) return "continue";
fns = fns.map(function (fn) {
var newFn = fn;
if (state) {
newFn = function newFn(path) {
return fn.call(state, path, state);
};
}
if (wrapper) {
newFn = wrapper(state.key, key, newFn);
}
return newFn;
});
newVisitor[key] = fns;
};
for (var key in oldVisitor) {
var _ret = _loop(key);
if (_ret === "continue") continue;
}
return newVisitor;
}
function ensureEntranceObjects(obj) {
for (var key in obj) {
if (shouldIgnoreKey(key)) continue;
var fns = obj[key];
if (typeof fns === "function") {
obj[key] = { enter: fns };
}
}
}
function ensureCallbackArrays(obj) {
if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter];
if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit];
}
function wrapCheck(wrapper, fn) {
var newFn = function newFn(path) {
if (wrapper.checkPath(path)) {
return fn.apply(this, arguments);
}
};
newFn.toString = function () {
return fn.toString();
};
return newFn;
}
function shouldIgnoreKey(key) {
if (key[0] === "_") return true;
if (key === "enter" || key === "exit" || key === "shouldSkip") return true;
if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true;
return false;
}
function mergePair(dest, src) {
for (var key in src) {
dest[key] = [].concat(dest[key] || [], src[key]);
}
} |
var gulp = require('gulp');
var paths = require('../paths');
var del = require('del');
var vinylPaths = require('vinyl-paths');
// deletes all files in the output path
gulp.task('clean', function() {
return gulp.src([paths.output])
.pipe(vinylPaths(del));
});
|
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/store/JsonRest",["../_base/xhr","../_base/lang","../json","../_base/declare","./util/QueryResults"],function(_1,_2,_3,_4,_5){
var _6=null;
return _4("dojo.store.JsonRest",_6,{constructor:function(_7){
this.headers={};
_4.safeMixin(this,_7);
},headers:{},target:"",idProperty:"id",ascendingPrefix:"+",descendingPrefix:"-",_getTarget:function(id){
var _8=this.target;
if(typeof id!="undefined"){
if(_8.charAt(_8.length-1)=="/"){
_8+=id;
}else{
_8+="/"+id;
}
}
return _8;
},get:function(id,_9){
_9=_9||{};
var _a=_2.mixin({Accept:this.accepts},this.headers,_9.headers||_9);
return _1("GET",{url:this._getTarget(id),handleAs:"json",headers:_a});
},accepts:"application/javascript, application/json",getIdentity:function(_b){
return _b[this.idProperty];
},put:function(_c,_d){
_d=_d||{};
var id=("id" in _d)?_d.id:this.getIdentity(_c);
var _e=typeof id!="undefined";
return _1(_e&&!_d.incremental?"PUT":"POST",{url:this._getTarget(id),postData:_3.stringify(_c),handleAs:"json",headers:_2.mixin({"Content-Type":"application/json",Accept:this.accepts,"If-Match":_d.overwrite===true?"*":null,"If-None-Match":_d.overwrite===false?"*":null},this.headers,_d.headers)});
},add:function(_f,_10){
_10=_10||{};
_10.overwrite=false;
return this.put(_f,_10);
},remove:function(id,_11){
_11=_11||{};
return _1("DELETE",{url:this._getTarget(id),headers:_2.mixin({},this.headers,_11.headers)});
},query:function(_12,_13){
_13=_13||{};
var _14=_2.mixin({Accept:this.accepts},this.headers,_13.headers);
var _15=this.target.indexOf("?")>-1;
if(_12&&typeof _12=="object"){
_12=_1.objectToQuery(_12);
_12=_12?(_15?"&":"?")+_12:"";
}
if(_13.start>=0||_13.count>=0){
_14["X-Range"]="items="+(_13.start||"0")+"-"+(("count" in _13&&_13.count!=Infinity)?(_13.count+(_13.start||0)-1):"");
if(this.rangeParam){
_12+=(_12||_15?"&":"?")+this.rangeParam+"="+_14["X-Range"];
_15=true;
}else{
_14.Range=_14["X-Range"];
}
}
if(_13&&_13.sort){
var _16=this.sortParam;
_12+=(_12||_15?"&":"?")+(_16?_16+"=":"sort(");
for(var i=0;i<_13.sort.length;i++){
var _17=_13.sort[i];
_12+=(i>0?",":"")+(_17.descending?this.descendingPrefix:this.ascendingPrefix)+encodeURIComponent(_17.attribute);
}
if(!_16){
_12+=")";
}
}
var _18=_1("GET",{url:this.target+(_12||""),handleAs:"json",headers:_14});
_18.total=_18.then(function(){
var _19=_18.ioArgs.xhr.getResponseHeader("Content-Range");
if(!_19){
_19=_18.ioArgs.xhr.getResponseHeader("X-Content-Range");
}
return _19&&(_19=_19.match(/\/(.*)/))&&+_19[1];
});
return _5(_18);
}});
});
|
var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
renderError() {
if(!this.props.error) return null;
return <span className="error">{this.props.error}</span>;
},
renderLabel() {
var cn = cx('label', this.props.d ? `g-${this.props.d}` : null);
if(!this.props.label) {
return (
<label className={cn}> </label>
);
}
return (
<label className={cn}>
{this.props.label}
</label>
);
},
render() {
var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm');
props.className = cx('u-field', {
'g-row': this.props.d,
'u-field-row': this.props.d,
'u-field-err': this.props.error
});
return (
<div {... props}>
{this.renderLabel()}
{this.props.d ? (
<div className={`g-${24 - this.props.d}`}>
{this.props.children}
</div>
) : this.props.children}
{this.renderError()}
</div>
);
}
});
|
/* @flow */
import { PropTypes } from 'react'
export default PropTypes.oneOfType([
// [Number, Number]
PropTypes.arrayOf(PropTypes.number),
// {lat: Number, lng: Number}
PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number,
}),
// {lat: Number, lon: Number}
PropTypes.shape({
lat: PropTypes.number,
lon: PropTypes.number,
}),
])
|
import { modulo } from './Math.js'
export function random(x) {
return modulo(Math.sin(x) * 43758.5453123, 1)
}
|
const test = require('tape')
const sinon = require('sinon')
const helpers = require('../test/helpers')
const MockCrock = require('../test/MockCrock')
const bindFunc = helpers.bindFunc
const curry = require('./curry')
const _compose = curry(require('./compose'))
const isFunction = require('./isFunction')
const isObject = require('./isObject')
const isSameType = require('./isSameType')
const isString = require('./isString')
const unit = require('./_unit')
const fl = require('./flNames')
const Maybe = require('./Maybe')
const Pred = require('./Pred')
const constant = x => () => x
const identity = x => x
const applyTo =
x => fn => fn(x)
const List = require('./List')
test('List', t => {
const f = x => List(x).toArray()
t.ok(isFunction(List), 'is a function')
t.ok(isObject(List([])), 'returns an object')
t.equals(List([]).constructor, List, 'provides TypeRep on constructor')
t.ok(isFunction(List.of), 'provides an of function')
t.ok(isFunction(List.fromArray), 'provides a fromArray function')
t.ok(isFunction(List.type), 'provides a type function')
t.ok(isString(List['@@type']), 'provides a @@type string')
const err = /List: List must wrap something/
t.throws(List, err, 'throws with no parameters')
t.same(f(undefined), [ undefined ], 'wraps value in array when called with undefined')
t.same(f(null), [ null ], 'wraps value in array when called with null')
t.same(f(0), [ 0 ], 'wraps value in array when called with falsey number')
t.same(f(1), [ 1 ], 'wraps value in array when called with truthy number')
t.same(f(''), [ '' ], 'wraps value in array when called with falsey string')
t.same(f('string'), [ 'string' ], 'wraps value in array when called with truthy string')
t.same(f(false), [ false ], 'wraps value in array when called with false')
t.same(f(true), [ true ], 'wraps value in array when called with true')
t.same(f({}), [ {} ], 'wraps value in array when called with an Object')
t.same(f([ 1, 2, 3 ]), [ 1, 2, 3 ], 'Does not wrap an array, just uses it as the list')
t.end()
})
test('List fantasy-land api', t => {
const m = List('value')
t.ok(isFunction(List[fl.empty]), 'provides empty function on constructor')
t.ok(isFunction(List[fl.of]), 'provides of function on constructor')
t.ok(isFunction(m[fl.of]), 'provides of method on instance')
t.ok(isFunction(m[fl.empty]), 'provides empty method on instance')
t.ok(isFunction(m[fl.equals]), 'provides equals method on instance')
t.ok(isFunction(m[fl.concat]), 'provides concat method on instance')
t.ok(isFunction(m[fl.map]), 'provides map method on instance')
t.ok(isFunction(m[fl.chain]), 'provides chain method on instance')
t.ok(isFunction(m[fl.reduce]), 'provides reduce method on instance')
t.ok(isFunction(m[fl.filter]), 'provides filter method on instance')
t.end()
})
test('List @@implements', t => {
const f = List['@@implements']
t.equal(f('ap'), true, 'implements ap func')
t.equal(f('chain'), true, 'implements chain func')
t.equal(f('concat'), true, 'implements concat func')
t.equal(f('empty'), true, 'implements empty func')
t.equal(f('equals'), true, 'implements equals func')
t.equal(f('map'), true, 'implements map func')
t.equal(f('of'), true, 'implements of func')
t.equal(f('reduce'), true, 'implements reduce func')
t.equal(f('traverse'), true, 'implements traverse func')
t.end()
})
test('List fromArray', t => {
const fromArray = bindFunc(List.fromArray)
const err = /List.fromArray: Array required/
t.throws(fromArray(undefined), err, 'throws with undefined')
t.throws(fromArray(null), err, 'throws with null')
t.throws(fromArray(0), err, 'throws with falsey number')
t.throws(fromArray(1), err, 'throws with truthy number')
t.throws(fromArray(''), err, 'throws with falsey string')
t.throws(fromArray('string'), err, 'throws with truthy string')
t.throws(fromArray(false), err, 'throws with false')
t.throws(fromArray(true), err, 'throws with true')
t.throws(fromArray({}), err, 'throws with an object')
const data = [ [ 2, 1 ], 'a' ]
t.ok(isSameType(List, List.fromArray([ 0 ])), 'returns a List')
t.same(List.fromArray(data).valueOf(), data, 'wraps the value passed into List in an array')
t.end()
})
test('List inspect', t => {
const m = List([ 1, true, 'string' ])
t.ok(isFunction(m.inspect), 'provides an inpsect function')
t.equal(m.inspect, m.toString, 'toString is the same function as inspect')
t.equal(m.inspect(), 'List [ 1, true, "string" ]', 'returns inspect string')
t.end()
})
test('List type', t => {
const m = List([])
t.ok(isFunction(m.type), 'is a function')
t.equal(m.type, List.type, 'static and instance versions are the same')
t.equal(m.type(), 'List', 'returns List')
t.end()
})
test('List @@type', t => {
const m = List([])
t.equal(m['@@type'], List['@@type'], 'static and instance versions are the same')
t.equal(m['@@type'], 'crocks/List@4', 'returns crocks/List@4')
t.end()
})
test('List head', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
t.ok(isFunction(two.head), 'Provides a head Function')
t.ok(isSameType(Maybe, empty.head()), 'empty List returns a Maybe')
t.ok(isSameType(Maybe, one.head()), 'one element List returns a Maybe')
t.ok(isSameType(Maybe, two.head()), 'two element List returns a Maybe')
t.equal(empty.head().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.head().option('Nothing'), 1, 'one element List returns a `Just 1`')
t.equal(two.head().option('Nothing'), 2, 'two element List returns a `Just 2`')
t.end()
})
test('List tail', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
const three = List([ 4, 5, 6 ])
t.ok(isFunction(two.tail), 'Provides a tail Function')
t.equal(empty.tail().type(), Maybe.type(), 'empty List returns a Maybe')
t.equal(one.tail().type(), Maybe.type(), 'one element List returns a Maybe')
t.equal(two.tail().type(), Maybe.type(), 'two element List returns a Maybe')
t.equal(three.tail().type(), Maybe.type(), 'three element List returns a Maybe')
t.equal(empty.tail().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.tail().option('Nothing'), 'Nothing', 'one element List returns a `Just 1`')
t.equal(two.tail().option('Nothing').type(), 'List', 'two element List returns a `Just List`')
t.same(two.tail().option('Nothing').valueOf(), [ 3 ], 'two element Maybe List contains `[ 3 ]`')
t.equal(three.tail().option('Nothing').type(), 'List', 'three element List returns a `Just List`')
t.same(three.tail().option('Nothing').valueOf(), [ 5, 6 ], 'three element Maybe List contains `[ 5, 6 ]`')
t.end()
})
test('List cons', t => {
const list = List.of('guy')
const consed = list.cons('hello')
t.ok(isFunction(list.cons), 'provides a cons function')
t.notSame(list.valueOf(), consed.valueOf(), 'keeps old list intact')
t.same(consed.valueOf(), [ 'hello', 'guy' ], 'returns a list with the element pushed to front')
t.end()
})
test('List valueOf', t => {
const x = List([ 'some-thing', 34 ]).valueOf()
t.same(x, [ 'some-thing', 34 ], 'provides the wrapped array')
t.end()
})
test('List toArray', t => {
const data = [ 'some-thing', [ 'else', 43 ], 34 ]
const a = List(data).toArray()
t.same(a, data, 'provides the wrapped array')
t.end()
})
test('List equals functionality', t => {
const a = List([ 'a', 'b' ])
const b = List([ 'a', 'b' ])
const c = List([ '1', 'b' ])
const value = 'yep'
const nonList = { type: 'List...Not' }
t.equal(a.equals(c), false, 'returns false when 2 Lists are not equal')
t.equal(a.equals(b), true, 'returns true when 2 Lists are equal')
t.equal(a.equals(value), false, 'returns false when passed a simple value')
t.equal(a.equals(nonList), false, 'returns false when passed a non-List')
t.end()
})
test('List equals properties (Setoid)', t => {
const a = List([ 0, 'like' ])
const b = List([ 0, 'like' ])
const c = List([ 1, 'rainbow' ])
const d = List([ 'like', 0 ])
t.ok(isFunction(List([]).equals), 'provides an equals function')
t.equal(a.equals(a), true, 'reflexivity')
t.equal(a.equals(b), b.equals(a), 'symmetry (equal)')
t.equal(a.equals(c), c.equals(a), 'symmetry (!equal)')
t.equal(a.equals(b) && b.equals(d), a.equals(d), 'transitivity')
t.end()
})
test('List concat properties (Semigroup)', t => {
const a = List([ 1, '' ])
const b = List([ 0, null ])
const c = List([ true, 'string' ])
const left = a.concat(b).concat(c)
const right = a.concat(b.concat(c))
t.ok(isFunction(a.concat), 'provides a concat function')
t.same(left.valueOf(), right.valueOf(), 'associativity')
t.equal(a.concat(b).type(), a.type(), 'returns a List')
t.end()
})
test('List concat errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a.concat)
const err = /List.concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat fantasy-land errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a[fl.concat])
const err = /List.fantasy-land\/concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat functionality', t => {
const a = List([ 1, 2 ])
const b = List([ 3, 4 ])
t.same(a.concat(b).valueOf(), [ 1, 2, 3, 4 ], 'concats second to first')
t.same(b.concat(a).valueOf(), [ 3, 4, 1, 2 ], 'concats first to second')
t.end()
})
test('List empty properties (Monoid)', t => {
const m = List([ 1, 2 ])
t.ok(isFunction(m.concat), 'provides a concat function')
t.ok(isFunction(m.empty), 'provides an empty function')
const right = m.concat(m.empty())
const left = m.empty().concat(m)
t.same(right.valueOf(), m.valueOf(), 'right identity')
t.same(left.valueOf(), m.valueOf(), 'left identity')
t.end()
})
test('List empty functionality', t => {
const x = List([ 0, 1, true ]).empty()
t.equal(x.type(), 'List', 'provides a List')
t.same(x.valueOf(), [], 'provides an empty array')
t.end()
})
test('List reduce errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduce)
const err = /List.reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce fantasy-land errors', t => {
const reduce = bindFunc(List([ 1, 2 ])[fl.reduce])
const err = /List.fantasy-land\/reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce functionality', t => {
const f = (y, x) => y + x
const m = List([ 1, 2, 3 ])
t.equal(m.reduce(f, 0), 6, 'reduces as expected with a neutral initial value')
t.equal(m.reduce(f, 10), 16, 'reduces as expected with a non-neutral initial value')
t.end()
})
test('List reduceRight errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduceRight)
const err = /List.reduceRight: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduceRight functionality', t => {
const f = (y, x) => y.concat(x)
const m = List([ '1', '2', '3' ])
t.equal(m.reduceRight(f, '4'), '4321', 'reduces as expected')
t.end()
})
test('List fold errors', t => {
const f = bindFunc(x => List(x).fold())
const noSemi = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f(undefined), noSemi, 'throws when contains single undefined')
t.throws(f(null), noSemi, 'throws when contains single null')
t.throws(f(0), noSemi, 'throws when contains single falsey number')
t.throws(f(1), noSemi, 'throws when contains single truthy number')
t.throws(f(false), noSemi, 'throws when contains single false')
t.throws(f(true), noSemi, 'throws when contains single true')
t.throws(f({}), noSemi, 'throws when contains a single object')
t.throws(f(unit), noSemi, 'throws when contains a single function')
const empty = /^TypeError: List.fold: List must contain at least one Semigroup/
t.throws(f([]), empty, 'throws when empty')
const diff = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f([ [], '' ]), diff, 'throws when empty')
t.end()
})
test('List fold functionality', t => {
const f = x => List(x).fold()
t.same(f([ [ 1 ], [ 2 ] ]), [ 1, 2 ], 'combines and extracts semigroups')
t.equals(f('lucky'), 'lucky', 'extracts a single semigroup')
t.end()
})
test('List foldMap errors', t => {
const noFunc = bindFunc(fn => List([ 1 ]).foldMap(fn))
const funcErr = /^TypeError: List.foldMap: Semigroup returning function required/
t.throws(noFunc(undefined), funcErr, 'throws with undefined')
t.throws(noFunc(null), funcErr, 'throws with null')
t.throws(noFunc(0), funcErr, 'throws with falsey number')
t.throws(noFunc(1), funcErr, 'throws with truthy number')
t.throws(noFunc(false), funcErr, 'throws with false')
t.throws(noFunc(true), funcErr, 'throws with true')
t.throws(noFunc(''), funcErr, 'throws with falsey string')
t.throws(noFunc('string'), funcErr, 'throws with truthy string')
t.throws(noFunc({}), funcErr, 'throws with an object')
t.throws(noFunc([]), funcErr, 'throws with an array')
const fn = bindFunc(x => List(x).foldMap(identity))
const emptyErr = /^TypeError: List.foldMap: List must not be empty/
t.throws(fn([]), emptyErr, 'throws when passed an empty List')
const notSameSemi = /^TypeError: List.foldMap: Provided function must return Semigroups of the same type/
t.throws(fn([ 0 ]), notSameSemi, 'throws when function does not return a Semigroup')
t.throws(fn([ '', 0 ]), notSameSemi, 'throws when not all returned values are Semigroups')
t.throws(fn([ '', [] ]), notSameSemi, 'throws when different semigroups are returned')
t.end()
})
test('List foldMap functionality', t => {
const fold = xs =>
List(xs).foldMap(x => x.toString())
t.same(fold([ 1, 2 ]), '12', 'combines and extracts semigroups')
t.same(fold([ 3 ]), '3', 'extracts a single semigroup')
t.end()
})
test('List filter fantasy-land errors', t => {
const filter = bindFunc(List([ 0 ])[fl.filter])
const err = /List.fantasy-land\/filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter errors', t => {
const filter = bindFunc(List([ 0 ]).filter)
const err = /List.filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.filter(bigNum).valueOf(), [ 34 ], 'filters for bigNums with function')
t.same(m.filter(justStrings).valueOf(), [ 'string' ], 'filters for strings with function')
t.same(m.filter(bigNumPred).valueOf(), [ 34 ], 'filters for bigNums with Pred')
t.same(m.filter(justStringsPred).valueOf(), [ 'string' ], 'filters for strings with Pred')
t.end()
})
test('List filter properties (Filterable)', t => {
const m = List([ 2, 6, 10, 25, 9, 28 ])
const n = List([ 'string', 'party' ])
const isEven = x => x % 2 === 0
const isBig = x => x >= 10
const left = m.filter(x => isBig(x) && isEven(x)).valueOf()
const right = m.filter(isBig).filter(isEven).valueOf()
t.same(left, right , 'distributivity')
t.same(m.filter(() => true).valueOf(), m.valueOf(), 'identity')
t.same(m.filter(() => false).valueOf(), n.filter(() => false).valueOf(), 'annihilation')
t.end()
})
test('List reject errors', t => {
const reject = bindFunc(List([ 0 ]).reject)
const err = /List.reject: Pred or predicate function required/
t.throws(reject(undefined), err, 'throws with undefined')
t.throws(reject(null), err, 'throws with null')
t.throws(reject(0), err, 'throws with falsey number')
t.throws(reject(1), err, 'throws with truthy number')
t.throws(reject(''), err, 'throws with falsey string')
t.throws(reject('string'), err, 'throws with truthy string')
t.throws(reject(false), err, 'throws with false')
t.throws(reject(true), err, 'throws with true')
t.throws(reject([]), err, 'throws with an array')
t.throws(reject({}), err, 'throws with an object')
t.end()
})
test('List reject functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.reject(bigNum).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with function')
t.same(m.reject(justStrings).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with function')
t.same(m.reject(bigNumPred).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with Pred')
t.same(m.reject(justStringsPred).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with Pred')
t.end()
})
test('List map errors', t => {
const map = bindFunc(List([]).map)
const err = /List.map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map fantasy-land errors', t => {
const map = bindFunc(List([])[fl.map])
const err = /List.fantasy-land\/map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map functionality', t => {
const spy = sinon.spy(identity)
const xs = [ 42 ]
const m = List(xs).map(spy)
t.equal(m.type(), 'List', 'returns a List')
t.equal(spy.called, true, 'calls mapping function')
t.same(m.valueOf(), xs, 'returns the result of the map inside of new List')
t.end()
})
test('List map properties (Functor)', t => {
const m = List([ 49 ])
const f = x => x + 54
const g = x => x * 4
t.ok(isFunction(m.map), 'provides a map function')
t.same(m.map(identity).valueOf(), m.valueOf(), 'identity')
t.same(m.map(_compose(f, g)).valueOf(), m.map(g).map(f).valueOf(), 'composition')
t.end()
})
test('List ap errors', t => {
const left = bindFunc(x => List([ x ]).ap(List([ 0 ])))
const noFunc = /List.ap: Wrapped values must all be functions/
t.throws(left([ undefined ]), noFunc, 'throws when wrapped value is undefined')
t.throws(left([ null ]), noFunc, 'throws when wrapped value is null')
t.throws(left([ 0 ]), noFunc, 'throws when wrapped value is a falsey number')
t.throws(left([ 1 ]), noFunc, 'throws when wrapped value is a truthy number')
t.throws(left([ '' ]), noFunc, 'throws when wrapped value is a falsey string')
t.throws(left([ 'string' ]), noFunc, 'throws when wrapped value is a truthy string')
t.throws(left([ false ]), noFunc, 'throws when wrapped value is false')
t.throws(left([ true ]), noFunc, 'throws when wrapped value is true')
t.throws(left([ [] ]), noFunc, 'throws when wrapped value is an array')
t.throws(left([ {} ]), noFunc, 'throws when wrapped value is an object')
t.throws(left([ unit, 'string' ]), noFunc, 'throws when wrapped values are not all functions')
const ap = bindFunc(x => List([ unit ]).ap(x))
const noList = /List.ap: List required/
t.throws(ap(undefined), noList, 'throws with undefined')
t.throws(ap(null), noList, 'throws with null')
t.throws(ap(0), noList, 'throws with falsey number')
t.throws(ap(1), noList, 'throws with truthy number')
t.throws(ap(''), noList, 'throws with falsey string')
t.throws(ap('string'), noList, 'throws with truthy string')
t.throws(ap(false), noList, 'throws with false')
t.throws(ap(true), noList, 'throws with true')
t.throws(ap([]), noList, 'throws with an array')
t.throws(ap({}), noList, 'throws with an object')
t.end()
})
test('List ap properties (Apply)', t => {
const m = List([ identity ])
const a = m.map(_compose).ap(m).ap(m)
const b = m.ap(m.ap(m))
t.ok(isFunction(List([]).ap), 'provides an ap function')
t.ok(isFunction(List([]).map), 'implements the Functor spec')
t.same(a.ap(List([ 3 ])).valueOf(), b.ap(List([ 3 ])).valueOf(), 'composition')
t.end()
})
test('List of', t => {
t.equal(List.of, List([]).of, 'List.of is the same as the instance version')
t.equal(List.of(0).type(), 'List', 'returns a List')
t.same(List.of(0).valueOf(), [ 0 ], 'wraps the value passed into List in an array')
t.end()
})
test('List of properties (Applicative)', t => {
const m = List([ identity ])
t.ok(isFunction(List([]).of), 'provides an of function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
t.same(m.ap(List([ 3 ])).valueOf(), [ 3 ], 'identity')
t.same(m.ap(List.of(3)).valueOf(), List.of(identity(3)).valueOf(), 'homomorphism')
const a = x => m.ap(List.of(x))
const b = x => List.of(applyTo(x)).ap(m)
t.same(a(3).valueOf(), b(3).valueOf(), 'interchange')
t.end()
})
test('List chain errors', t => {
const chain = bindFunc(List([ 0 ]).chain)
const bad = bindFunc(x => List.of(x).chain(identity))
const noFunc = /List.chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain fantasy-land errors', t => {
const chain = bindFunc(List([ 0 ])[fl.chain])
const bad = bindFunc(x => List.of(x)[fl.chain](identity))
const noFunc = /List.fantasy-land\/chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.fantasy-land\/chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain properties (Chain)', t => {
t.ok(isFunction(List([]).chain), 'provides a chain function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
const f = x => List.of(x + 2)
const g = x => List.of(x + 10)
const a = x => List.of(x).chain(f).chain(g)
const b = x => List.of(x).chain(y => f(y).chain(g))
t.same(a(10).valueOf(), b(10).valueOf(), 'assosiativity')
t.end()
})
test('List chain properties (Monad)', t => {
t.ok(isFunction(List([]).chain), 'implements the Chain spec')
t.ok(isFunction(List([]).of), 'implements the Applicative spec')
const f = x => List([ x ])
t.same(List.of(3).chain(f).valueOf(), f(3).valueOf(), 'left identity')
t.same(f(3).chain(List.of).valueOf(), f(3).valueOf(), 'right identity')
t.end()
})
test('List sequence errors', t => {
const seq = bindFunc(List.of(MockCrock(2)).sequence)
const seqBad = bindFunc(List.of(0).sequence)
const err = /List.sequence: Applicative TypeRep or Apply returning function required/
t.throws(seq(undefined), err, 'throws with undefined')
t.throws(seq(null), err, 'throws with null')
t.throws(seq(0), err, 'throws falsey with number')
t.throws(seq(1), err, 'throws truthy with number')
t.throws(seq(''), err, 'throws falsey with string')
t.throws(seq('string'), err, 'throws with truthy string')
t.throws(seq(false), err, 'throws with false')
t.throws(seq(true), err, 'throws with true')
t.throws(seq([]), err, 'throws with an array')
t.throws(seq({}), err, 'throws with an object')
const noAppl = /List.sequence: Must wrap Applys of the same type/
t.throws(seqBad(unit), noAppl, 'wrapping non-Apply throws')
t.end()
})
test('List sequence with Apply function', t => {
const x = 'string'
const fn = x => MockCrock(x)
const m = List.of(MockCrock(x)).sequence(fn)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = x => [ x ]
const arM = List.of([ x ]).sequence(ar)
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List sequence with Applicative TypeRep', t => {
const x = 'string'
const m = List.of(MockCrock(x)).sequence(MockCrock)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = List.of([ x ]).sequence(Array)
t.ok(isSameType(Array, ar), 'Provides an outer type of Array')
t.ok(isSameType(List, ar[0]), 'Provides an inner type of List')
t.same(ar[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List traverse errors', t => {
const trav = bindFunc(List.of(2).traverse)
const first = /List.traverse: Applicative TypeRep or Apply returning function required for first argument/
t.throws(trav(undefined, MockCrock), first, 'throws with undefined in first argument')
t.throws(trav(null, MockCrock), first, 'throws with null in first argument')
t.throws(trav(0, MockCrock), first, 'throws falsey with number in first argument')
t.throws(trav(1, MockCrock), first, 'throws truthy with number in first argument')
t.throws(trav('', MockCrock), first, 'throws falsey with string in first argument')
t.throws(trav('string', MockCrock), first, 'throws with truthy string in first argument')
t.throws(trav(false, MockCrock), first, 'throws with false in first argument')
t.throws(trav(true, MockCrock), first, 'throws with true in first argument')
t.throws(trav([], MockCrock), first, 'throws with an array in first argument')
t.throws(trav({}, MockCrock), first, 'throws with an object in first argument')
const second = /List.traverse: Apply returning functions required for second argument/
t.throws(trav(MockCrock, undefined), second, 'throws with undefined in second argument')
t.throws(trav(MockCrock, null), second, 'throws with null in second argument')
t.throws(trav(MockCrock, 0), second, 'throws falsey with number in second argument')
t.throws(trav(MockCrock, 1), second, 'throws truthy with number in second argument')
t.throws(trav(MockCrock, ''), second, 'throws falsey with string in second argument')
t.throws(trav(MockCrock, 'string'), second, 'throws with truthy string in second argument')
t.throws(trav(MockCrock, false), second, 'throws with false in second argument')
t.throws(trav(MockCrock, true), second, 'throws with true in second argument')
t.throws(trav(MockCrock, []), second, 'throws with an array in second argument')
t.throws(trav(MockCrock, {}), second, 'throws with an object in second argument')
const noAppl = /List.traverse: Both functions must return an Apply of the same type/
t.throws(trav(unit, MockCrock), noAppl, 'throws with non-Appicative returning function in first argument')
t.throws(trav(MockCrock, unit), noAppl, 'throws with non-Appicative returning function in second argument')
t.end()
})
test('List traverse with Apply function', t => {
const x = 'string'
const res = 'result'
const f = x => MockCrock(x)
const fn = m => constant(m(res))
const m = List.of(x).traverse(f, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(ar, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})
test('List traverse with Applicative TypeRep', t => {
const x = 'string'
const res = 'result'
const fn = m => constant(m(res))
const m = List.of(x).traverse(MockCrock, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(Array, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})
|
Subsets and Splits