code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
'use strict'; angular.module('openshiftConsole') .directive('overviewDeployment', function($location, $timeout, LabelFilter) { return { restrict: 'E', scope: { // Replication controller / deployment fields rc: '=', deploymentConfigId: '=', deploymentConfigMissing: '=', deploymentConfigDifferentService: '=', // Nested podTemplate fields imagesByDockerReference: '=', builds: '=', // Pods pods: '=' }, templateUrl: 'views/_overview-deployment.html', controller: function($scope) { $scope.viewPodsForDeployment = function(deployment) { $location.url("/project/" + deployment.metadata.namespace + "/browse/pods"); $timeout(function() { LabelFilter.setLabelSelector(new LabelSelector(deployment.spec.selector, true)); }, 1); }; } }; }) .directive('overviewMonopod', function() { return { restrict: 'E', scope: { pod: '=' }, templateUrl: 'views/_overview-monopod.html' }; }) .directive('podTemplate', function() { return { restrict: 'E', scope: { podTemplate: '=', imagesByDockerReference: '=', builds: '=' }, templateUrl: 'views/_pod-template.html' }; }) .directive('pods', function() { return { restrict: 'E', scope: { pods: '=', projectName: '@?' //TODO optional for now }, templateUrl: 'views/_pods.html', controller: function($scope) { $scope.phases = [ "Failed", "Pending", "Running", "Succeeded", "Unknown" ]; $scope.expandedPhase = null; $scope.warningsExpanded = false; $scope.expandPhase = function(phase, warningsExpanded, $event) { $scope.expandedPhase = phase; $scope.warningsExpanded = warningsExpanded; if ($event) { $event.stopPropagation(); } }; } }; }) .directive('podContent', function() { // sub-directive used by the pods directive return { restrict: 'E', scope: { pod: '=', troubled: '=' }, templateUrl: 'views/directives/_pod-content.html' }; }) .directive('triggers', function() { var hideBuildKey = function(build) { return 'hide/build/' + build.metadata.namespace + '/' + build.metadata.name; }; return { restrict: 'E', scope: { triggers: '=' }, link: function(scope) { scope.isBuildHidden = function(build) { var key = hideBuildKey(build); return sessionStorage.getItem(key) === 'true'; }; scope.hideBuild = function(build) { var key = hideBuildKey(build); sessionStorage.setItem(key, 'true'); }; }, templateUrl: 'views/_triggers.html' }; }) .directive('deploymentConfigMetadata', function() { return { restrict: 'E', scope: { deploymentConfigId: '=', exists: '=', differentService: '=' }, templateUrl: 'views/_deployment-config-metadata.html' }; });
domenicbove/origin
assets/app/scripts/directives/resources.js
JavaScript
apache-2.0
3,240
/* * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ var RokIEWarn=new Class({site:"sitename",initialize:function(f){var d=f;this.box=new Element("div",{id:"iewarn"}).inject(document.body,"top");var g=new Element("div").inject(this.box).set("html",d); var e=this.toggle.bind(this);var c=new Element("a",{id:"iewarn_close"}).addEvents({mouseover:function(){this.addClass("cHover");},mouseout:function(){this.removeClass("cHover"); },click:function(){e();}}).inject(g,"top");this.height=document.id("iewarn").getSize().y;this.fx=new Fx.Morph(this.box,{duration:1000}).set({top:document.id("iewarn").getStyle("top").toInt()}); this.open=false;var b=Cookie.read("rokIEWarn"),a=this.height;if(!b||b=="open"){this.show();}else{this.fx.set({top:-a});}return;},show:function(){this.fx.start({top:0}); this.open=true;Cookie.write("rokIEWarn","open",{duration:7});},close:function(){var a=this.height;this.fx.start({top:-a});this.open=false;Cookie.write("rokIEWarn","close",{duration:7}); },status:function(){return this.open;},toggle:function(){if(this.open){this.close();}else{this.show();}}});
devxive/nawala-rdk
src/lib_gantry/js/gantry-ie6warn.js
JavaScript
apache-2.0
1,220
/** * */ var obj = { num: 123, str: 'hello', }; obj.
JonathanUsername/flow
newtests/autocomplete/foo.js
JavaScript
mit
61
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 }
cigraphics/phpjs
experimental/errorfunc/error_log.js
JavaScript
mit
2,020
'use strict' const Buffer = require('safe-buffer').Buffer const crypto = require('crypto') const Transform = require('stream').Transform const SPEC_ALGORITHMS = ['sha256', 'sha384', 'sha512'] const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i const SRI_REGEX = /^([^-]+)-([^?]+)([?\S*]*)$/ const STRICT_SRI_REGEX = /^([^-]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)*$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ class Hash { get isHash () { return true } constructor (hash, opts) { const strict = !!(opts && opts.strict) this.source = hash.trim() // 3.1. Integrity metadata (called "Hash" by ssri) // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description const match = this.source.match( strict ? STRICT_SRI_REGEX : SRI_REGEX ) if (!match) { return } if (strict && !SPEC_ALGORITHMS.some(a => a === match[1])) { return } this.algorithm = match[1] this.digest = match[2] const rawOpts = match[3] this.options = rawOpts ? rawOpts.slice(1).split('?') : [] } hexDigest () { return this.digest && Buffer.from(this.digest, 'base64').toString('hex') } toJSON () { return this.toString() } toString (opts) { if (opts && opts.strict) { // Strict mode enforces the standard as close to the foot of the // letter as it can. if (!( // The spec has very restricted productions for algorithms. // https://www.w3.org/TR/CSP2/#source-list-syntax SPEC_ALGORITHMS.some(x => x === this.algorithm) && // Usually, if someone insists on using a "different" base64, we // leave it as-is, since there's multiple standards, and the // specified is not a URL-safe variant. // https://www.w3.org/TR/CSP2/#base64_value this.digest.match(BASE64_REGEX) && // Option syntax is strictly visual chars. // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression // https://tools.ietf.org/html/rfc5234#appendix-B.1 (this.options || []).every(opt => opt.match(VCHAR_REGEX)) )) { return '' } } const options = this.options && this.options.length ? `?${this.options.join('?')}` : '' return `${this.algorithm}-${this.digest}${options}` } } class Integrity { get isIntegrity () { return true } toJSON () { return this.toString() } toString (opts) { opts = opts || {} let sep = opts.sep || ' ' if (opts.strict) { // Entries must be separated by whitespace, according to spec. sep = sep.replace(/\S+/g, ' ') } return Object.keys(this).map(k => { return this[k].map(hash => { return Hash.prototype.toString.call(hash, opts) }).filter(x => x.length).join(sep) }).filter(x => x.length).join(sep) } concat (integrity, opts) { const other = typeof integrity === 'string' ? integrity : stringify(integrity, opts) return parse(`${this.toString(opts)} ${other}`, opts) } hexDigest () { return parse(this, {single: true}).hexDigest() } match (integrity, opts) { const other = parse(integrity, opts) const algo = other.pickAlgorithm(opts) return ( this[algo] && other[algo] && this[algo].find(hash => other[algo].find(otherhash => hash.digest === otherhash.digest ) ) ) || false } pickAlgorithm (opts) { const pickAlgorithm = (opts && opts.pickAlgorithm) || getPrioritizedHash const keys = Object.keys(this) if (!keys.length) { throw new Error(`No algorithms available for ${ JSON.stringify(this.toString()) }`) } return keys.reduce((acc, algo) => { return pickAlgorithm(acc, algo) || acc }) } } module.exports.parse = parse function parse (sri, opts) { opts = opts || {} if (typeof sri === 'string') { return _parse(sri, opts) } else if (sri.algorithm && sri.digest) { const fullSri = new Integrity() fullSri[sri.algorithm] = [sri] return _parse(stringify(fullSri, opts), opts) } else { return _parse(stringify(sri, opts), opts) } } function _parse (integrity, opts) { // 3.4.3. Parse metadata // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata if (opts.single) { return new Hash(integrity, opts) } return integrity.trim().split(/\s+/).reduce((acc, string) => { const hash = new Hash(string, opts) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.stringify = stringify function stringify (obj, opts) { if (obj.algorithm && obj.digest) { return Hash.prototype.toString.call(obj, opts) } else if (typeof obj === 'string') { return stringify(parse(obj, opts), opts) } else { return Integrity.prototype.toString.call(obj, opts) } } module.exports.fromHex = fromHex function fromHex (hexDigest, algorithm, opts) { const optString = (opts && opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' return parse( `${algorithm}-${ Buffer.from(hexDigest, 'hex').toString('base64') }${optString}`, opts ) } module.exports.fromData = fromData function fromData (data, opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' return algorithms.reduce((acc, algo) => { const digest = crypto.createHash(algo).update(data).digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.fromStream = fromStream function fromStream (stream, opts) { opts = opts || {} const P = opts.Promise || Promise const istream = integrityStream(opts) return new P((resolve, reject) => { stream.pipe(istream) stream.on('error', reject) istream.on('error', reject) let sri istream.on('integrity', s => { sri = s }) istream.on('end', () => resolve(sri)) istream.on('data', () => {}) }) } module.exports.checkData = checkData function checkData (data, sri, opts) { opts = opts || {} sri = parse(sri, opts) if (!Object.keys(sri).length) { if (opts.error) { throw Object.assign( new Error('No valid integrity hashes to check against'), { code: 'EINTEGRITY' } ) } else { return false } } const algorithm = sri.pickAlgorithm(opts) const digest = crypto.createHash(algorithm).update(data).digest('base64') const newSri = parse({algorithm, digest}) const match = newSri.match(sri, opts) if (match || !opts.error) { return match } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) err.code = 'EBADSIZE' err.found = data.length err.expected = opts.size err.sri = sri throw err } else { const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = sri err.algorithm = algorithm err.sri = sri throw err } } module.exports.checkStream = checkStream function checkStream (stream, sri, opts) { opts = opts || {} const P = opts.Promise || Promise const checker = integrityStream(Object.assign({}, opts, { integrity: sri })) return new P((resolve, reject) => { stream.pipe(checker) stream.on('error', reject) checker.on('error', reject) let sri checker.on('verified', s => { sri = s }) checker.on('end', () => resolve(sri)) checker.on('data', () => {}) }) } module.exports.integrityStream = integrityStream function integrityStream (opts) { opts = opts || {} // For verification const sri = opts.integrity && parse(opts.integrity, opts) const goodSri = sri && Object.keys(sri).length const algorithm = goodSri && sri.pickAlgorithm(opts) const digests = goodSri && sri[algorithm] // Calculating stream const algorithms = Array.from( new Set( (opts.algorithms || ['sha512']) .concat(algorithm ? [algorithm] : []) ) ) const hashes = algorithms.map(crypto.createHash) let streamSize = 0 const stream = new Transform({ transform (chunk, enc, cb) { streamSize += chunk.length hashes.forEach(h => h.update(chunk, enc)) cb(null, chunk, enc) } }).on('end', () => { const optString = (opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' const newSri = parse(hashes.map((h, i) => { return `${algorithms[i]}-${h.digest('base64')}${optString}` }).join(' '), opts) // Integrity verification mode const match = goodSri && newSri.match(sri, opts) if (typeof opts.size === 'number' && streamSize !== opts.size) { const err = new Error(`stream size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${streamSize}`) err.code = 'EBADSIZE' err.found = streamSize err.expected = opts.size err.sri = sri stream.emit('error', err) } else if (opts.integrity && !match) { const err = new Error(`${sri} integrity checksum failed when using ${algorithm}: wanted ${digests} but got ${newSri}. (${streamSize} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = digests err.algorithm = algorithm err.sri = sri stream.emit('error', err) } else { stream.emit('size', streamSize) stream.emit('integrity', newSri) match && stream.emit('verified', match) } }) return stream } module.exports.create = createIntegrity function createIntegrity (opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' const hashes = algorithms.map(crypto.createHash) return { update: function (chunk, enc) { hashes.forEach(h => h.update(chunk, enc)) return this }, digest: function (enc) { const integrity = algorithms.reduce((acc, algo) => { const digest = hashes.shift().digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) return integrity } } } const NODE_HASHES = new Set(crypto.getHashes()) // This is a Best Effort™ at a reasonable priority for hash algos const DEFAULT_PRIORITY = [ 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', // TODO - it's unclear _which_ of these Node will actually use as its name // for the algorithm, so we guesswork it based on the OpenSSL names. 'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512' ].filter(algo => NODE_HASHES.has(algo)) function getPrioritizedHash (algo1, algo2) { return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) ? algo1 : algo2 }
veerhiremath7/veerhiremath7.github.io
node_modules/ssri/index.js
JavaScript
unlicense
11,559
/** * DO NOT EDIT THIS FILE. * See the following change record for more information, * https://www.drupal.org/node/2815083 * @preserve **/ (function (_, $, Backbone, Drupal) { Drupal.quickedit.EntityModel = Drupal.quickedit.BaseModel.extend({ defaults: { el: null, entityID: null, entityInstanceID: null, id: null, label: null, fields: null, isActive: false, inTempStore: false, isDirty: false, isCommitting: false, state: 'closed', fieldsInTempStore: [], reload: false }, initialize: function initialize() { this.set('fields', new Drupal.quickedit.FieldCollection()); this.listenTo(this, 'change:state', this.stateChange); this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange); Drupal.quickedit.BaseModel.prototype.initialize.call(this); }, stateChange: function stateChange(entityModel, state, options) { var to = state; switch (to) { case 'closed': this.set({ isActive: false, inTempStore: false, isDirty: false }); break; case 'launching': break; case 'opening': entityModel.get('fields').each(function (fieldModel) { fieldModel.set('state', 'candidate', options); }); break; case 'opened': this.set('isActive', true); break; case 'committing': { var fields = this.get('fields'); fields.chain().filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['active']).length; }).each(function (fieldModel) { fieldModel.set('state', 'candidate'); }); fields.chain().filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], Drupal.quickedit.app.changedFieldStates).length; }).each(function (fieldModel) { fieldModel.set('state', 'saving'); }); break; } case 'deactivating': { var changedFields = this.get('fields').filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length; }); if ((changedFields.length || this.get('fieldsInTempStore').length) && !options.saved && !options.confirmed) { this.set('state', 'opened', { confirming: true }); _.defer(function () { Drupal.quickedit.app.confirmEntityDeactivation(entityModel); }); } else { var invalidFields = this.get('fields').filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['invalid']).length; }); entityModel.set('reload', this.get('fieldsInTempStore').length || invalidFields.length); entityModel.get('fields').each(function (fieldModel) { if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) { fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options); } else { fieldModel.set('state', 'candidate', options); } }); } break; } case 'closing': options.reason = 'stop'; this.get('fields').each(function (fieldModel) { fieldModel.set({ inTempStore: false, state: 'inactive' }, options); }); break; } }, _updateInTempStoreAttributes: function _updateInTempStoreAttributes(entityModel, fieldModel) { var current = fieldModel.get('state'); var previous = fieldModel.previous('state'); var fieldsInTempStore = entityModel.get('fieldsInTempStore'); if (current === 'saved') { entityModel.set('inTempStore', true); fieldModel.set('inTempStore', true); fieldsInTempStore.push(fieldModel.get('fieldID')); fieldsInTempStore = _.uniq(fieldsInTempStore); entityModel.set('fieldsInTempStore', fieldsInTempStore); } else if (current === 'candidate' && previous === 'inactive') { fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0); } }, fieldStateChange: function fieldStateChange(fieldModel, state) { var entityModel = this; var fieldState = state; switch (this.get('state')) { case 'closed': case 'launching': break; case 'opening': _.defer(function () { entityModel.set('state', 'opened', { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }); }); break; case 'opened': if (fieldState === 'changed') { entityModel.set('isDirty', true); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } break; case 'committing': { if (fieldState === 'invalid') { _.defer(function () { entityModel.set('state', 'opened', { reason: 'invalid' }); }); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } var options = { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }; if (entityModel.set('isCommitting', true, options)) { entityModel.save({ success: function success() { entityModel.set({ state: 'deactivating', isCommitting: false }, { saved: true }); }, error: function error() { entityModel.set('isCommitting', false); entityModel.set('state', 'opened', { reason: 'networkerror' }); var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', { '@entity-title': entityModel.get('label') }); Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message); } }); } break; } case 'deactivating': _.defer(function () { entityModel.set('state', 'closing', { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }); }); break; case 'closing': _.defer(function () { entityModel.set('state', 'closed', { 'accept-field-states': ['inactive'] }); }); break; } }, save: function save(options) { var entityModel = this; var entitySaverAjax = Drupal.ajax({ url: Drupal.url('quickedit/entity/' + entityModel.get('entityID')), error: function error() { options.error.call(entityModel); } }); entitySaverAjax.commands.quickeditEntitySaved = function (ajax, response, status) { entityModel.get('fields').each(function (fieldModel) { fieldModel.set('inTempStore', false); }); entityModel.set('inTempStore', false); entityModel.set('fieldsInTempStore', []); if (options.success) { options.success.call(entityModel); } }; entitySaverAjax.execute(); }, validate: function validate(attrs, options) { var acceptedFieldStates = options['accept-field-states'] || []; var currentState = this.get('state'); var nextState = attrs.state; if (currentState !== nextState) { if (_.indexOf(this.constructor.states, nextState) === -1) { return '"' + nextState + '" is an invalid state'; } if (!this._acceptStateChange(currentState, nextState, options)) { return 'state change not accepted'; } else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'state change not accepted because fields are not in acceptable state'; } } var currentIsCommitting = this.get('isCommitting'); var nextIsCommitting = attrs.isCommitting; if (currentIsCommitting === false && nextIsCommitting === true) { if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'isCommitting change not accepted because fields are not in acceptable state'; } } else if (currentIsCommitting === true && nextIsCommitting === true) { return 'isCommitting is a mutex, hence only changes are allowed'; } }, _acceptStateChange: function _acceptStateChange(from, to, context) { var accept = true; if (!this.constructor.followsStateSequence(from, to)) { accept = false; if (from === 'closing' && to === 'closed') { accept = true; } else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) { accept = true; } else if (from === 'deactivating' && to === 'opened' && context.confirming) { accept = true; } else if (from === 'opened' && to === 'deactivating' && context.confirmed) { accept = true; } } return accept; }, _fieldsHaveAcceptableStates: function _fieldsHaveAcceptableStates(acceptedFieldStates) { var accept = true; if (acceptedFieldStates.length > 0) { var fieldStates = this.get('fields').pluck('state') || []; if (_.difference(fieldStates, acceptedFieldStates).length) { accept = false; } } return accept; }, destroy: function destroy(options) { Drupal.quickedit.BaseModel.prototype.destroy.call(this, options); this.stopListening(); this.get('fields').reset(); }, sync: function sync() {} }, { states: ['closed', 'launching', 'opening', 'opened', 'committing', 'deactivating', 'closing'], followsStateSequence: function followsStateSequence(from, to) { return _.indexOf(this.states, from) < _.indexOf(this.states, to); } }); Drupal.quickedit.EntityCollection = Backbone.Collection.extend({ model: Drupal.quickedit.EntityModel }); })(_, jQuery, Backbone, Drupal);
isauragalafate/drupal8
web/core/modules/quickedit/js/models/EntityModel.js
JavaScript
gpl-2.0
10,662
var $ = require('common:widget/ui/jquery/jquery.js'); var UT = require('common:widget/ui/ut/ut.js'); var FBClient = {}; var TPL_CONF = require('home:widget/ui/facebook/fbclient-tpl.js'); /** * Fackbook module init function * @return {object} [description] */ var WIN = window, DOC = document, conf = WIN.conf.FBClient, undef; var UI_CONF = { // ui el uiMod: "#fbMod" , uiBtnLogin: ".fb-mod_login_btn" , uiBtnLogout: ".fb-mod_logout" , uiBtnRefresh: ".fb-mod_refresh" , uiSide: ".fb-mod_side" , uiBtnClose: ".fb-mod_close" , uiWrap: ".fb-mod_wrap" , uiList: ".fb-mod_list" , uiUsrinfo: ".fb-mod_usrinfo" , uiAvatar: ".fb-mod_avatar" , uiTextareaSubmit: ".fb-mod_submit" , uiBtnSubmit: ".fb-mod_submit_btn" , uiBody: ".fb-mod_body" , uiTip: ".fb-mod_tip" , uiSideHome: ".fb-mod_side_home" , uiSideFriend: ".fb-mod_side_friend em" , uiSideMessages: ".fb-mod_side_messages em" , uiSideNotifications: ".fb-mod_side_notifications em" , uiBodyLoader: ".fb-mod_body_loader" }; FBClient.init = function() { // DOC.body.innerHTML += '<div id="fb-root"></div>'; var that = this, $this = $(UI_CONF.uiMod); /* ui controller */ that.ui = { uiMod: $this , side: $this.find(UI_CONF.uiSide) , btnLogin: $this.find(UI_CONF.uiBtnLogin) , btnLogout: $this.find(UI_CONF.uiBtnLogout) , btnClose: $this.find(UI_CONF.uiBtnClose) , btnRefresh: $this.find(UI_CONF.uiBtnRefresh) , wrap: $this.find(UI_CONF.uiWrap) , list: $this.find(UI_CONF.uiList) , usrinfo: $this.find(UI_CONF.uiUsrinfo) , avatar: $this.find(UI_CONF.uiAvatar) , textareaSubmit: $this.find(UI_CONF.uiTextareaSubmit) , btnSubmit: $this.find(UI_CONF.uiBtnSubmit) , body: $this.find(UI_CONF.uiBody) , tip: $this.find(UI_CONF.uiTip) , sideHome: $this.find(UI_CONF.uiSideHome) , sideFriend: $this.find(UI_CONF.uiSideFriend) , sideNotifications: $this.find(UI_CONF.uiSideNotifications) , sideMessages: $this.find(UI_CONF.uiSideMessages) , bodyLoader: $this.find(UI_CONF.uiBodyLoader) , panelHome: $this.find(".fb-mod_c") , panelFriend: $('<div class="fb-mod_c fb-mod_c_friend" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelNotifications: $('<div class="fb-mod_c fb-mod_c_notifications" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelMessages: $('<div class="fb-mod_c fb-mod_c_messages" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , bubble: $('<div class="fb-mod_bubble">' + (conf.tplBubble || "NEW") + '</div>') , placeholder: function(first, last) { return $(TPL_CONF.tplPlaceholder.replaceTpl({first: first, last: last })) } }; // live loader that.ui.liveLoader = that.ui.bodyLoader.clone(!0) .css({"width": "370px"}) .insertBefore(that.ui.list).hide(); $("body").append('<div id="fb-root" class=" fb_reset"></div>'); that.ui.wrap.append(that.ui.panelFriend).append(that.ui.panelNotifications).append(that.ui.panelMessages); // window.ActiveXObject && !window.XMLHttpRequest && $("body").append(that.ui.fakeBox = $(that.ui.textareaSubmit[0].cloneNode(false)).css({ "position": "absolute" , "top" : "0" , "left": "0" , "right": "-10000px" , "visibility": "hidden" , "padding-top": "0" , "padding-bottom": "0" , "height": "18" //for fixed , "width": that.ui.textareaSubmit.width() })); that.supportAnimate = function(style, name) { return 't' + name in style || 'webkitT' + name in style || 'MozT' + name in style || 'OT' + name in style; }((new Image).style, "ransition"); /* status controller 0 ==> none 1 ==> doing 2 ==> done */ that.status = { login: 0 , fold: 0 , sdkLoaded: 0 , scrollLoaded: 0 , insertLoaded: 0 , fixed: 0 , eventBinded: 0 , bubble: 0 }; // bubble !$.cookie("fb_bubble") && (that.status.bubble = 1, that.ui.uiMod.append(that.ui.bubble)); /* post status cache */ that.cache = { prePost: null , nextPost: null , refreshPost: null , noOldPost: 0 , myPost: 0 , stayTip: "" , userID: null , userName: "" , panel: that.ui.panelHome , curSideType: "" , panelRendered: 0 }; that.ui.btnClose.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_logo").mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_home").mousedown(function(e) { UT && that.status.fold === 0 && UT.send({"type": "click", "position": "fb", "sort": "pull","modId":"fb-box"}); UT && UT.send({"type": "click", "position": "fb", "sort": "icon_home","modId":"fb-box"}); that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_home_cur", that.ui.panelHome); }); $(".fb-mod_side_friend").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_friend", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_friend_cur", that.ui.panelFriend); }); $(".fb-mod_side_messages").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_messages", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_messages_cur", that.ui.panelMessages); }); $(".fb-mod_side_notifications").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_notifications", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_notifications_cur", that.ui.panelNotifications); }); that.ui.btnRefresh.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": "refresh","modId":"fb-box"}); }); $(".fb-mod_side_friend").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_messages").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_notifications").click(function(e) { e.preventDefault(); }); // 7. FB-APP的打开、收缩机制;——点击F、箭头、new三个地方打开,点击F、箭头两个地方关闭;做上新功能上线的提示图标,放cookies内; // // kill the feature // that.ui.side.mouseover(function(e) { // that.status.fold === 0 && that.foldHandle.call(that, e); // }); that.ui.textareaSubmit.attr("placeholder", conf.tplSuggestText); // sdk loading that.status.sdkLoaded = 1; /*$.ajax({ url: that.conf.modPath, dataType: "script", cache: true, success: function() { }, error: function() { } });*/ require.async('home:widget/ui/facebook/fbclient-core.js'); }; if(window.ActiveXObject && !window.XMLHttpRequest) { var body = DOC.body; if(body) { body.style.backgroundAttachment = 'fixed'; if(body.currentStyle.backgroundImage == "none") { body.style.backgroundImage = (DOC.domain.indexOf("https:") == 0) ? 'url(https:///)' : 'url(about:blank)'; } } } FBClient.clickHandle = function($el, type, panel) { var that = this, fold = that.status.fold, sideHome = that.ui.sideHome, cache = that.cache; // fold && sideHome.removeClass(type); cache.curSide && cache.curSide.removeClass(cache.curSideType); $el && $el.addClass(type); cache.curSide = $el; cache.curSideType = type; cache.panel && cache.panel.hide(); panel && panel.show(); cache.panel = panel; }; FBClient.foldHandle = function(e) { var that = this, fold = that.status.fold, sdkLoaded = that.status.sdkLoaded; // playing animation if(fold === 1) return; that.status.fold = 1; that.clickHandle(fold ? null : that.ui.sideHome, fold ? "" : "fb-mod_side_home_cur", that.ui.panelHome); that.status.bubble && ($.cookie("fb_bubble", 1), that.status.bubble = 0, that.ui.bubble.hide()); fold ? that.ui.uiMod.removeClass("fb-mod--fixed").addClass("fb-mod--fold") : that.ui.uiMod.removeClass("fb-mod--fold"); setTimeout(function() { // fold ? sideHome.removeClass("fb-mod_side_home_cur") : that.ui.sideHome.addClass("fb-mod_side_home_cur"), that.cache.curSideType = "fb-mod_side_home_cur"; (that.status.fold = fold ? 0 : 2) && that.status.fixed && that.ui.uiMod.addClass("fb-mod--fixed"); if (!that.status.eventBinded) { if (sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; } else { var t = setInterval(function () { if (that.status.sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; clearInterval(t); } }, 1000); } } if(fold || sdkLoaded) return; !function(el) { if($.browser.mozilla){ el.addEventListener('DOMMouseScroll',function(e){ el.scrollTop += e.detail > 0 ? 30 : -30; e.preventDefault(); }, !1); } else el.onmousewheel = function(e){ e = e || WIN.event; el.scrollTop += e.wheelDelta > 0 ? -30 : 30; e.returnValue = false; }; }(that.ui.body[0]) }, that.supportAnimate ? 300 : 0); }; module.exports = FBClient;
femxd/fxd
test/diff_fis3_smarty/product_code/hao123_fis3_smarty/home/widget/ui/facebook/fbclient.js
JavaScript
bsd-2-clause
11,122
/** * 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); }); };
Karnith/sails-generate-backend-gulp
templates/api/responses/notFound.js
JavaScript
mit
2,543
(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)}})})();
Asaf-S/jsdelivr
files/amcharts/3.21.0/xy.js
JavaScript
mit
21,406
/** * Copyright 2015 IBM Corp. * * 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. **/ var express = require("express"); var util = require("util"); var path = require("path"); var fs = require("fs"); var clone = require("clone"); var defaultContext = { page: { title: "Node-RED", favicon: "favicon.ico" }, header: { title: "Node-RED", image: "red/images/node-red.png" }, asset: { red: (process.env.NODE_ENV == "development")? "red/red.js":"red/red.min.js" } }; var themeContext = clone(defaultContext); var themeSettings = null; function serveFile(app,baseUrl,file) { try { var stats = fs.statSync(file); var url = baseUrl+path.basename(file); //console.log(url,"->",file); app.get(url,function(req, res) { res.sendfile(file); }); return "theme"+url; } catch(err) { //TODO: log filenotfound return null; } } module.exports = { init: function(settings) { var i; var url; themeContext = clone(defaultContext); themeSettings = null; if (settings.editorTheme) { var theme = settings.editorTheme; themeSettings = {}; var themeApp = express(); if (theme.page) { if (theme.page.css) { var styles = theme.page.css; if (!util.isArray(styles)) { styles = [styles]; } themeContext.page.css = []; for (i=0;i<styles.length;i++) { url = serveFile(themeApp,"/css/",styles[i]); if (url) { themeContext.page.css.push(url); } } } if (theme.page.favicon) { url = serveFile(themeApp,"/favicon/",theme.page.favicon) if (url) { themeContext.page.favicon = url; } } themeContext.page.title = theme.page.title || themeContext.page.title; } if (theme.header) { themeContext.header.title = theme.header.title || themeContext.header.title; if (theme.header.hasOwnProperty("url")) { themeContext.header.url = theme.header.url; } if (theme.header.hasOwnProperty("image")) { if (theme.header.image) { url = serveFile(themeApp,"/header/",theme.header.image); if (url) { themeContext.header.image = url; } } else { themeContext.header.image = null; } } } if (theme.deployButton) { if (theme.deployButton.type == "simple") { themeSettings.deployButton = { type: "simple" } if (theme.deployButton.label) { themeSettings.deployButton.label = theme.deployButton.label; } if (theme.deployButton.icon) { url = serveFile(themeApp,"/deploy/",theme.deployButton.icon); if (url) { themeSettings.deployButton.icon = url; } } } } if (theme.hasOwnProperty("userMenu")) { themeSettings.userMenu = theme.userMenu; } if (theme.login) { if (theme.login.image) { url = serveFile(themeApp,"/login/",theme.login.image); if (url) { themeContext.login = { image: url } } } } if (theme.hasOwnProperty("menu")) { themeSettings.menu = theme.menu; } return themeApp; } }, context: function() { return themeContext; }, settings: function() { return themeSettings; } }
mikestebbins/node-red
red/api/theme.js
JavaScript
apache-2.0
5,062
/*! 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; });
x112358/cdnjs
ajax/libs/asynquence-contrib/0.13.0/contrib.src.js
JavaScript
mit
50,809
/** * Copyright 2014 Google Inc. All Rights Reserved. * * 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. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Cloud Storage API * * @classdesc Lets you store and retrieve potentially-large, immutable data objects. * @namespace storage * @version v1 * @variation v1 * @this Storage * @param {object=} options Options for Storage */ function Storage(options) { var self = this; this._options = options || {}; this.bucketAccessControls = { /** * storage.bucketAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.insert * * @desc Creates a new ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.list * * @desc Retrieves ACL entries on the specified bucket. * * @alias storage.bucketAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.patch * * @desc Updates an ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.bucketAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.update * * @desc Updates an ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.buckets = { /** * storage.buckets.delete * * @desc Permanently deletes an empty bucket. * * @alias storage.buckets.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If set, only deletes the bucket if its metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If set, only deletes the bucket if its metageneration does not match this value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'DELETE' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.get * * @desc Returns metadata for the specified bucket. * * @alias storage.buckets.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.insert * * @desc Creates a new bucket. * * @alias storage.buckets.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'POST' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.list * * @desc Retrieves a list of buckets for a given project. * * @alias storage.buckets.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {integer=} params.maxResults - Maximum number of buckets to return. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to buckets whose names begin with this prefix. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'GET' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.patch * * @desc Updates a bucket. This method supports patch semantics. * * @alias storage.buckets.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PATCH' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.update * * @desc Updates a bucket. * * @alias storage.buckets.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PUT' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; this.channels = { /** * storage.channels.stop * * @desc Stop watching resources through this channel * * @alias storage.channels.stop * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ stop: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/channels/stop', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.defaultObjectAccessControls = { /** * storage.defaultObjectAccessControls.delete * * @desc Permanently deletes the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.get * * @desc Returns the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.insert * * @desc Creates a new default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.list * * @desc Retrieves default object ACL entries on the specified bucket. * * @alias storage.defaultObjectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If present, only return default ACL listing if the bucket's current metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If present, only return default ACL listing if the bucket's current metageneration does not match the given value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.patch * * @desc Updates a default object ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.defaultObjectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.update * * @desc Updates a default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.objectAccessControls = { /** * storage.objectAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.insert * * @desc Creates a new ACL entry on the specified object. * * @alias storage.objectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'POST' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.list * * @desc Retrieves ACL entries on the specified object. * * @alias storage.objectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.patch * * @desc Updates an ACL entry on the specified object. This method supports patch semantics. * * @alias storage.objectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.update * * @desc Updates an ACL entry on the specified object. * * @alias storage.objectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); } }; this.objects = { /** * storage.objects.compose * * @desc Concatenates a list of existing objects into a new object in the same bucket. * * @alias storage.objects.compose * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. * @param {string} params.destinationObject - Name of the new object. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ compose: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose', method: 'POST' }, params: params, requiredParams: ['destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.copy * * @desc Copies an object to a specified location. Optionally overrides metadata. * * @alias storage.objects.copy * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string} params.destinationObject - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the destination object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the destination object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the destination object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the destination object's current metageneration does not match the given value. * @param {string=} params.ifSourceGenerationMatch - Makes the operation conditional on whether the source object's generation matches the given value. * @param {string=} params.ifSourceGenerationNotMatch - Makes the operation conditional on whether the source object's generation does not match the given value. * @param {string=} params.ifSourceMetagenerationMatch - Makes the operation conditional on whether the source object's current metageneration matches the given value. * @param {string=} params.ifSourceMetagenerationNotMatch - Makes the operation conditional on whether the source object's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {string} params.sourceBucket - Name of the bucket in which to find the source object. * @param {string=} params.sourceGeneration - If present, selects a specific revision of the source object (as opposed to the latest version, the default). * @param {string} params.sourceObject - Name of the source object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ copy: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}', method: 'POST' }, params: params, requiredParams: ['sourceBucket', 'sourceObject', 'destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject', 'sourceBucket', 'sourceObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.delete * * @desc Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used. * * @alias storage.objects.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.get * * @desc Retrieves an object or its metadata. * * @alias storage.objects.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.insert * * @desc Stores a new object and metadata. * * @alias storage.objects.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string=} params.contentEncoding - If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string=} params.name - Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {object} params.resource - Media resource metadata * @param {object} params.media - Media object * @param {string} params.media.mimeType - Media mime-type * @param {string|object} params.media.body - Media body contents * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'POST' }, params: params, mediaUrl: 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o', requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.list * * @desc Retrieves a list of objects matching the criteria. * * @alias storage.objects.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.patch * * @desc Updates an object's metadata. This method supports patch semantics. * * @alias storage.objects.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.update * * @desc Updates an object's metadata. * * @alias storage.objects.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.watchAll * * @desc Watch for changes on all objects in a bucket. * * @alias storage.objects.watchAll * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watchAll: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/watch', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Storage object * @type Storage */ module.exports = Storage;
Shance/newsaity74.ru
templates/blank_j3/node_modules/psi/node_modules/googleapis/apis/storage/v1.js
JavaScript
gpl-2.0
48,996
// Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(window.crypto && window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes;
enketosurvey/mo
www/lib/rsa/rng.js
JavaScript
apache-2.0
2,112
/* ========================================================== * bootstrap-formhelpers-countries.en_US.js * https://github.com/vlamanna/BootstrapFormHelpers * ========================================================== * Copyright 2012 Vincent Lamanna * * 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. * ========================================================== */ var BFHCountriesList = { 'AF': 'Afghanistan', 'AL': 'Albania', 'DZ': 'Algeria', 'AS': 'American Samoa', 'AD': 'Andorra', 'AO': 'Angola', 'AI': 'Anguilla', 'AQ': 'Antarctica', 'AG': 'Antigua and Barbuda', 'AR': 'Argentina', 'AM': 'Armenia', 'AW': 'Aruba', 'AU': 'Australia', 'AT': 'Austria', 'AZ': 'Azerbaijan', 'BH': 'Bahrain', 'BD': 'Bangladesh', 'BB': 'Barbados', 'BY': 'Belarus', 'BE': 'Belgium', 'BZ': 'Belize', 'BJ': 'Benin', 'BM': 'Bermuda', 'BT': 'Bhutan', 'BO': 'Bolivia', 'BA': 'Bosnia and Herzegovina', 'BW': 'Botswana', 'BV': 'Bouvet Island', 'BR': 'Brazil', 'IO': 'British Indian Ocean Territory', 'VG': 'British Virgin Islands', 'BN': 'Brunei', 'BG': 'Bulgaria', 'BF': 'Burkina Faso', 'BI': 'Burundi', 'CI': 'Côte d\'Ivoire', 'KH': 'Cambodia', 'CM': 'Cameroon', 'CA': 'Canada', 'CV': 'Cape Verde', 'KY': 'Cayman Islands', 'CF': 'Central African Republic', 'TD': 'Chad', 'CL': 'Chile', 'CN': 'China', 'CX': 'Christmas Island', 'CC': 'Cocos (Keeling) Islands', 'CO': 'Colombia', 'KM': 'Comoros', 'CG': 'Congo', 'CK': 'Cook Islands', 'CR': 'Costa Rica', 'HR': 'Croatia', 'CU': 'Cuba', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'CD': 'Democratic Republic of the Congo', 'DK': 'Denmark', 'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'TP': 'East Timor', 'EC': 'Ecuador', 'EG': 'Egypt', 'SV': 'El Salvador', 'GQ': 'Equatorial Guinea', 'ER': 'Eritrea', 'EE': 'Estonia', 'ET': 'Ethiopia', 'FO': 'Faeroe Islands', 'FK': 'Falkland Islands', 'FJ': 'Fiji', 'FI': 'Finland', 'MK': 'Former Yugoslav Republic of Macedonia', 'FR': 'France', 'FX': 'France, Metropolitan', 'GF': 'French Guiana', 'PF': 'French Polynesia', 'TF': 'French Southern Territories', 'GA': 'Gabon', 'GE': 'Georgia', 'DE': 'Germany', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GR': 'Greece', 'GL': 'Greenland', 'GD': 'Grenada', 'GP': 'Guadeloupe', 'GU': 'Guam', 'GT': 'Guatemala', 'GN': 'Guinea', 'GW': 'Guinea-Bissau', 'GY': 'Guyana', 'HT': 'Haiti', 'HM': 'Heard and Mc Donald Islands', 'HN': 'Honduras', 'HK': 'Hong Kong', 'HU': 'Hungary', 'IS': 'Iceland', 'IN': 'India', 'ID': 'Indonesia', 'IR': 'Iran', 'IQ': 'Iraq', 'IE': 'Ireland', 'IL': 'Israel', 'IT': 'Italy', 'JM': 'Jamaica', 'JP': 'Japan', 'JO': 'Jordan', 'KZ': 'Kazakhstan', 'KE': 'Kenya', 'KI': 'Kiribati', 'KW': 'Kuwait', 'KG': 'Kyrgyzstan', 'LA': 'Laos', 'LV': 'Latvia', 'LB': 'Lebanon', 'LS': 'Lesotho', 'LR': 'Liberia', 'LY': 'Libya', 'LI': 'Liechtenstein', 'LT': 'Lithuania', 'LU': 'Luxembourg', 'MO': 'Macau', 'MG': 'Madagascar', 'MW': 'Malawi', 'MY': 'Malaysia', 'MV': 'Maldives', 'ML': 'Mali', 'MT': 'Malta', 'MH': 'Marshall Islands', 'MQ': 'Martinique', 'MR': 'Mauritania', 'MU': 'Mauritius', 'YT': 'Mayotte', 'MX': 'Mexico', 'FM': 'Micronesia', 'MD': 'Moldova', 'MC': 'Monaco', 'MN': 'Mongolia', 'ME': 'Montenegro', 'MS': 'Montserrat', 'MA': 'Morocco', 'MZ': 'Mozambique', 'MM': 'Myanmar', 'NA': 'Namibia', 'NR': 'Nauru', 'NP': 'Nepal', 'NL': 'Netherlands', 'AN': 'Netherlands Antilles', 'NC': 'New Caledonia', 'NZ': 'New Zealand', 'NI': 'Nicaragua', 'NE': 'Niger', 'NG': 'Nigeria', 'NU': 'Niue', 'NF': 'Norfolk Island', 'KP': 'North Korea', 'MP': 'Northern Marianas', 'NO': 'Norway', 'OM': 'Oman', 'PK': 'Pakistan', 'PW': 'Palau', 'PS': 'Palestine', 'PA': 'Panama', 'PG': 'Papua New Guinea', 'PY': 'Paraguay', 'PE': 'Peru', 'PH': 'Philippines', 'PN': 'Pitcairn Islands', 'PL': 'Poland', 'PT': 'Portugal', 'PR': 'Puerto Rico', 'QA': 'Qatar', 'RE': 'Reunion', 'RO': 'Romania', 'RU': 'Russia', 'RW': 'Rwanda', 'ST': 'São Tomé and Príncipe', 'SH': 'Saint Helena', 'PM': 'St. Pierre and Miquelon', 'KN': 'Saint Kitts and Nevis', 'LC': 'Saint Lucia', 'VC': 'Saint Vincent and the Grenadines', 'WS': 'Samoa', 'SM': 'San Marino', 'SA': 'Saudi Arabia', 'SN': 'Senegal', 'RS': 'Serbia', 'SC': 'Seychelles', 'SL': 'Sierra Leone', 'SG': 'Singapore', 'SK': 'Slovakia', 'SI': 'Slovenia', 'SB': 'Solomon Islands', 'SO': 'Somalia', 'ZA': 'South Africa', 'GS': 'South Georgia and the South Sandwich Islands', 'KR': 'South Korea', 'ES': 'Spain', 'LK': 'Sri Lanka', 'SD': 'Sudan', 'SR': 'Suriname', 'SJ': 'Svalbard and Jan Mayen Islands', 'SZ': 'Swaziland', 'SE': 'Sweden', 'CH': 'Switzerland', 'SY': 'Syria', 'TW': 'Taiwan', 'TJ': 'Tajikistan', 'TZ': 'Tanzania', 'TH': 'Thailand', 'BS': 'The Bahamas', 'GM': 'The Gambia', 'TG': 'Togo', 'TK': 'Tokelau', 'TO': 'Tonga', 'TT': 'Trinidad and Tobago', 'TN': 'Tunisia', 'TR': 'Turkey', 'TM': 'Turkmenistan', 'TC': 'Turks and Caicos Islands', 'TV': 'Tuvalu', 'VI': 'US Virgin Islands', 'UG': 'Uganda', 'UA': 'Ukraine', 'AE': 'United Arab Emirates', 'GB': 'United Kingdom', 'US': 'United States', 'UM': 'United States Minor Outlying Islands', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VU': 'Vanuatu', 'VA': 'Vatican City', 'VE': 'Venezuela', 'VN': 'Vietnam', 'WF': 'Wallis and Futuna Islands', 'EH': 'Western Sahara', 'YE': 'Yemen', 'ZM': 'Zambia', 'ZW': 'Zimbabwe' };
Eonic/EonicWeb5
wwwroot/ewcommon/bs3/addons/formHelpers/js/lang/en_US/bootstrap-formhelpers-countries.en_US.js
JavaScript
apache-2.0
6,201
/*before*/"use strict"; /*after*/foo();
zjmiller/babel
packages/babel-plugin-transform-strict-mode/test/fixtures/auxiliary-comment/use-strict-add/expected.js
JavaScript
mit
41
/** * Update: 15-5-11 * Editor: qihongye */ var fs = require('fs'); var path = require('path'); var fis = require('../lib/fis.js'); var _ = fis.file; var defaultSettings = (require('../lib/config.js')).DEFALUT_SETTINGS; var expect = require('chai').expect; var u = fis.util; var config = null; describe('config: config',function(){ beforeEach(function(){ fis.project.setProjectRoot(__dirname); fis.config.init(defaultSettings); process.env.NODE_ENV = 'dev'; }); it('set / get', function () { fis.set('namespace', 'common'); expect(fis.get('namespace')).to.equal('common'); fis.set('obj', {a:'a'}); fis.set('obj.b', 'b'); expect(fis.get('obj')).to.deep.equal({a:'a', b:'b'}); expect(fis.get('obj.c', {c: 'c'})).to.deep.equal({c:'c'}); expect(fis.get('obj.a')).to.equal('a'); expect(fis.get('obj.b')).to.equal('b'); }); it('media', function () { fis.set('a', 'a'); fis.set('b', 'b'); fis.media('prod').set('a', 'aa'); expect(fis.get('a')).to.equal('a'); expect(fis.media('prod').get('a')).to.equal('aa'); expect(fis.media('prod').get('b')).to.equal('b'); expect(fis.media('prod').get('project.charset')).to.equal('utf8'); }); it('fis.match',function(){ fis.match('**', { release: 'static/$&' }); // fis.config.match fis.match('**/js.js', { domain: 'www.baidu.com', useHash: false }, 1); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); //without domain // useDomain 已经去除,所以应该不收其影响了 fis.match('**/js.js', { useDomain: false }, 2); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); fis.match('**/js.js', { release: null }, 3); //without path path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with () fis.match('**/v1.0-(*)/(*).html', { release: '/$1/$2' }); path = __dirname+'/file/ext/v1.0-layout/test.html?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/layout/test.html?__inline'); fis.match('!**/js.js', { release: '/static/$&', useHash: true, domain: 'www.baidu.com' }); //with ! path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with ! but not match path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js_'+ f.getHash() +'.less?__inline'); }); it('match ${}', function() { fis.match('**/*.js', { release: null, useHash: false }) fis.set('coffee', 'js'); fis.match('**/js.js', { release: '/static/$&' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/j.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/file/ext/modular/j.js?__inline'); }); it('match 混合用法', function() { fis.set('ROOT', 'js'); fis.match('**', { useHash: false }); fis.match('(**/${ROOT}.js)', { release: '/static/js/$1' }); fis.match('(**/${ROOT}.less)', { release: '/static/js/$1' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.less?__inline'); }); it('del', function(){ fis.config.del(); var origin = fis.config.get(); fis.set('a.b', 'b'); fis.media('pro').set('a.b', 'b'); fis.config.del('a.b'); expect(fis.get('a')).to.deep.equal({}); expect(fis.media('pro').get('a.b')).to.equal('b'); fis.config.del('a'); expect(fis.get()).to.deep.equal(origin); fis.media('pro').del('a'); expect(fis.media('pro').get()).to.deep.equal({}); }); it('getSortedMatches', function() { fis.media('prod').match('a', { name: '' }); var matches = fis.media('prod')._matches.concat(); var initIndex = matches[matches.length - 1].index; fis.match('b', { name: '' }, 1) fis.match('c', { name: '' }, 2) fis.media('prod').match('b', { name: 'prod' }, 1) fis.media('prod').match('c', { name: 'prod' }, 2); var result_gl = [ { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 } ], result_prod = [ { raw: 'a', reg: u.glob('a'), negate: false, properties: {name: ''}, media: 'prod', weight: 0, index: initIndex + 0 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 1, index: initIndex + 3 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 2, index: initIndex + 4 }, ]; var xp = fis.config.getSortedMatches(); expect(xp).to.deep.equal(result_gl); var xp2 = fis.media('prod').getSortedMatches(); expect(xp2).to.deep.equal(result_prod); }); it("hook",function(){ fis.config.hook("module"); expect(fis.env().parent.data.modules.hook[1]['__plugin']).to.equal('module'); }); it("unhook",function(){ fis.config.unhook("module"); expect(fis.env().parent.data.modules.hook.length).to.equal(1); }); });
richard-chen-1985/fis3
test/config.js
JavaScript
bsd-2-clause
6,959
(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);
yuyang545262477/AfterWork
webpack/LittleTwo/node_modules/autoprefixer/data/prefixes.js
JavaScript
mit
15,271
/* * grunt-contrib-compress * http://gruntjs.com/ * * Copyright (c) 2016 Chris Talkington, contributors * Licensed under the MIT license. */ 'use strict'; var fs = require('fs'); var path = require('path'); var prettyBytes = require('pretty-bytes'); var chalk = require('chalk'); var zlib = require('zlib'); var archiver = require('archiver'); var streamBuffers = require('stream-buffers'); var _ = require('lodash'); module.exports = function(grunt) { var exports = { options: {} }; var fileStatSync = function() { var filepath = path.join.apply(path, arguments); if (grunt.file.exists(filepath)) { return fs.statSync(filepath); } return false; }; // 1 to 1 gziping of files exports.gzip = function(files, done) { exports.singleFile(files, zlib.createGzip, 'gz', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflate of files exports.deflate = function(files, done) { exports.singleFile(files, zlib.createDeflate, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflateRaw of files exports.deflateRaw = function(files, done) { exports.singleFile(files, zlib.createDeflateRaw, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 compression of files, expects a compatible zlib method to be passed in, see above exports.singleFile = function(files, algorithm, extension, done) { grunt.util.async.forEachSeries(files, function(filePair, nextPair) { grunt.util.async.forEachSeries(filePair.src, function(src, nextFile) { // Must be a file if (grunt.file.isDir(src)) { return nextFile(); } // Ensure the dest folder exists grunt.file.mkdir(path.dirname(filePair.dest)); var srcStream = fs.createReadStream(src); var originalSize = exports.getSize(src); var destStream; function initDestStream() { destStream = fs.createWriteStream(filePair.dest); destStream.on('close', function() { var compressedSize = exports.getSize(filePair.dest); var ratio = Math.round(parseInt(compressedSize, 10) / parseInt(originalSize, 10) * 100) + '%'; grunt.verbose.writeln('Created ' + chalk.cyan(filePair.dest) + ' (' + compressedSize + ') - ' + chalk.cyan(ratio) + ' of the original size'); nextFile(); }); } // write to memory stream if source and destination are the same var tmpStream; if (src === filePair.dest) { tmpStream = new streamBuffers.WritableStreamBuffer(); tmpStream.on('close', function() { initDestStream(); destStream.write(this.getContents()); destStream.end(); }); } else { initDestStream(); } var compressor = algorithm.call(zlib, exports.options); compressor.on('error', function(err) { grunt.log.error(err); grunt.fail.warn(algorithm + ' failed.'); nextFile(); }); srcStream.pipe(compressor).pipe(tmpStream || destStream); }, nextPair); }, done); }; // Compress with tar, tgz and zip exports.tar = function(files, done) { if (typeof exports.options.archive !== 'string' || exports.options.archive.length === 0) { grunt.fail.warn('Unable to compress; no valid archive file was specified.'); return; } var mode = exports.options.mode; if (mode === 'tgz') { mode = 'tar'; exports.options.gzip = true; } var archive = archiver.create(mode, exports.options); var dest = exports.options.archive; var dataWhitelist = ['comment', 'date', 'mode', 'store', 'gid', 'uid']; var sourcePaths = {}; // Ensure dest folder exists grunt.file.mkdir(path.dirname(dest)); // Where to write the file var destStream = fs.createWriteStream(dest); archive.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('Archiving failed.'); }); archive.on('entry', function(file) { var sp = sourcePaths[file.name] || 'unknown'; grunt.verbose.writeln('Archived ' + chalk.cyan(sp) + ' -> ' + chalk.cyan(dest + '/' + file.name)); }); destStream.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('WriteStream failed.'); }); destStream.on('close', function() { var size = archive.pointer(); grunt.verbose.writeln('Created ' + chalk.cyan(dest) + ' (' + exports.getSize(size) + ')'); done(); }); archive.pipe(destStream); files.forEach(function(file) { var isExpandedPair = file.orig.expand || false; file.src.forEach(function(srcFile) { var fstat = fileStatSync(srcFile); if (!fstat) { grunt.fail.warn('unable to stat srcFile (' + srcFile + ')'); return; } var internalFileName = isExpandedPair ? file.dest : exports.unixifyPath(path.join(file.dest || '', srcFile)); // check if internal file name is not a dot, should not be present in an archive if (internalFileName === '.' || internalFileName === './') { return; } if (fstat.isDirectory() && internalFileName.slice(-1) !== '/') { srcFile += '/'; internalFileName += '/'; } var fileData = { name: internalFileName, stats: fstat }; for (var i = 0; i < dataWhitelist.length; i++) { if (typeof file[dataWhitelist[i]] === 'undefined') { continue; } if (typeof file[dataWhitelist[i]] === 'function') { fileData[dataWhitelist[i]] = file[dataWhitelist[i]](srcFile); } else { fileData[dataWhitelist[i]] = file[dataWhitelist[i]]; } } if (fstat.isFile()) { archive.file(srcFile, fileData); } else if (fstat.isDirectory()) { archive.append(null, fileData); } else { grunt.fail.warn('srcFile (' + srcFile + ') should be a valid file or directory'); return; } sourcePaths[internalFileName] = srcFile; }); }); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); archive.finalize(); }; exports.getSize = function(filename, pretty) { var size = 0; if (typeof filename === 'string') { try { size = fs.statSync(filename).size; } catch (e) {} } else { size = filename; } if (pretty !== false) { if (!exports.options.pretty) { return size + ' bytes'; } return prettyBytes(size); } return Number(size); }; exports.autoDetectMode = function(dest) { if (exports.options.mode) { return exports.options.mode; } if (!dest) { return 'gzip'; } if (_.endsWith(dest, '.tar.gz')) { return 'tgz'; } var ext = path.extname(dest).replace('.', ''); if (ext === 'gz') { return 'gzip'; } return ext; }; exports.unixifyPath = function(filepath) { return process.platform === 'win32' ? filepath.replace(/\\/g, '/') : filepath; }; return exports; };
ph3l1x/realestate
sites/all/themes/default/bootstrap/node_modules/grunt-contrib-compress/tasks/lib/compress.js
JavaScript
gpl-2.0
7,527
tinyMCE.addI18n('th.advimage_dlg',{ tab_general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", tab_appearance:"\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30", tab_advanced:"\u0E02\u0E31\u0E49\u0E19\u0E2A\u0E39\u0E07", general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", title:"\u0E0A\u0E37\u0E48\u0E2D", preview:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07", constrain_proportions:"\u0E04\u0E07\u0E2A\u0E31\u0E14\u0E2A\u0E48\u0E27\u0E19", langdir:"\u0E17\u0E34\u0E28\u0E17\u0E32\u0E07\u0E01\u0E32\u0E23\u0E2D\u0E48\u0E32\u0E19", langcode:"\u0E42\u0E04\u0E49\u0E14\u0E20\u0E32\u0E29\u0E32", long_desc:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E25\u0E34\u0E49\u0E07\u0E04\u0E4C", style:"\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A", classes:"\u0E04\u0E25\u0E32\u0E2A", ltr:"\u0E0B\u0E49\u0E32\u0E22\u0E44\u0E1B\u0E02\u0E27\u0E32", rtl:"\u0E02\u0E27\u0E32\u0E44\u0E1B\u0E0B\u0E49\u0E32\u0E22", id:"Id", map:"Image map", swap_image:"Swap image", alt_image:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E23\u0E39\u0E1B", mouseover:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E0A\u0E35\u0E49", mouseout:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E2D\u0E2D\u0E01", misc:"\u0E40\u0E1A\u0E47\u0E14\u0E40\u0E15\u0E25\u0E47\u0E14", example_img:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30\u0E02\u0E2D\u0E07\u0E23\u0E39\u0E1B", missing_alt:"\u0E04\u0E38\u0E13\u0E41\u0E19\u0E48\u0E43\u0E08\u0E2B\u0E23\u0E37\u0E2D\u0E44\u0E21\u0E48\u0E27\u0E48\u0E32\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E14\u0E33\u0E40\u0E19\u0E34\u0E19\u0E01\u0E32\u0E23\u0E15\u0E48\u0E2D\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E20\u0E32\u0E1E ? \u0E01\u0E32\u0E23\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E17\u0E33\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E1E\u0E34\u0E01\u0E32\u0E23\u0E17\u0E32\u0E07\u0E2A\u0E32\u0E22\u0E15\u0E32\u0E2A\u0E32\u0E21\u0E32\u0E23\u0E16\u0E23\u0E39\u0E49\u0E44\u0E14\u0E49\u0E27\u0E48\u0E32\u0E23\u0E39\u0E1B\u0E04\u0E38\u0E13\u0E04\u0E37\u0E2D\u0E23\u0E39\u0E1B\u0E2D\u0E30\u0E44\u0E23", dialog_title:"\u0E40\u0E1E\u0E34\u0E48\u0E21/\u0E41\u0E01\u0E49\u0E44\u0E02 image", src:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E23\u0E39\u0E1B", alt:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E23\u0E39\u0E1B", list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B", border:"\u0E01\u0E23\u0E2D\u0E1A", dimensions:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07", vspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E15\u0E31\u0E49\u0E07", hspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E19\u0E2D\u0E19", align:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E08\u0E31\u0E14\u0E27\u0E32\u0E07", align_baseline:"\u0E40\u0E2A\u0E49\u0E19\u0E1E\u0E37\u0E49\u0E19", align_top:"\u0E1A\u0E19", align_middle:"\u0E01\u0E25\u0E32\u0E07", align_bottom:"\u0E25\u0E48\u0E32\u0E07", align_texttop:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E1A\u0E19", align_textbottom:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E25\u0E48\u0E32\u0E07", align_left:"\u0E0B\u0E49\u0E32\u0E22", align_right:"\u0E02\u0E27\u0E32", image_list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B" });
numericube/twistranet
twistranet/themes/twistheme/static/js/tiny_mce/plugins/advimage/langs/th_dlg.js
JavaScript
agpl-3.0
3,520
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ /* THIS FILE WAS AUTOGENERATED BY mode.tmpl.js */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var NSISHighlightRules = require("./nsis_highlight_rules").NSISHighlightRules; var FoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = NSISHighlightRules; this.foldingRules = new FoldMode(); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = [";", "#"]; this.blockComment = {start: "/*", end: "*/"}; this.$id = "ace/mode/nsis"; }).call(Mode.prototype); exports.Mode = Mode; });
jecelyin/920-text-editor-v2
tools/assets/ace/lib/ace/mode/nsis.js
JavaScript
apache-2.0
2,369
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;
jdlehman/react
fixtures/dom/src/components/fixtures/password-inputs/index.js
JavaScript
mit
835
(function( $ ) { /** * Activity reply object for the activity index screen * * @since 1.6 */ var activityReply = { /** * Attach event handler functions to the relevant elements. * * @since 1.6 */ init : function() { $(document).on( 'click', '.row-actions a.reply', activityReply.open ); $(document).on( 'click', '#bp-activities-container a.cancel', activityReply.close ); $(document).on( 'click', '#bp-activities-container a.save', activityReply.send ); // Close textarea on escape $(document).on( 'keyup', '#bp-activities:visible', function( e ) { if ( 27 == e.which ) { activityReply.close(); } }); }, /** * Reveals the entire row when "reply" is pressed. * * @since 1.6 */ open : function( e ) { // Hide the container row, and move it to the new location var box = $( '#bp-activities-container' ).hide(); $( this ).parents( 'tr' ).after( box ); // Fade the whole row in, and set focus on the text area. box.fadeIn( '300' ); $( '#bp-activities' ).focus(); return false; }, /** * Hide and reset the entire row when "cancel", or escape, are pressed. * * @since 1.6 */ close : function( e ) { // Hide the container row $('#bp-activities-container').fadeOut( '200', function () { // Empty and unfocus the text area $( '#bp-activities' ).val( '' ).blur(); // Remove any error message and disable the spinner $( '#bp-replysubmit .error' ).html( '' ).hide(); $( '#bp-replysubmit .waiting' ).hide(); }); return false; }, /** * Submits "form" via AJAX back to WordPress. * * @since 1.6 */ send : function( e ) { // Hide any existing error message, and show the loading spinner $( '#bp-replysubmit .error' ).hide(); $( '#bp-replysubmit .waiting' ).show(); // Grab the nonce var reply = {}; reply['_ajax_nonce-bp-activity-admin-reply'] = $( '#bp-activities-container input[name="_ajax_nonce-bp-activity-admin-reply"]' ).val(); // Get the rest of the data reply.action = 'bp-activity-admin-reply'; reply.content = $( '#bp-activities' ).val(); reply.parent_id = $( '#bp-activities-container' ).prev().data( 'parent_id' ); reply.root_id = $( '#bp-activities-container' ).prev().data( 'root_id' ); // Make the AJAX call $.ajax({ data : reply, type : 'POST', url : ajaxurl, // Callbacks error : function( r ) { activityReply.error( r ); }, success : function( r ) { activityReply.show( r ); } }); return false; }, /** * send() error message handler * * @since 1.6 */ error : function( r ) { var er = r.statusText; $('#bp-replysubmit .waiting').hide(); if ( r.responseText ) { er = r.responseText.replace( /<.[^<>]*?>/g, '' ); } if ( er ) { $('#bp-replysubmit .error').html( er ).show(); } }, /** * send() success handler * * @since 1.6 */ show : function ( xml ) { var bg, id, response; // Handle any errors in the response if ( typeof( xml ) == 'string' ) { activityReply.error( { 'responseText': xml } ); return false; } response = wpAjax.parseAjaxResponse( xml ); if ( response.errors ) { activityReply.error( { 'responseText': wpAjax.broken } ); return false; } response = response.responses[0]; // Close and reset the reply row, and add the new Activity item into the list. $('#bp-activities-container').fadeOut( '200', function () { // Empty and unfocus the text area $( '#bp-activities' ).val( '' ).blur(); // Remove any error message and disable the spinner $( '#bp-replysubmit .error' ).html( '' ).hide(); $( '#bp-replysubmit .waiting' ).hide(); // Insert new activity item $( '#bp-activities-container' ).before( response.data ); // Get background colour and animate the flash id = $( '#activity-' + response.id ); bg = id.closest( '.widefat' ).css( 'backgroundColor' ); id.animate( { 'backgroundColor': '#CEB' }, 300 ).animate( { 'backgroundColor': bg }, 300 ); }); } }; $(document).ready( function () { // Create the Activity reply object after domready event activityReply.init(); // On the edit screen, unload the close/open toggle js for the action & content metaboxes $( '#bp_activity_action h3, #bp_activity_content h3' ).unbind( 'click' ); }); })(jQuery);
jnishiyama/PebblesWP
wp-content/plugins/buddypress/bp-activity/admin/js/admin.dev.js
JavaScript
gpl-2.0
4,291
/** * @preserve SelectNav.js (v. 0.1) * Converts your <ul>/<ol> navigation into a dropdown list for small screens * https://github.com/lukaszfiszer/selectnav.js */ window.selectnav = (function(){ "use strict"; var selectnav = function(element,options){ element = document.getElementById(element); // return immediately if element doesn't exist if( ! element){ return; } // return immediately if element is not a list if( ! islist(element) ){ return; } // return immediately if no support for insertAdjacentHTML (Firefox 7 and under) if( ! ('insertAdjacentHTML' in window.document.documentElement) ){ return; } // add a js class to <html> tag document.documentElement.className += " js"; // retreive options and set defaults var o = options || {}, activeclass = o.activeclass || 'active', autoselect = typeof(o.autoselect) === "boolean" ? o.autoselect : true, nested = typeof(o.nested) === "boolean" ? o.nested : true, indent = o.indent || "→", label = o.label || "- Navigation -", // helper variables level = 0, selected = " selected "; // insert the freshly created dropdown navigation after the existing navigation element.insertAdjacentHTML('afterend', parselist(element) ); var nav = document.getElementById(id()); // autoforward on click if (nav.addEventListener) { nav.addEventListener('change',goTo); } if (nav.attachEvent) { nav.attachEvent('onchange', goTo); } return nav; function goTo(e){ // Crossbrowser issues - http://www.quirksmode.org/js/events_properties.html var targ; if (!e) e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType === 3) // defeat Safari bug targ = targ.parentNode; if(targ.value) window.location.href = targ.value; } function islist(list){ var n = list.nodeName.toLowerCase(); return (n === 'ul' || n === 'ol'); } function id(nextId){ for(var j=1; document.getElementById('selectnav'+j);j++); return (nextId) ? 'selectnav'+j : 'selectnav'+(j-1); } function parselist(list){ // go one level down level++; var length = list.children.length, html = '', prefix = '', k = level-1 ; // return immediately if has no children if (!length) { return; } if(k) { while(k--){ prefix += indent; } prefix += " "; } for(var i=0; i < length; i++){ var link = list.children[i].children[0]; if(typeof(link) !== 'undefined'){ var text = link.innerText || link.textContent; var isselected = ''; if(activeclass){ isselected = link.className.search(activeclass) !== -1 || link.parentNode.className.search(activeclass) !== -1 ? selected : ''; } if(autoselect && !isselected){ isselected = link.href === document.URL ? selected : ''; } html += '<option value="' + link.href + '" ' + isselected + '>' + prefix + text +'</option>'; if(nested){ var subElement = list.children[i].children[1]; if( subElement && islist(subElement) ){ html += parselist(subElement); } } } } // adds label if(level === 1 && label) { html = '<option value="">' + label + '</option>' + html; } // add <select> tag to the top level of the list if(level === 1) { html = '<select class="selectnav" id="'+id(true)+'">' + html + '</select>'; } // go 1 level up level--; return html; } }; return function (element,options) { selectnav(element,options); }; })();
rtdean93/drupalengage
store.drupalengage.com/profiles/commerce_kickstart/libraries/selectnav.js/selectnav.js
JavaScript
gpl-2.0
3,924
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; $.__views.index = Ti.UI.createWindow({ backgroundColor: "#fff", fullscreen: false, exitOnClose: true, id: "index" }); $.__views.index && $.addTopLevelView($.__views.index); $.__views.__alloyId0 = Ti.UI.createLabel({ text: "This app is supported only on iOS", id: "__alloyId0" }); $.__views.index.add($.__views.__alloyId0); exports.destroy = function() {}; _.extend($, $.__views); $.index.open(); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
jvkops/alloy
test/apps/testing/ALOY-262/_generated/mobileweb/alloy/controllers/index.js
JavaScript
apache-2.0
1,252
/* 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"});
Laravel-Backpack/crud
src/public/packages/ckeditor/plugins/placeholder/lang/sv.js
JavaScript
mit
456
// 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); }
pawaranand/phr_frappe
frappe/public/js/legacy/clientscriptAPI.js
JavaScript
mit
7,148
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;
mmrtnz/material-ui
src/svg-icons/action/thumb-down.js
JavaScript
mit
562
/** * 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;
f14c0/rb-sensor
webapp/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
JavaScript
mit
2,154
// $Id: ajax.js,v 1.26.2.2 2009/11/30 22:47:05 merlinofchaos Exp $ /** * @file ajax_admin.js * * Handles AJAX submission and response in Views UI. */ Drupal.Views.Ajax = Drupal.Views.Ajax || {}; /** * Handles the simple process of setting the ajax form area with new data. */ Drupal.Views.Ajax.setForm = function(title, output) { $(Drupal.settings.views.ajax.title).html(title); $(Drupal.settings.views.ajax.id).html(output); } /** * An ajax responder that accepts a packet of JSON data and acts appropriately. * * The following fields control behavior. * - 'display': Display the associated data in the form area; bind the new * form to 'url' if appropriate. The 'title' field may also be used. * - 'add': This is a keyed array of HTML output to add via append. The key is * the id to append via $(key).append(value) * - 'replace': This is a keyed array of HTML output to add via replace. The key is * the id to append via $(key).html(value) * */ Drupal.Views.Ajax.ajaxResponse = function(data) { $('a.views-throbbing').removeClass('views-throbbing'); $('span.views-throbbing').remove(); if (data.debug) { alert(data.debug); } // See if we have any settings to extend. Do this first so that behaviors // can access the new settings easily. if (Drupal.settings.viewsAjax) { Drupal.settings.viewsAjax = {}; } if (data.js) { $.extend(Drupal.settings, data.js); } // Check the 'display' for data. if (data.display) { Drupal.Views.Ajax.setForm(data.title, data.display); // if a URL was supplied, bind the form to it. if (data.url) { var ajax_area = Drupal.settings.views.ajax.id; var ajax_title = Drupal.settings.views.ajax.title; // Bind a click to the button to set the value for the button. $('input[type=submit], button', ajax_area).unbind('click'); $('input[type=submit], button', ajax_area).click(function() { $('form', ajax_area).append('<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).val() + '">'); $(this).after('<span class="views-throbbing">&nbsp</span>'); }); // Bind forms to ajax submit. $('form', ajax_area).unbind('submit'); // be safe here. $('form', ajax_area).submit(function(arg) { $(this).ajaxSubmit({ url: data.url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': data.url})); }, dataType: 'json' }); return false; }); } Drupal.attachBehaviors(ajax_area); } else { // If no display, reset the form. Drupal.Views.Ajax.setForm('', Drupal.settings.views.ajax.defaultForm); //Enable the save button. $('#edit-save').removeAttr('disabled'); // Trigger an update for the live preview when we reach this state: $('#views-ui-preview-form').trigger('submit'); } // Go through the 'add' array and add any new content we're instructed to add. if (data.add) { for (id in data.add) { var newContent = $(id).append(data.add[id]); Drupal.attachBehaviors(newContent); } } // Go through the 'replace' array and replace any content we're instructed to. if (data.replace) { for (id in data.replace) { $(id).html(data.replace[id]); Drupal.attachBehaviors(id); } } // Go through and add any requested tabs if (data.tab) { for (id in data.tab) { $('#views-tabset').addTab(id, data.tab[id]['title'], 0); $(id).html(data.tab[id]['body']); $(id).addClass('views-tab'); Drupal.attachBehaviors(id); // This is kind of annoying, but we have to actually to find where the new // tab is. var instance = $.ui.tabs.instances[$('#views-tabset').get(0).UI_TABS_UUID]; $('#views-tabset').clickTab(instance.$tabs.length); } } if (data.hilite) { $('.hilited').removeClass('hilited'); $(data.hilite).addClass('hilited'); } if (data.changed) { $('div.views-basic-info').addClass('changed'); } } /** * An ajax responder that accepts a packet of JSON data and acts appropriately. * This one specifically responds to the Views live preview area, so it's * hardcoded and specialized. */ Drupal.Views.Ajax.previewResponse = function(data) { $('a.views-throbbing').removeClass('views-throbbing'); $('span.views-throbbing').remove(); if (data.debug) { alert(data.debug); } // See if we have any settings to extend. Do this first so that behaviors // can access the new settings easily. // Clear any previous viewsAjax settings. if (Drupal.settings.viewsAjax) { Drupal.settings.viewsAjax = {}; } if (data.js) { $.extend(Drupal.settings, data.js); } // Check the 'display' for data. if (data.display) { var ajax_area = 'div#views-live-preview'; $(ajax_area).html(data.display); var url = $(ajax_area, 'form').attr('action'); // if a URL was supplied, bind the form to it. if (url) { // Bind a click to the button to set the value for the button. $('input[type=submit], button', ajax_area).unbind('click'); $('input[type=submit], button', ajax_area).click(function() { $('form', ajax_area).append('<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).val() + '">'); $(this).after('<span class="views-throbbing">&nbsp</span>'); }); // Bind forms to ajax submit. $('form', ajax_area).unbind('submit'); // be safe here. $('form', ajax_area).submit(function() { $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); } Drupal.attachBehaviors(ajax_area); } } Drupal.Views.updatePreviewForm = function() { var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); $('input[type=submit], button', this).after('<span class="views-throbbing">&nbsp</span>'); $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.Views.updatePreviewFilterForm = function() { var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); $('input[type=submit], button', this).after('<span class="views-throbbing">&nbsp</span>'); $('input[name=q]', this).remove(); // remove 'q' for live preview. $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'GET', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.Views.updatePreviewLink = function() { var url = $(this).attr('href'); url = url.replace('nojs', 'ajax'); if (url.substring(0, 18) != '/admin/build/views') { return true; } $(this).addClass('views-throbbing'); $.ajax({ url: url, data: 'js=1', type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.behaviors.ViewsAjaxLinks = function() { // Make specified links ajaxy. $('a.views-ajax-link:not(.views-processed)').addClass('views-processed').click(function() { // Translate the href on the link to the ajax href. That way this degrades // into a nice, normal link. var url = $(this).attr('href'); url = url.replace('nojs', 'ajax'); // Turn on the hilite to indicate this is in use. $(this).addClass('hilite'); // Disable the save button. $('#edit-save').attr('disabled', 'true'); $(this).addClass('views-throbbing'); $.ajax({ type: "POST", url: url, data: 'js=1', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); $('form.views-ajax-form:not(.views-processed)').addClass('views-processed').submit(function(arg) { // Translate the href on the link to the ajax href. That way this degrades // into a nice, normal link. var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); // $('input[@type=submit]', this).after('<span class="views-throbbing">&nbsp</span>'); $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); // Bind the live preview to where it's supposed to go. $('form#views-ui-preview-form:not(.views-processed)') .addClass('views-processed') .submit(Drupal.Views.updatePreviewForm); $('div#views-live-preview form:not(.views-processed)') .addClass('views-processed') .submit(Drupal.Views.updatePreviewFilterForm); $('div#views-live-preview a:not(.views-processed)') .addClass('views-processed') .click(Drupal.Views.updatePreviewLink); } /** * Get rid of irritating tabledrag messages */ Drupal.theme.tableDragChangedWarning = function () { return '<div></div>'; }
hugowetterberg/goodold_drupal
sites/all/modules/views/js/ajax.js
JavaScript
gpl-2.0
9,897
esprima.tokenize(null);
supriyantomaftuh/esprima
test/fixtures/api/migrated_0010.run.js
JavaScript
bsd-2-clause
24
!function(e){e.calendarsPicker.regionalOptions.km={renderer:e.calendarsPicker.defaultRenderer,prevText:"ថយ​ក្រោយ",prevStatus:"",prevJumpText:"&#x3c;&#x3c;",prevJumpStatus:"",nextText:"ទៅ​មុខ",nextStatus:"",nextJumpText:"&#x3e;&#x3e;",nextJumpStatus:"",currentText:"ថ្ងៃ​នេះ",currentStatus:"",todayText:"ថ្ងៃ​នេះ",todayStatus:"",clearText:"X",clearStatus:"",closeText:"រួច​រាល់",closeStatus:"",yearStatus:"",monthStatus:"",weekText:"Wk",weekStatus:"",dayStatus:"DD d MM",defaultStatus:"",isRTL:!1},e.calendarsPicker.setDefaults(e.calendarsPicker.regionalOptions.km)}(jQuery);
bedegaming-aleksej/Orchard
src/Orchard.Web/Modules/Orchard.Resources/Scripts/Calendars/jquery.calendars.picker-km.min.js
JavaScript
bsd-3-clause
651
// Copyright JS Foundation and other contributors, http://js.foundation // // 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. print("help tests");
grgustaf/jerryscript
tests/debugger/do_help.js
JavaScript
apache-2.0
651
/* Copyright (c) 2011 by The Authors. * Published under the LGPL 2.1 license. * See /license-notice.txt for the full text of the license notice. * See /license.txt for the full text of the license. */ /** * Supplies a set of utility methods for building Geometry objects from lists * of Coordinates. * * Note that the factory constructor methods do <b>not</b> change the input * coordinates in any way. * * In particular, they are not rounded to the supplied <tt>PrecisionModel</tt>. * It is assumed that input Coordinates meet the given precision. */ /** * @requires jsts/geom/PrecisionModel.js */ /** * Constructs a GeometryFactory that generates Geometries having a floating * PrecisionModel and a spatial-reference ID of 0. * * @constructor */ jsts.geom.GeometryFactory = function(precisionModel) { this.precisionModel = precisionModel || new jsts.geom.PrecisionModel(); }; jsts.geom.GeometryFactory.prototype.precisionModel = null; jsts.geom.GeometryFactory.prototype.getPrecisionModel = function() { return this.precisionModel; }; /** * Creates a Point using the given Coordinate; a null Coordinate will create an * empty Geometry. * * @param {Coordinate} * coordinate Coordinate to base this Point on. * @return {Point} A new Point. */ jsts.geom.GeometryFactory.prototype.createPoint = function(coordinate) { var point = new jsts.geom.Point(coordinate, this); return point; }; /** * Creates a LineString using the given Coordinates; a null or empty array will * create an empty LineString. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LineString} A new LineString. */ jsts.geom.GeometryFactory.prototype.createLineString = function(coordinates) { var lineString = new jsts.geom.LineString(coordinates, this); return lineString; }; /** * Creates a LinearRing using the given Coordinates; a null or empty array will * create an empty LinearRing. The points must form a closed and simple * linestring. Consecutive points must not be equal. * * @param {Coordinate[]} * coordinates an array without null elements, or an empty array, or * null. * @return {LinearRing} A new LinearRing. */ jsts.geom.GeometryFactory.prototype.createLinearRing = function(coordinates) { var linearRing = new jsts.geom.LinearRing(coordinates, this); return linearRing; }; /** * Constructs a <code>Polygon</code> with the given exterior boundary and * interior boundaries. * * @param {LinearRing} * shell the outer boundary of the new <code>Polygon</code>, or * <code>null</code> or an empty <code>LinearRing</code> if the * empty geometry is to be created. * @param {LinearRing[]} * holes the inner boundaries of the new <code>Polygon</code>, or * <code>null</code> or empty <code>LinearRing</code> s if the * empty geometry is to be created. * @return {Polygon} A new Polygon. */ jsts.geom.GeometryFactory.prototype.createPolygon = function(shell, holes) { var polygon = new jsts.geom.Polygon(shell, holes, this); return polygon; }; jsts.geom.GeometryFactory.prototype.createMultiPoint = function(points) { if (points && points[0] instanceof jsts.geom.Coordinate) { var converted = []; var i; for (i = 0; i < points.length; i++) { converted.push(this.createPoint(points[i])); } points = converted; } return new jsts.geom.MultiPoint(points, this); }; jsts.geom.GeometryFactory.prototype.createMultiLineString = function( lineStrings) { return new jsts.geom.MultiLineString(lineStrings, this); }; jsts.geom.GeometryFactory.prototype.createMultiPolygon = function(polygons) { return new jsts.geom.MultiPolygon(polygons, this); }; /** * Build an appropriate <code>Geometry</code>, <code>MultiGeometry</code>, * or <code>GeometryCollection</code> to contain the <code>Geometry</code>s * in it. For example:<br> * * <ul> * <li> If <code>geomList</code> contains a single <code>Polygon</code>, * the <code>Polygon</code> is returned. * <li> If <code>geomList</code> contains several <code>Polygon</code>s, a * <code>MultiPolygon</code> is returned. * <li> If <code>geomList</code> contains some <code>Polygon</code>s and * some <code>LineString</code>s, a <code>GeometryCollection</code> is * returned. * <li> If <code>geomList</code> is empty, an empty * <code>GeometryCollection</code> is returned * </ul> * * Note that this method does not "flatten" Geometries in the input, and hence * if any MultiGeometries are contained in the input a GeometryCollection * containing them will be returned. * * @param geomList * the <code>Geometry</code>s to combine. * @return {Geometry} a <code>Geometry</code> of the "smallest", "most * type-specific" class that can contain the elements of * <code>geomList</code> . */ jsts.geom.GeometryFactory.prototype.buildGeometry = function(geomList) { /** * Determine some facts about the geometries in the list */ var geomClass = null; var isHeterogeneous = false; var hasGeometryCollection = false; for (var i = geomList.iterator(); i.hasNext();) { var geom = i.next(); var partClass = geom.CLASS_NAME; if (geomClass === null) { geomClass = partClass; } if (!(partClass === geomClass)) { isHeterogeneous = true; } if (geom.isGeometryCollectionBase()) hasGeometryCollection = true; } /** * Now construct an appropriate geometry to return */ // for the empty geometry, return an empty GeometryCollection if (geomClass === null) { return this.createGeometryCollection(null); } if (isHeterogeneous || hasGeometryCollection) { return this.createGeometryCollection(geomList.toArray()); } // at this point we know the collection is hetereogenous. // Determine the type of the result from the first Geometry in the list // this should always return a geometry, since otherwise an empty collection // would have already been returned var geom0 = geomList.get(0); var isCollection = geomList.size() > 1; if (isCollection) { if (geom0 instanceof jsts.geom.Polygon) { return this.createMultiPolygon(geomList.toArray()); } else if (geom0 instanceof jsts.geom.LineString) { return this.createMultiLineString(geomList.toArray()); } else if (geom0 instanceof jsts.geom.Point) { return this.createMultiPoint(geomList.toArray()); } jsts.util.Assert.shouldNeverReachHere('Unhandled class: ' + geom0); } return geom0; }; jsts.geom.GeometryFactory.prototype.createGeometryCollection = function( geometries) { return new jsts.geom.GeometryCollection(geometries, this); }; /** * Creates a {@link Geometry} with the same extent as the given envelope. The * Geometry returned is guaranteed to be valid. To provide this behaviour, the * following cases occur: * <p> * If the <code>Envelope</code> is: * <ul> * <li>null : returns an empty {@link Point} * <li>a point : returns a non-empty {@link Point} * <li>a line : returns a two-point {@link LineString} * <li>a rectangle : returns a {@link Polygon}> whose points are (minx, miny), * (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny). * </ul> * * @param {jsts.geom.Envelope} * envelope the <code>Envelope</code> to convert. * @return {jsts.geom.Geometry} an empty <code>Point</code> (for null * <code>Envelope</code>s), a <code>Point</code> (when min x = max * x and min y = max y) or a <code>Polygon</code> (in all other cases). */ jsts.geom.GeometryFactory.prototype.toGeometry = function(envelope) { // null envelope - return empty point geometry if (envelope.isNull()) { return this.createPoint(null); } // point? if (envelope.getMinX() === envelope.getMaxX() && envelope.getMinY() === envelope.getMaxY()) { return this.createPoint(new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())); } // vertical or horizontal line? if (envelope.getMinX() === envelope.getMaxX() || envelope.getMinY() === envelope.getMaxY()) { return this.createLineString([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY())]); } // create a CW ring for the polygon return this.createPolygon(this.createLinearRing([ new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMaxY()), new jsts.geom.Coordinate(envelope.getMaxX(), envelope.getMinY()), new jsts.geom.Coordinate(envelope.getMinX(), envelope.getMinY())]), null); };
mileswwatkins/ABiteBetweenUs
utilities/scripts/jsts/src/jsts/geom/GeometryFactory.js
JavaScript
apache-2.0
8,870
/** * 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
spawashe/poc-mango-cad
www/lib/bower_components/angular-strap/dist/modules/date-formatter.min.js
JavaScript
mit
873
/** * @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(); };
stoneman1/phaser
v2/src/gameobjects/Image.js
JavaScript
mit
3,099
// 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 .
danielwanja/bulk_data_source_flex
testrailsapp/app/assets/javascripts/application.js
JavaScript
mit
215
(function ($, Drupal) { /** * Toggle show/hide links for off canvas layout. */ Drupal.behaviors.omegaOffCanvasLayout = { attach: function (context) { $('#off-canvas').click(function(e) { if (!$(this).hasClass('is-visible')) { $(this).addClass('is-visible'); e.preventDefault(); e.stopPropagation(); } }); $('#off-canvas-hide').click(function(e) { $(this).parent().removeClass('is-visible'); e.preventDefault(); e.stopPropagation(); }); $('.l-page').click(function(e) { if($('#off-canvas').hasClass('is-visible') && $(e.target).closest('#off-canvas').length === 0) { $('#off-canvas').removeClass('is-visible'); e.stopPropagation(); } }); } }; })(jQuery, Drupal);
sgurlt/drupal-sandbox
www/sites/all/themes/omega/omega/layouts/off-canvas/assets/off-canvas.js
JavaScript
gpl-2.0
827
/*! 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);
dlueth/cdnjs
ajax/libs/mvw-injection/0.2.5/dependency-injection.js
JavaScript
mit
5,110
/** * 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;
demns/todomvc-perf-comparison
todomvc/react/node_modules/react/lib/ReactCompositeComponent.js
JavaScript
mit
48,272
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * 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. */ // Entry point into AMP for compilation with babel. Just loads amp.js and // Babel's helpers. import '../third_party/babel/custom-babel-helpers'; import './amp-shadow';
DistroScale/amphtml
src/amp-shadow-babel.js
JavaScript
apache-2.0
799
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; }; });
jelbourn/material
src/components/menu/demoMenuPositionModes/script.js
JavaScript
mit
747
/** * @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; } };
ccclayton/DataWar
static/js/threejs.r70/src/loaders/XHRLoader.js
JavaScript
mit
1,408
/* * 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.&nbsp; 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.&nbsp; 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.&nbsp; 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.&nbsp; 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.&nbsp; 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.&nbsp; 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.&nbsp; 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); })();
xixizhang96/Example
例子example/jQuery+html5圆形进度条倒计时动画特效/改动版/js/kinetic-v5.1.0.js
JavaScript
mit
514,339
/*! * 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; }));
sashberd/cdnjs
ajax/libs/inferno/0.7.3/inferno.js
JavaScript
mit
6,896
/** * OpenLayers 3 Layer Switcher Control. * See [the examples](./examples) for usage. * @constructor * @extends {ol.control.Control} * @param {Object} opt_options Control options, extends olx.control.ControlOptions adding: * **`tipLabel`** `String` - the button tooltip. */ ol.control.LayerSwitcher = function(opt_options) { var options = opt_options || {}; var tipLabel = options.tipLabel ? options.tipLabel : 'Legend'; this.mapListeners = []; this.hiddenClassName = 'ol-unselectable ol-control layer-switcher'; this.shownClassName = this.hiddenClassName + ' shown'; var element = document.createElement('div'); element.className = this.hiddenClassName; var button = document.createElement('button'); button.setAttribute('title', tipLabel); element.appendChild(button); this.panel = document.createElement('div'); this.panel.className = 'panel'; element.appendChild(this.panel); var this_ = this; element.onmouseover = function(e) { this_.showPanel(); }; button.onclick = function(e) { this_.showPanel(); }; element.onmouseout = function(e) { e = e || window.event; if (!element.contains(e.toElement)) { this_.hidePanel(); } }; ol.control.Control.call(this, { element: element, target: options.target }); }; ol.inherits(ol.control.LayerSwitcher, ol.control.Control); /** * Show the layer panel. */ ol.control.LayerSwitcher.prototype.showPanel = function() { if (this.element.className != this.shownClassName) { this.element.className = this.shownClassName; this.renderPanel(); } }; /** * Hide the layer panel. */ ol.control.LayerSwitcher.prototype.hidePanel = function() { if (this.element.className != this.hiddenClassName) { this.element.className = this.hiddenClassName; } }; /** * Re-draw the layer panel to represent the current state of the layers. */ ol.control.LayerSwitcher.prototype.renderPanel = function() { this.ensureTopVisibleBaseLayerShown_(); while(this.panel.firstChild) { this.panel.removeChild(this.panel.firstChild); } var ul = document.createElement('ul'); this.panel.appendChild(ul); this.renderLayers_(this.getMap(), ul); }; /** * Set the map instance the control is associated with. * @param {ol.Map} map The map instance. */ ol.control.LayerSwitcher.prototype.setMap = function(map) { // Clean up listeners associated with the previous map for (var i = 0, key; i < this.mapListeners.length; i++) { this.getMap().unByKey(this.mapListeners[i]); } this.mapListeners.length = 0; // Wire up listeners etc. and store reference to new map ol.control.Control.prototype.setMap.call(this, map); if (map) { var this_ = this; this.mapListeners.push(map.on('pointerdown', function() { this_.hidePanel(); })); this.renderPanel(); } }; /** * Ensure only the top-most base layer is visible if more than one is visible. * @private */ ol.control.LayerSwitcher.prototype.ensureTopVisibleBaseLayerShown_ = function() { var lastVisibleBaseLyr; ol.control.LayerSwitcher.forEachRecursive(this.getMap(), function(l, idx, a) { if (l.get('type') === 'base' && l.getVisible()) { lastVisibleBaseLyr = l; } }); if (lastVisibleBaseLyr) this.setVisible_(lastVisibleBaseLyr, true); }; /** * Toggle the visible state of a layer. * Takes care of hiding other layers in the same exclusive group if the layer * is toggle to visible. * @private * @param {ol.layer.Base} The layer whos visibility will be toggled. */ ol.control.LayerSwitcher.prototype.setVisible_ = function(lyr, visible) { var map = this.getMap(); lyr.setVisible(visible); if (visible && lyr.get('type') === 'base') { // Hide all other base layers regardless of grouping ol.control.LayerSwitcher.forEachRecursive(map, function(l, idx, a) { if (l != lyr && l.get('type') === 'base') { l.setVisible(false); } }); } }; /** * Render all layers that are children of a group. * @private * @param {ol.layer.Base} lyr Layer to be rendered (should have a title property). * @param {Number} idx Position in parent group list. */ ol.control.LayerSwitcher.prototype.renderLayer_ = function(lyr, idx) { var this_ = this; var li = document.createElement('li'); var lyrTitle = lyr.get('title'); var lyrId = lyr.get('title').replace(' ', '-') + '_' + idx; var label = document.createElement('label'); if (lyr.getLayers) { li.className = 'group'; label.innerHTML = lyrTitle; li.appendChild(label); var ul = document.createElement('ul'); li.appendChild(ul); this.renderLayers_(lyr, ul); } else { var input = document.createElement('input'); if (lyr.get('type') === 'base') { input.type = 'radio'; input.name = 'base'; } else { input.type = 'checkbox'; } input.id = lyrId; input.checked = lyr.get('visible'); input.onchange = function(e) { this_.setVisible_(lyr, e.target.checked); }; li.appendChild(input); label.htmlFor = lyrId; label.innerHTML = lyrTitle; li.appendChild(label); } return li; }; /** * Render all layers that are children of a group. * @private * @param {ol.layer.Group} lyr Group layer whos children will be rendered. * @param {Element} elm DOM element that children will be appended to. */ ol.control.LayerSwitcher.prototype.renderLayers_ = function(lyr, elm) { var lyrs = lyr.getLayers().getArray().slice().reverse(); for (var i = 0, l; i < lyrs.length; i++) { l = lyrs[i]; if (l.get('title')) { elm.appendChild(this.renderLayer_(l, i)); } } }; /** * **Static** Call the supplied function for each layer in the passed layer group * recursing nested groups. * @param {ol.layer.Group} lyr The layer group to start iterating from. * @param {Function} fn Callback which will be called for each `ol.layer.Base` * found under `lyr`. The signature for `fn` is the same as `ol.Collection#forEach` */ ol.control.LayerSwitcher.forEachRecursive = function(lyr, fn) { lyr.getLayers().forEach(function(lyr, idx, a) { fn(lyr, idx, a); if (lyr.getLayers) { ol.control.LayerSwitcher.forEachRecursive(lyr, fn); } }); };
mwernimont/sparrow-ui
src/main/webapp/js/vendor/ol3-layerswitcher/1.0.2/ol3-layerswitcher.js
JavaScript
cc0-1.0
6,635
(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'); }); })();
rlugojr/cdnjs
ajax/libs/x-tag/1.5.10/x-tag-no-polyfills.js
JavaScript
mit
30,690
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview New tab page * This is the main code for the new tab page used by touch-enabled Chrome * browsers. For now this is still a prototype. */ // Use an anonymous function to enable strict mode just for this file (which // will be concatenated with other files when embedded in Chrome cr.define('ntp', function() { 'use strict'; /** * NewTabView instance. * @type {!Object|undefined} */ var newTabView; /** * The 'notification-container' element. * @type {!Element|undefined} */ var notificationContainer; /** * If non-null, an info bubble for showing messages to the user. It points at * the Most Visited label, and is used to draw more attention to the * navigation dot UI. * @type {!Element|undefined} */ var promoBubble; /** * If non-null, an bubble confirming that the user has signed into sync. It * points at the login status at the top of the page. * @type {!Element|undefined} */ var loginBubble; /** * true if |loginBubble| should be shown. * @type {boolean} */ var shouldShowLoginBubble = false; /** * The 'other-sessions-menu-button' element. * @type {!Element|undefined} */ var otherSessionsButton; /** * The time when all sections are ready. * @type {number|undefined} * @private */ var startTime; /** * The time in milliseconds for most transitions. This should match what's * in new_tab.css. Unfortunately there's no better way to try to time * something to occur until after a transition has completed. * @type {number} * @const */ var DEFAULT_TRANSITION_TIME = 500; /** * See description for these values in ntp_stats.h. * @enum {number} */ var NtpFollowAction = { CLICKED_TILE: 11, CLICKED_OTHER_NTP_PANE: 12, OTHER: 13 }; /** * Creates a NewTabView object. NewTabView extends PageListView with * new tab UI specific logics. * @constructor * @extends {PageListView} */ function NewTabView() { var pageSwitcherStart = null; var pageSwitcherEnd = null; if (loadTimeData.getValue('showApps')) { pageSwitcherStart = getRequiredElement('page-switcher-start'); pageSwitcherEnd = getRequiredElement('page-switcher-end'); } this.initialize(getRequiredElement('page-list'), getRequiredElement('dot-list'), getRequiredElement('card-slider-frame'), getRequiredElement('trash'), pageSwitcherStart, pageSwitcherEnd); } NewTabView.prototype = { __proto__: ntp.PageListView.prototype, /** @override */ appendTilePage: function(page, title, titleIsEditable, opt_refNode) { ntp.PageListView.prototype.appendTilePage.apply(this, arguments); if (promoBubble) window.setTimeout(promoBubble.reposition.bind(promoBubble), 0); } }; /** * Invoked at startup once the DOM is available to initialize the app. */ function onLoad() { sectionsToWaitFor = 0; if (loadTimeData.getBoolean('showMostvisited')) sectionsToWaitFor++; if (loadTimeData.getBoolean('showApps')) { sectionsToWaitFor++; if (loadTimeData.getBoolean('showAppLauncherPromo')) { $('app-launcher-promo-close-button').addEventListener('click', function() { chrome.send('stopShowingAppLauncherPromo'); }); $('apps-promo-learn-more').addEventListener('click', function() { chrome.send('onLearnMore'); }); } } if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled')) sectionsToWaitFor++; measureNavDots(); // Load the current theme colors. themeChanged(); newTabView = new NewTabView(); notificationContainer = getRequiredElement('notification-container'); notificationContainer.addEventListener( 'webkitTransitionEnd', onNotificationTransitionEnd); if (loadTimeData.getBoolean('showRecentlyClosed')) { cr.ui.decorate($('recently-closed-menu-button'), ntp.RecentMenuButton); chrome.send('getRecentlyClosedTabs'); } else { $('recently-closed-menu-button').hidden = true; } if (loadTimeData.getBoolean('showOtherSessionsMenu')) { otherSessionsButton = getRequiredElement('other-sessions-menu-button'); cr.ui.decorate(otherSessionsButton, ntp.OtherSessionsMenuButton); otherSessionsButton.initialize(loadTimeData.getBoolean('isUserSignedIn')); } else { getRequiredElement('other-sessions-menu-button').hidden = true; } if (loadTimeData.getBoolean('showMostvisited')) { var mostVisited = new ntp.MostVisitedPage(); // Move the footer into the most visited page if we are in "bare minimum" // mode. if (document.body.classList.contains('bare-minimum')) mostVisited.appendFooter(getRequiredElement('footer')); newTabView.appendTilePage(mostVisited, loadTimeData.getString('mostvisited'), false); chrome.send('getMostVisited'); } if (loadTimeData.getBoolean('isDiscoveryInNTPEnabled')) { var suggestionsScript = document.createElement('script'); suggestionsScript.src = 'suggestions_page.js'; suggestionsScript.onload = function() { newTabView.appendTilePage(new ntp.SuggestionsPage(), loadTimeData.getString('suggestions'), false, (newTabView.appsPages.length > 0) ? newTabView.appsPages[0] : null); chrome.send('getSuggestions'); cr.dispatchSimpleEvent(document, 'sectionready', true, true); }; document.querySelector('head').appendChild(suggestionsScript); } if (!loadTimeData.getBoolean('showWebStoreIcon')) { var webStoreIcon = $('chrome-web-store-link'); // Not all versions of the NTP have a footer, so this may not exist. if (webStoreIcon) webStoreIcon.hidden = true; } else { var webStoreLink = loadTimeData.getString('webStoreLink'); var url = appendParam(webStoreLink, 'utm_source', 'chrome-ntp-launcher'); $('chrome-web-store-link').href = url; $('chrome-web-store-link').addEventListener('click', onChromeWebStoreButtonClick); } // We need to wait for all the footer menu setup to be completed before // we can compute its layout. layoutFooter(); if (loadTimeData.getString('login_status_message')) { loginBubble = new cr.ui.Bubble; loginBubble.anchorNode = $('login-container'); loginBubble.arrowLocation = cr.ui.ArrowLocation.TOP_END; loginBubble.bubbleAlignment = cr.ui.BubbleAlignment.BUBBLE_EDGE_TO_ANCHOR_EDGE; loginBubble.deactivateToDismissDelay = 2000; loginBubble.closeButtonVisible = false; $('login-status-advanced').onclick = function() { chrome.send('showAdvancedLoginUI'); }; $('login-status-dismiss').onclick = loginBubble.hide.bind(loginBubble); var bubbleContent = $('login-status-bubble-contents'); loginBubble.content = bubbleContent; // The anchor node won't be updated until updateLogin is called so don't // show the bubble yet. shouldShowLoginBubble = true; } if (loadTimeData.valueExists('bubblePromoText')) { promoBubble = new cr.ui.Bubble; promoBubble.anchorNode = getRequiredElement('promo-bubble-anchor'); promoBubble.arrowLocation = cr.ui.ArrowLocation.BOTTOM_START; promoBubble.bubbleAlignment = cr.ui.BubbleAlignment.ENTIRELY_VISIBLE; promoBubble.deactivateToDismissDelay = 2000; promoBubble.content = parseHtmlSubset( loadTimeData.getString('bubblePromoText'), ['BR']); var bubbleLink = promoBubble.querySelector('a'); if (bubbleLink) { bubbleLink.addEventListener('click', function(e) { chrome.send('bubblePromoLinkClicked'); }); } promoBubble.handleCloseEvent = function() { promoBubble.hide(); chrome.send('bubblePromoClosed'); }; promoBubble.show(); chrome.send('bubblePromoViewed'); } var loginContainer = getRequiredElement('login-container'); loginContainer.addEventListener('click', showSyncLoginUI); if (loadTimeData.getBoolean('shouldShowSyncLogin')) chrome.send('initializeSyncLogin'); doWhenAllSectionsReady(function() { // Tell the slider about the pages. newTabView.updateSliderCards(); // Mark the current page. newTabView.cardSlider.currentCardValue.navigationDot.classList.add( 'selected'); if (loadTimeData.valueExists('notificationPromoText')) { var promoText = loadTimeData.getString('notificationPromoText'); var tags = ['IMG']; var attrs = { src: function(node, value) { return node.tagName == 'IMG' && /^data\:image\/(?:png|gif|jpe?g)/.test(value); }, }; var promo = parseHtmlSubset(promoText, tags, attrs); var promoLink = promo.querySelector('a'); if (promoLink) { promoLink.addEventListener('click', function(e) { chrome.send('notificationPromoLinkClicked'); }); } showNotification(promo, [], function() { chrome.send('notificationPromoClosed'); }, 60000); chrome.send('notificationPromoViewed'); } cr.dispatchSimpleEvent(document, 'ntpLoaded', true, true); document.documentElement.classList.remove('starting-up'); startTime = Date.now(); }); preventDefaultOnPoundLinkClicks(); // From webui/js/util.js. cr.ui.FocusManager.disableMouseFocusOnButtons(); } /** * Launches the chrome web store app with the chrome-ntp-launcher * source. * @param {Event} e The click event. */ function onChromeWebStoreButtonClick(e) { chrome.send('recordAppLaunchByURL', [encodeURIComponent(this.href), ntp.APP_LAUNCH.NTP_WEBSTORE_FOOTER]); } /* * The number of sections to wait on. * @type {number} */ var sectionsToWaitFor = -1; /** * Queued callbacks which lie in wait for all sections to be ready. * @type {array} */ var readyCallbacks = []; /** * Fired as each section of pages becomes ready. * @param {Event} e Each page's synthetic DOM event. */ document.addEventListener('sectionready', function(e) { if (--sectionsToWaitFor <= 0) { while (readyCallbacks.length) { readyCallbacks.shift()(); } } }); /** * This is used to simulate a fire-once event (i.e. $(document).ready() in * jQuery or Y.on('domready') in YUI. If all sections are ready, the callback * is fired right away. If all pages are not ready yet, the function is queued * for later execution. * @param {function} callback The work to be done when ready. */ function doWhenAllSectionsReady(callback) { assert(typeof callback == 'function'); if (sectionsToWaitFor > 0) readyCallbacks.push(callback); else window.setTimeout(callback, 0); // Do soon after, but asynchronously. } /** * Measure the width of a nav dot with a given title. * @param {string} id The loadTimeData ID of the desired title. * @return {number} The width of the nav dot. */ function measureNavDot(id) { var measuringDiv = $('fontMeasuringDiv'); measuringDiv.textContent = loadTimeData.getString(id); // The 4 is for border and padding. return Math.max(measuringDiv.clientWidth * 1.15 + 4, 80); } /** * Fills in an invisible div with the longest dot title string so that * its length may be measured and the nav dots sized accordingly. */ function measureNavDots() { var pxWidth = measureNavDot('appDefaultPageName'); if (loadTimeData.getBoolean('showMostvisited')) pxWidth = Math.max(measureNavDot('mostvisited'), pxWidth); var styleElement = document.createElement('style'); styleElement.type = 'text/css'; // max-width is used because if we run out of space, the nav dots will be // shrunk. styleElement.textContent = '.dot { max-width: ' + pxWidth + 'px; }'; document.querySelector('head').appendChild(styleElement); } /** * Layout the footer so that the nav dots stay centered. */ function layoutFooter() { // We need the image to be loaded. var logo = $('logo-img'); var logoImg = logo.querySelector('img'); if (!logoImg.complete) { logoImg.onload = layoutFooter; return; } var menu = $('footer-menu-container'); if (menu.clientWidth > logoImg.width) logo.style.WebkitFlex = '0 1 ' + menu.clientWidth + 'px'; else menu.style.WebkitFlex = '0 1 ' + logoImg.width + 'px'; } function themeChanged(opt_hasAttribution) { $('themecss').href = 'chrome://theme/css/new_tab_theme.css?' + Date.now(); if (typeof opt_hasAttribution != 'undefined') { document.documentElement.setAttribute('hasattribution', opt_hasAttribution); } updateAttribution(); } function setBookmarkBarAttached(attached) { document.documentElement.setAttribute('bookmarkbarattached', attached); } /** * Attributes the attribution image at the bottom left. */ function updateAttribution() { var attribution = $('attribution'); if (document.documentElement.getAttribute('hasattribution') == 'true') { attribution.hidden = false; } else { attribution.hidden = true; } } /** * Timeout ID. * @type {number} */ var notificationTimeout = 0; /** * Shows the notification bubble. * @param {string|Node} message The notification message or node to use as * message. * @param {Array.<{text: string, action: function()}>} links An array of * records describing the links in the notification. Each record should * have a 'text' attribute (the display string) and an 'action' attribute * (a function to run when the link is activated). * @param {Function} opt_closeHandler The callback invoked if the user * manually dismisses the notification. */ function showNotification(message, links, opt_closeHandler, opt_timeout) { window.clearTimeout(notificationTimeout); var span = document.querySelector('#notification > span'); if (typeof message == 'string') { span.textContent = message; } else { span.textContent = ''; // Remove all children. span.appendChild(message); } var linksBin = $('notificationLinks'); linksBin.textContent = ''; for (var i = 0; i < links.length; i++) { var link = linksBin.ownerDocument.createElement('div'); link.textContent = links[i].text; link.action = links[i].action; link.onclick = function() { this.action(); hideNotification(); }; link.setAttribute('role', 'button'); link.setAttribute('tabindex', 0); link.className = 'link-button'; linksBin.appendChild(link); } function closeFunc(e) { if (opt_closeHandler) opt_closeHandler(); hideNotification(); } document.querySelector('#notification button').onclick = closeFunc; document.addEventListener('dragstart', closeFunc); notificationContainer.hidden = false; showNotificationOnCurrentPage(); newTabView.cardSlider.frame.addEventListener( 'cardSlider:card_change_ended', onCardChangeEnded); var timeout = opt_timeout || 10000; notificationTimeout = window.setTimeout(hideNotification, timeout); } /** * Hide the notification bubble. */ function hideNotification() { notificationContainer.classList.add('inactive'); newTabView.cardSlider.frame.removeEventListener( 'cardSlider:card_change_ended', onCardChangeEnded); } /** * Happens when 1 or more consecutive card changes end. * @param {Event} e The cardSlider:card_change_ended event. */ function onCardChangeEnded(e) { // If we ended on the same page as we started, ignore. if (newTabView.cardSlider.currentCardValue.notification) return; // Hide the notification the old page. notificationContainer.classList.add('card-changed'); showNotificationOnCurrentPage(); } /** * Move and show the notification on the current page. */ function showNotificationOnCurrentPage() { var page = newTabView.cardSlider.currentCardValue; doWhenAllSectionsReady(function() { if (page != newTabView.cardSlider.currentCardValue) return; // NOTE: This moves the notification to inside of the current page. page.notification = notificationContainer; // Reveal the notification and instruct it to hide itself if ignored. notificationContainer.classList.remove('inactive'); // Gives the browser time to apply this rule before we remove it (causing // a transition). window.setTimeout(function() { notificationContainer.classList.remove('card-changed'); }, 0); }); } /** * When done fading out, set hidden to true so the notification can't be * tabbed to or clicked. * @param {Event} e The webkitTransitionEnd event. */ function onNotificationTransitionEnd(e) { if (notificationContainer.classList.contains('inactive')) notificationContainer.hidden = true; } function setRecentlyClosedTabs(dataItems) { $('recently-closed-menu-button').dataItems = dataItems; layoutFooter(); } function setMostVisitedPages(data, hasBlacklistedUrls) { newTabView.mostVisitedPage.data = data; cr.dispatchSimpleEvent(document, 'sectionready', true, true); } function setSuggestionsPages(data, hasBlacklistedUrls) { newTabView.suggestionsPage.data = data; } /** * Set the dominant color for a node. This will be called in response to * getFaviconDominantColor. The node represented by |id| better have a setter * for stripeColor. * @param {string} id The ID of a node. * @param {string} color The color represented as a CSS string. */ function setFaviconDominantColor(id, color) { var node = $(id); if (node) node.stripeColor = color; } /** * Updates the text displayed in the login container. If there is no text then * the login container is hidden. * @param {string} loginHeader The first line of text. * @param {string} loginSubHeader The second line of text. * @param {string} iconURL The url for the login status icon. If this is null then the login status icon is hidden. * @param {boolean} isUserSignedIn Indicates if the user is signed in or not. */ function updateLogin(loginHeader, loginSubHeader, iconURL, isUserSignedIn) { if (loginHeader || loginSubHeader) { $('login-container').hidden = false; $('login-status-header').innerHTML = loginHeader; $('login-status-sub-header').innerHTML = loginSubHeader; $('card-slider-frame').classList.add('showing-login-area'); if (iconURL) { $('login-status-header-container').style.backgroundImage = url(iconURL); $('login-status-header-container').classList.add('login-status-icon'); } else { $('login-status-header-container').style.backgroundImage = 'none'; $('login-status-header-container').classList.remove( 'login-status-icon'); } } else { $('login-container').hidden = true; $('card-slider-frame').classList.remove('showing-login-area'); } if (shouldShowLoginBubble) { window.setTimeout(loginBubble.show.bind(loginBubble), 0); chrome.send('loginMessageSeen'); shouldShowLoginBubble = false; } else if (loginBubble) { loginBubble.reposition(); } if (otherSessionsButton) { otherSessionsButton.updateSignInState(isUserSignedIn); layoutFooter(); } } /** * Show the sync login UI. * @param {Event} e The click event. */ function showSyncLoginUI(e) { var rect = e.currentTarget.getBoundingClientRect(); chrome.send('showSyncLoginUI', [rect.left, rect.top, rect.width, rect.height]); } /** * Logs the time to click for the specified item. * @param {string} item The item to log the time-to-click. */ function logTimeToClick(item) { var timeToClick = Date.now() - startTime; chrome.send('logTimeToClick', ['NewTabPage.TimeToClick' + item, timeToClick]); } /** * Wrappers to forward the callback to corresponding PageListView member. */ function appAdded() { return newTabView.appAdded.apply(newTabView, arguments); } function appMoved() { return newTabView.appMoved.apply(newTabView, arguments); } function appRemoved() { return newTabView.appRemoved.apply(newTabView, arguments); } function appsPrefChangeCallback() { return newTabView.appsPrefChangedCallback.apply(newTabView, arguments); } function appLauncherPromoPrefChangeCallback() { return newTabView.appLauncherPromoPrefChangeCallback.apply(newTabView, arguments); } function appsReordered() { return newTabView.appsReordered.apply(newTabView, arguments); } function enterRearrangeMode() { return newTabView.enterRearrangeMode.apply(newTabView, arguments); } function setForeignSessions(sessionList, isTabSyncEnabled) { if (otherSessionsButton) { otherSessionsButton.setForeignSessions(sessionList, isTabSyncEnabled); layoutFooter(); } } function getAppsCallback() { return newTabView.getAppsCallback.apply(newTabView, arguments); } function getAppsPageIndex() { return newTabView.getAppsPageIndex.apply(newTabView, arguments); } function getCardSlider() { return newTabView.cardSlider; } function leaveRearrangeMode() { return newTabView.leaveRearrangeMode.apply(newTabView, arguments); } function saveAppPageName() { return newTabView.saveAppPageName.apply(newTabView, arguments); } function setAppToBeHighlighted(appId) { newTabView.highlightAppId = appId; } // Return an object with all the exports return { appAdded: appAdded, appMoved: appMoved, appRemoved: appRemoved, appsPrefChangeCallback: appsPrefChangeCallback, appLauncherPromoPrefChangeCallback: appLauncherPromoPrefChangeCallback, enterRearrangeMode: enterRearrangeMode, getAppsCallback: getAppsCallback, getAppsPageIndex: getAppsPageIndex, getCardSlider: getCardSlider, onLoad: onLoad, leaveRearrangeMode: leaveRearrangeMode, logTimeToClick: logTimeToClick, NtpFollowAction: NtpFollowAction, saveAppPageName: saveAppPageName, setAppToBeHighlighted: setAppToBeHighlighted, setBookmarkBarAttached: setBookmarkBarAttached, setForeignSessions: setForeignSessions, setMostVisitedPages: setMostVisitedPages, setSuggestionsPages: setSuggestionsPages, setRecentlyClosedTabs: setRecentlyClosedTabs, setFaviconDominantColor: setFaviconDominantColor, showNotification: showNotification, themeChanged: themeChanged, updateLogin: updateLogin }; }); document.addEventListener('DOMContentLoaded', ntp.onLoad); var toCssPx = cr.ui.toCssPx;
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/resources/ntp4/new_tab.js
JavaScript
gpl-3.0
23,568
/** * 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" + ""); }]);
dhenson02/cdnjs
ajax/libs/ng-wig/1.1.3/ng-wig.js
JavaScript
mit
6,452
/** * Arabic translation (Syrian Localization, it may differ if you aren't from Syria or any Country in Middle East) * @author Tawfek Daghistani <[email protected]> * @version 2011-07-09 */ if (elFinder && elFinder.prototype && typeof(elFinder.prototype.i18) == 'object') { elFinder.prototype.i18.ar = { translator : 'Tawfek Daghistani &lt;[email protected]&gt;', language : 'العربية', direction : 'rtl', messages : { /********************************** errors **********************************/ 'error' : 'خطأ', 'errUnknown' : 'خطأ غير معروف .', 'errUnknownCmd' : 'أمر غير معروف .', 'errJqui' : 'إعدادات jQuery UI غير كاملة الرجاء التأكد من وجود كل من selectable, draggable and droppable', 'errNode' : '. موجود DOM إلى عنصر elFinder تحتاج ', 'errURL' : 'إعدادات خاطئة , عليك وضع الرابط ضمن الإعدادات', 'errAccess' : 'وصول مرفوض .', 'errConnect' : 'غير قادر على الاتصال بالخادم الخلفي (backend)', 'errAbort' : 'تم فصل الإتصال', 'errTimeout' : 'مهلة الإتصال قد إنتهت .', 'errNotFound' : 'الخادم الخلفي غير موجود .', 'errResponse' : 'رد غير مقبول من الخادم الخلفي', 'errConf' : 'خطأ في الإعدادات الخاصة بالخادم الخلفي ', 'errJSON' : 'الميزة PHP JSON module غير موجودة ', 'errNoVolumes' : 'لا يمكن القراءة من أي من الوسائط الموجودة ', 'errCmdParams' : 'البيانات المرسلة للأمر غير مقبولة "$1".', 'errDataNotJSON' : 'المعلومات المرسلة ليست من نوع JSON ', 'errDataEmpty' : 'لا يوجد معلومات مرسلة', 'errCmdReq' : 'الخادم الخلفي يطلب وجود اسم الأمر ', 'errOpen' : 'غير قادر على فتح "$1".', 'errNotFolder' : 'العنصر المختار ليس مجلد', 'errNotFile' : 'العنصر المختار ليس ملف', 'errRead' : 'غير قادر على القراءة "$1".', 'errWrite' : 'غير قادر على الكتابة "$1".', 'errPerm' : 'وصول مرفوض ', 'errLocked' : ' محمي و لا يمكن التعديل أو النقل أو إعادة التسمية"$1"', 'errExists' : ' موجود مسبقاً "$1"', 'errInvName' : 'الاسم مرفوض', 'errFolderNotFound' : 'المجلد غير موجود', 'errFileNotFound' : 'الملف غير موجود', 'errTrgFolderNotFound' : 'الملف الهدف "$1" غير موجود ', 'errPopup' : 'يمنعني المتصفح من إنشاء نافذة منبثقة , الرجاء تعديل الخيارات الخاصة من إعدادات المتصفح ', 'errMkdir' : ' غير قادر على إنشاء مجلد جديد "$1".', 'errMkfile' : ' غير قادر على إنشاء ملف جديد"$1".', 'errRename' : 'غير قادر على إعادة تسمية ال "$1".', 'errCopyFrom' : 'نسخ الملفات من الوسط المحدد "$1"غير مسموح.', 'errCopyTo' : 'نسخ الملفات إلى الوسط المحدد "$1" غير مسموح .', 'errUploadCommon' : 'خطأ أثناء عملية الرفع', 'errUpload' : 'غير قادر على رفع "$1".', 'errUploadNoFiles' : 'لم يتم رفع أي ملف ', 'errMaxSize' : 'حجم البيانات أكبر من الحجم المسموح به ', 'errFileMaxSize' : 'حجم الملف أكبر من الحجم المسموح به', 'errUploadMime' : 'نوع ملف غير مسموح ', 'errUploadTransfer' : '"$1" خطأ أثناء عملية النقل', 'errSave' : 'غير قادر على الحفظ في "$1".', 'errCopy' : 'غير قادر على النسخ إلى"$1".', 'errMove' : 'غير قادر على القص إلى "$1".', 'errCopyInItself' : 'غير قادر على نسخ الملف "$1" ضمن الملف نفسه.', 'errRm' : 'غير قادر على الحذف "$1".', 'errExtract' : 'غير قادر على استخراج الملفات من "$1".', 'errArchive' : 'غير قادر على إنشاء ملف مضغوط', 'errArcType' : 'نوع الملف المضغوط غير مدعومة', 'errNoArchive' : 'هذا الملف ليس ملف مضغوط أو ذو صسغة غير مدعومة ', 'errCmdNoSupport' : 'الخادم الخلفي لا يدعم هذا الأمر ', 'errReplByChild' : 'The folder “$1” can’t be replaced by an item it contains.', 'errArcSymlinks' : 'For security reason denied to unpack archives contains symlinks.', 'errArcMaxSize' : 'Archive files exceeds maximum allowed size.', /******************************* commands names ********************************/ 'cmdarchive' : 'أنشئ مجلد مضغوط', 'cmdback' : 'الخلف', 'cmdcopy' : 'نسخ', 'cmdcut' : 'قص', 'cmddownload' : 'تحميل', 'cmdduplicate' : 'تكرار', 'cmdedit' : 'تعديل الملف', 'cmdextract' : 'استخراج الملفات', 'cmdforward' : 'الأمام', 'cmdgetfile' : 'أختيار الملفات', 'cmdhelp' : 'عن هذا المشروع', 'cmdhome' : 'المجلد الرئيسي', 'cmdinfo' : 'معلومات ', 'cmdmkdir' : 'مجلد جديد', 'cmdmkfile' : 'ملف نصي جديد', 'cmdopen' : 'فتح', 'cmdpaste' : 'لصق', 'cmdquicklook' : 'معاينة', 'cmdreload' : 'إعادة تحميل', 'cmdrename' : 'إعادة تسمية', 'cmdrm' : 'حذف', 'cmdsearch' : 'بحث عن ملفات', 'cmdup' : 'تغيير المسار إلى مستوى أعلى', 'cmdupload' : 'رفع ملفات', 'cmdview' : 'عرض', /*********************************** buttons ***********************************/ 'btnClose' : 'إغلاق', 'btnSave' : 'حفظ', 'btnRm' : 'إزالة', 'btnCancel' : 'إلغاء', 'btnNo' : 'لا', 'btnYes' : 'نعم', /******************************** notifications ********************************/ 'ntfopen' : 'فتح مجلد', 'ntffile' : 'فتح ملف', 'ntfreload' : 'إعادة عرض محتويات المجلد ', 'ntfmkdir' : 'ينشئ المجلدات', 'ntfmkfile' : 'ينشئ الملفات', 'ntfrm' : 'حذف الملفات', 'ntfcopy' : 'نسخ الملفات', 'ntfmove' : 'نقل الملفات', 'ntfprepare' : 'تحضير لنسخ الملفات', 'ntfrename' : 'إعادة تسمية الملفات', 'ntfupload' : 'رفع الملفات', 'ntfdownload' : 'تحميل الملفات', 'ntfsave' : 'حفظ الملفات', 'ntfarchive' : 'ينشئ ملف مضغوط', 'ntfextract' : 'استخراج ملفات من الملف المضغوط ', 'ntfsearch' : 'يبحث عن ملفات', 'ntfsmth' : 'يحضر لشيء ما >_<', /************************************ dates **********************************/ 'dateUnknown' : 'غير معلوم', 'Today' : 'اليوم', 'Yesterday' : 'البارحة', 'Jan' : 'كانون الثاني', 'Feb' : 'شباط', 'Mar' : 'آذار', 'Apr' : 'نيسان', 'May' : 'أيار', 'Jun' : 'حزيران', 'Jul' : 'تموز', 'Aug' : 'آب', 'Sep' : 'أيلول', 'Oct' : 'تشرين الأول', 'Nov' : 'تشرين الثاني', 'Dec' : 'كانون الأول ', /********************************** messages **********************************/ 'confirmReq' : 'يرجى التأكيد', 'confirmRm' : 'هل انت متأكد من انك تريد الحذف<br/>لا يمكن التراجع عن هذه العملية ', 'confirmRepl' : 'استبدال الملف القديم بملف جديد ؟', 'apllyAll' : 'تطبيق على الكل', 'name' : 'الأسم', 'size' : 'الحجم', 'perms' : 'الصلاحيات', 'modify' : 'أخر تعديل', 'kind' : 'نوع الملف', 'read' : 'قراءة', 'write' : 'كتابة', 'noaccess' : 'وصول ممنوع', 'and' : 'و', 'unknown' : 'غير معروف', 'selectall' : 'تحديد كل الملفات', 'selectfiles' : 'تحديد ملفات', 'selectffile' : 'تحديد الملف الاول', 'selectlfile' : 'تحديد الملف الأخير', 'viewlist' : 'اعرض ك قائمة', 'viewicons' : 'اعرض ك ايقونات', 'places' : 'المواقع', 'calc' : 'حساب', 'path' : 'مسار', 'aliasfor' : 'Alias for', 'locked' : 'مقفول', 'dim' : 'الابعاد', 'files' : 'ملفات', 'folders' : 'مجلدات', 'items' : 'عناصر', 'yes' : 'نعم', 'no' : 'لا', 'link' : 'اربتاط', 'searcresult' : 'نتائج البحث', 'selected' : 'العناصر المحددة', 'about' : 'عن البرنامج', 'shortcuts' : 'الاختصارات', 'help' : 'مساعدة', 'webfm' : 'مدير ملفات الويب', 'ver' : 'رقم الإصدار', 'protocol' : 'اصدار البرتوكول', 'homepage' : 'الصفحة الرئيسية', 'docs' : 'التعليمات', 'github' : 'شاركنا بتطوير المشروع على Github', 'twitter' : 'تابعنا على تويتر', 'facebook' : 'انضم إلينا على الفيس بوك', 'team' : 'الفريق', 'chiefdev' : 'رئيس المبرمجين', 'developer' : 'مبرمح', 'contributor' : 'مبرمح', 'maintainer' : 'مشارك', 'translator' : 'مترجم', 'icons' : 'أيقونات', 'dontforget' : 'and don\'t forget to take your towel', 'shortcutsof' : 'الاختصارات غير مفعلة', 'dropFiles' : 'لصق الملفات هنا', 'or' : 'أو', 'selectForUpload' : 'اختر الملفات التي تريد رفعها', 'moveFiles' : 'قص الملفات', 'copyFiles' : 'نسخ الملفات', 'rmFromPlaces' : 'Remove from places', 'untitled folder' : 'untitled folder', 'untitled file.txt' : 'untitled file.txt', /********************************** mimetypes **********************************/ 'kindUnknown' : 'غير معروف', 'kindFolder' : 'مجلد', 'kindAlias' : 'اختصار', 'kindAliasBroken' : 'اختصار غير صالح', // applications 'kindApp' : 'برنامج', 'kindPostscript' : 'Postscript ملف', 'kindMsOffice' : 'Microsoft Office ملف', 'kindMsWord' : 'Microsoft Word ملف', 'kindMsExcel' : 'Microsoft Excel ملف', 'kindMsPP' : 'Microsoft Powerpoint عرض تقديمي ', 'kindOO' : 'Open Office ملف', 'kindAppFlash' : 'تطبيق فلاش', 'kindPDF' : 'ملف (PDF)', 'kindTorrent' : 'Bittorrent ملف', 'kind7z' : '7z ملف', 'kindTAR' : 'TAR ملف', 'kindGZIP' : 'GZIP ملف', 'kindBZIP' : 'BZIP ملف', 'kindZIP' : 'ZIP ملف', 'kindRAR' : 'RAR ملف', 'kindJAR' : 'Java JAR ملف', 'kindTTF' : 'True Type خط ', 'kindOTF' : 'Open Type خط ', 'kindRPM' : 'RPM ملف تنصيب', // texts 'kindText' : 'Text ملف', 'kindTextPlain' : 'مستند نصي', 'kindPHP' : 'PHP ملف نصي برمجي لـ', 'kindCSS' : 'Cascading style sheet', 'kindHTML' : 'HTML ملف', 'kindJS' : 'Javascript ملف نصي برمجي لـ', 'kindRTF' : 'Rich Text Format', 'kindC' : 'C ملف نصي برمجي لـ', 'kindCHeader' : 'C header ملف نصي برمجي لـ', 'kindCPP' : 'C++ ملف نصي برمجي لـ', 'kindCPPHeader' : 'C++ header ملف نصي برمجي لـ', 'kindShell' : 'Unix shell script', 'kindPython' : 'Python ملف نصي برمجي لـ', 'kindJava' : 'Java ملف نصي برمجي لـ', 'kindRuby' : 'Ruby ملف نصي برمجي لـ', 'kindPerl' : 'Perl script', 'kindSQL' : 'SQL ملف نصي برمجي لـ', 'kindXML' : 'XML ملف', 'kindAWK' : 'AWK ملف نصي برمجي لـ', 'kindCSV' : 'ملف CSV', 'kindDOCBOOK' : 'Docbook XML ملف', // images 'kindصورة' : 'صورة', 'kindBMP' : 'BMP صورة', 'kindJPEG' : 'JPEG صورة', 'kindGIF' : 'GIF صورة', 'kindPNG' : 'PNG صورة', 'kindTIFF' : 'TIFF صورة', 'kindTGA' : 'TGA صورة', 'kindPSD' : 'Adobe Photoshop صورة', 'kindXBITMAP' : 'X bitmap صورة', 'kindPXM' : 'Pixelmator صورة', // media 'kindAudio' : 'ملف صوتي', 'kindAudioMPEG' : 'MPEG ملف صوتي', 'kindAudioMPEG4' : 'MPEG-4 ملف صوتي', 'kindAudioMIDI' : 'MIDI ملف صوتي', 'kindAudioOGG' : 'Ogg Vorbis ملف صوتي', 'kindAudioWAV' : 'WAV ملف صوتي', 'AudioPlaylist' : 'MP3 قائمة تشغيل', 'kindVideo' : 'ملف فيديو', 'kindVideoDV' : 'DV ملف فيديو', 'kindVideoMPEG' : 'MPEG ملف فيديو', 'kindVideoMPEG4' : 'MPEG-4 ملف فيديو', 'kindVideoAVI' : 'AVI ملف فيديو', 'kindVideoMOV' : 'Quick Time ملف فيديو', 'kindVideoWM' : 'Windows Media ملف فيديو', 'kindVideoFlash' : 'Flash ملف فيديو', 'kindVideoMKV' : 'Matroska ملف فيديو', 'kindVideoOGG' : 'Ogg ملف فيديو' } } }
tokenly/tokenly-cms
www/themes/tokentalk/js/i18n/elfinder.ar.js
JavaScript
gpl-2.0
14,935
/** * 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;
Eurofunk/ag-grid
dist/lib/selectionRendererFactory.js
JavaScript
mit
2,720
/* 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(); }
viskin/cdnjs
ajax/libs/spellbook/0.0.28/spellbook.js
JavaScript
mit
9,757
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* jslint sloppy:true */ /* global Windows:true, setImmediate */ var cordova = require('cordova'), urlutil = require('cordova/urlutil'); var browserWrap, popup, navigationButtonsDiv, navigationButtonsDivInner, backButton, forwardButton, closeButton, bodyOverflowStyle, navigationEventsCallback; // x-ms-webview is available starting from Windows 8.1 (platformId is 'windows') // http://msdn.microsoft.com/en-us/library/windows/apps/dn301831.aspx var isWebViewAvailable = cordova.platformId === 'windows'; function attachNavigationEvents(element, callback) { if (isWebViewAvailable) { element.addEventListener("MSWebViewNavigationStarting", function (e) { callback({ type: "loadstart", url: e.uri}, {keepCallback: true} ); }); element.addEventListener("MSWebViewNavigationCompleted", function (e) { if (e.isSuccess) { callback({ type: "loadstop", url: e.uri }, { keepCallback: true }); } else { callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true }); } }); element.addEventListener("MSWebViewUnviewableContentIdentified", function (e) { // WebView found the content to be not HTML. // http://msdn.microsoft.com/en-us/library/windows/apps/dn609716.aspx callback({ type: "loaderror", url: e.uri, code: e.webErrorStatus, message: "Navigation failed with error code " + e.webErrorStatus}, { keepCallback: true }); }); element.addEventListener("MSWebViewContentLoading", function (e) { if (navigationButtonsDiv && popup) { if (popup.canGoBack) { backButton.removeAttribute("disabled"); } else { backButton.setAttribute("disabled", "true"); } if (popup.canGoForward) { forwardButton.removeAttribute("disabled"); } else { forwardButton.setAttribute("disabled", "true"); } } }); } else { var onError = function () { callback({ type: "loaderror", url: this.contentWindow.location}, {keepCallback: true}); }; element.addEventListener("unload", function () { callback({ type: "loadstart", url: this.contentWindow.location}, {keepCallback: true}); }); element.addEventListener("load", function () { callback({ type: "loadstop", url: this.contentWindow.location}, {keepCallback: true}); }); element.addEventListener("error", onError); element.addEventListener("abort", onError); } } var IAB = { close: function (win, lose) { setImmediate(function () { if (browserWrap) { if (navigationEventsCallback) { navigationEventsCallback({ type: "exit" }); } browserWrap.parentNode.removeChild(browserWrap); // Reset body overflow style to initial value document.body.style.msOverflowStyle = bodyOverflowStyle; browserWrap = null; popup = null; } }); }, show: function (win, lose) { setImmediate(function () { if (browserWrap) { browserWrap.style.display = "block"; } }); }, open: function (win, lose, args) { // make function async so that we can add navigation events handlers before view is loaded and navigation occured setImmediate(function () { var strUrl = args[0], target = args[1], features = args[2], url; navigationEventsCallback = win; if (target === "_system") { url = new Windows.Foundation.Uri(strUrl); Windows.System.Launcher.launchUriAsync(url); } else if (target === "_self" || !target) { window.location = strUrl; } else { // "_blank" or anything else if (!browserWrap) { var browserWrapStyle = document.createElement('link'); browserWrapStyle.rel = "stylesheet"; browserWrapStyle.type = "text/css"; browserWrapStyle.href = urlutil.makeAbsolute("/www/css/inappbrowser.css"); document.head.appendChild(browserWrapStyle); browserWrap = document.createElement("div"); browserWrap.className = "inAppBrowserWrap"; if (features.indexOf("fullscreen=yes") > -1) { browserWrap.classList.add("inAppBrowserWrapFullscreen"); } // Save body overflow style to be able to reset it back later bodyOverflowStyle = document.body.style.msOverflowStyle; browserWrap.onclick = function () { setTimeout(function () { IAB.close(navigationEventsCallback); }, 0); }; document.body.appendChild(browserWrap); // Hide scrollbars for the whole body while inappbrowser's window is open document.body.style.msOverflowStyle = "none"; } if (features.indexOf("hidden=yes") !== -1) { browserWrap.style.display = "none"; } popup = document.createElement(isWebViewAvailable ? "x-ms-webview" : "iframe"); if (popup instanceof HTMLIFrameElement) { // For iframe we need to override bacground color of parent element here // otherwise pages without background color set will have transparent background popup.style.backgroundColor = "white"; } popup.style.borderWidth = "0px"; popup.style.width = "100%"; browserWrap.appendChild(popup); if (features.indexOf("location=yes") !== -1 || features.indexOf("location") === -1) { popup.style.height = "calc(100% - 70px)"; navigationButtonsDiv = document.createElement("div"); navigationButtonsDiv.className = "inappbrowser-app-bar"; navigationButtonsDiv.onclick = function (e) { e.cancelBubble = true; }; navigationButtonsDivInner = document.createElement("div"); navigationButtonsDivInner.className = "inappbrowser-app-bar-inner"; navigationButtonsDivInner.onclick = function (e) { e.cancelBubble = true; }; backButton = document.createElement("div"); backButton.innerText = "back"; backButton.className = "app-bar-action action-back"; backButton.addEventListener("click", function (e) { if (popup.canGoBack) popup.goBack(); }); forwardButton = document.createElement("div"); forwardButton.innerText = "forward"; forwardButton.className = "app-bar-action action-forward"; forwardButton.addEventListener("click", function (e) { if (popup.canGoForward) popup.goForward(); }); closeButton = document.createElement("div"); closeButton.innerText = "close"; closeButton.className = "app-bar-action action-close"; closeButton.addEventListener("click", function (e) { setTimeout(function () { IAB.close(navigationEventsCallback); }, 0); }); if (!isWebViewAvailable) { // iframe navigation is not yet supported backButton.setAttribute("disabled", "true"); forwardButton.setAttribute("disabled", "true"); } navigationButtonsDivInner.appendChild(backButton); navigationButtonsDivInner.appendChild(forwardButton); navigationButtonsDivInner.appendChild(closeButton); navigationButtonsDiv.appendChild(navigationButtonsDivInner); browserWrap.appendChild(navigationButtonsDiv); } else { popup.style.height = "100%"; } // start listening for navigation events attachNavigationEvents(popup, navigationEventsCallback); if (isWebViewAvailable) { strUrl = strUrl.replace("ms-appx://", "ms-appx-web://"); } popup.src = strUrl; } }); }, injectScriptCode: function (win, fail, args) { setImmediate(function () { var code = args[0], hasCallback = args[1]; if (isWebViewAvailable && browserWrap && popup) { var op = popup.invokeScriptAsync("eval", code); op.oncomplete = function (e) { if (hasCallback) { // return null if event target is unavailable by some reason var result = (e && e.target) ? [e.target.result] : [null]; win(result); } }; op.onerror = function () { }; op.start(); } }); }, injectScriptFile: function (win, fail, args) { setImmediate(function () { var filePath = args[0], hasCallback = args[1]; if (!!filePath) { filePath = urlutil.makeAbsolute(filePath); } if (isWebViewAvailable && browserWrap && popup) { var uri = new Windows.Foundation.Uri(filePath); Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).done(function (file) { Windows.Storage.FileIO.readTextAsync(file).done(function (code) { var op = popup.invokeScriptAsync("eval", code); op.oncomplete = function(e) { if (hasCallback) { var result = [e.target.result]; win(result); } }; op.onerror = function () { }; op.start(); }); }); } }); }, injectStyleCode: function (win, fail, args) { setImmediate(function () { var code = args[0], hasCallback = args[1]; if (isWebViewAvailable && browserWrap && popup) { injectCSS(popup, code, hasCallback && win); } }); }, injectStyleFile: function (win, fail, args) { setImmediate(function () { var filePath = args[0], hasCallback = args[1]; filePath = filePath && urlutil.makeAbsolute(filePath); if (isWebViewAvailable && browserWrap && popup) { var uri = new Windows.Foundation.Uri(filePath); Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) { return Windows.Storage.FileIO.readTextAsync(file); }).done(function (code) { injectCSS(popup, code, hasCallback && win); }, function () { // no-op, just catch an error }); } }); } }; function injectCSS (webView, cssCode, callback) { // This will automatically escape all thing that we need (quotes, slashes, etc.) var escapedCode = JSON.stringify(cssCode); var evalWrapper = "(function(d){var c=d.createElement('style');c.innerHTML=%s;d.head.appendChild(c);})(document)" .replace('%s', escapedCode); var op = webView.invokeScriptAsync("eval", evalWrapper); op.oncomplete = function() { if (callback) { callback([]); } }; op.onerror = function () { }; op.start(); } module.exports = IAB; require("cordova/exec/proxy").add("InAppBrowser", module.exports);
aroegies/trecrts-tools
trecrts-mobile-app/plugins/cordova-plugin-inappbrowser/src/windows/InAppBrowserProxy.js
JavaScript
apache-2.0
13,645
/** File Name: expression-014.js Corresponds To: ecma/Expressions/11.2.2-9-n.js ECMA Section: 11.2.2. The new operator Description: Author: [email protected] Date: 12 november 1997 */ var SECTION = "expression-014.js"; var VERSION = "ECMA_1"; var TITLE = "The new operator"; var BUGNUMBER= "327765"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); var tc = 0; var testcases = new Array(); var BOOLEAN = new Boolean(); var result = "Failed"; var exception = "No exception thrown"; var expect = "Passed"; try { result = new BOOLEAN(); } catch ( e ) { result = expect; exception = e.toString(); } testcases[tc++] = new TestCase( SECTION, "BOOLEAN = new Boolean(); result = new BOOLEAN()" + " (threw " + exception +")", expect, result ); test();
danialbehzadi/Nokia-RM-1013-2.0.0.11
webkit/Source/JavaScriptCore/tests/mozilla/ecma_2/Exceptions/expression-014.js
JavaScript
gpl-3.0
966
"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
diegojromerolopez/djanban
src/djanban/static/angularapps/taskboard/node_modules/rxjs/scheduler/VirtualTimeScheduler.js
JavaScript
mit
3,914
(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]);
AMoo-Miki/cdnjs
ajax/libs/forerunnerdb/1.3.505/fdb-core.js
JavaScript
mit
240,356
import css from './source.css'; __export__ = css; export default css;
webpack-contrib/css-loader
test/fixtures/postcss-present-env/source.js
JavaScript
mit
72
/*! * 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));
wayne-lewis/baiducdnstatic
libs/platform/0.4.0/platform.js
JavaScript
mit
29,104
'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"); };
yuyang545262477/Resume
项目二电商首页/node_modules/es5-ext/test/object/valid-object.js
JavaScript
mit
506
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. cr.define('cr.ui', function() { // require cr.ui.define // require cr.ui.limitInputWidth /** * The number of pixels to indent per level. * @type {number} * @const */ var INDENT = 20; /** * Returns the computed style for an element. * @param {!Element} el The element to get the computed style for. * @return {!CSSStyleDeclaration} The computed style. */ function getComputedStyle(el) { return el.ownerDocument.defaultView.getComputedStyle(el); } /** * Helper function that finds the first ancestor tree item. * @param {!Element} el The element to start searching from. * @return {cr.ui.TreeItem} The found tree item or null if not found. */ function findTreeItem(el) { while (el && !(el instanceof TreeItem)) { el = el.parentNode; } return el; } /** * Creates a new tree element. * @param {Object=} opt_propertyBag Optional properties. * @constructor * @extends {HTMLElement} */ var Tree = cr.ui.define('tree'); Tree.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the element. */ decorate: function() { // Make list focusable if (!this.hasAttribute('tabindex')) this.tabIndex = 0; this.addEventListener('click', this.handleClick); this.addEventListener('mousedown', this.handleMouseDown); this.addEventListener('dblclick', this.handleDblClick); this.addEventListener('keydown', this.handleKeyDown); }, /** * Returns the tree item that are children of this tree. */ get items() { return this.children; }, /** * Adds a tree item to the tree. * @param {!cr.ui.TreeItem} treeItem The item to add. */ add: function(treeItem) { this.addAt(treeItem, 0xffffffff); }, /** * Adds a tree item at the given index. * @param {!cr.ui.TreeItem} treeItem The item to add. * @param {number} index The index where we want to add the item. */ addAt: function(treeItem, index) { this.insertBefore(treeItem, this.children[index]); treeItem.setDepth_(this.depth + 1); }, /** * Removes a tree item child. * @param {!cr.ui.TreeItem} treeItem The tree item to remove. */ remove: function(treeItem) { this.removeChild(treeItem); }, /** * The depth of the node. This is 0 for the tree itself. * @type {number} */ get depth() { return 0; }, /** * Handles click events on the tree and forwards the event to the relevant * tree items as necesary. * @param {Event} e The click event object. */ handleClick: function(e) { var treeItem = findTreeItem(e.target); if (treeItem) treeItem.handleClick(e); }, handleMouseDown: function(e) { if (e.button == 2) // right this.handleClick(e); }, /** * Handles double click events on the tree. * @param {Event} e The dblclick event object. */ handleDblClick: function(e) { var treeItem = findTreeItem(e.target); if (treeItem) treeItem.expanded = !treeItem.expanded; }, /** * Handles keydown events on the tree and updates selection and exanding * of tree items. * @param {Event} e The click event object. */ handleKeyDown: function(e) { var itemToSelect; if (e.ctrlKey) return; var item = this.selectedItem; if (!item) return; var rtl = getComputedStyle(item).direction == 'rtl'; switch (e.keyIdentifier) { case 'Up': itemToSelect = item ? getPrevious(item) : this.items[this.items.length - 1]; break; case 'Down': itemToSelect = item ? getNext(item) : this.items[0]; break; case 'Left': case 'Right': // Don't let back/forward keyboard shortcuts be used. if (!cr.isMac && e.altKey || cr.isMac && e.metaKey) break; if (e.keyIdentifier == 'Left' && !rtl || e.keyIdentifier == 'Right' && rtl) { if (item.expanded) item.expanded = false; else itemToSelect = findTreeItem(item.parentNode); } else { if (!item.expanded) item.expanded = true; else itemToSelect = item.items[0]; } break; case 'Home': itemToSelect = this.items[0]; break; case 'End': itemToSelect = this.items[this.items.length - 1]; break; } if (itemToSelect) { itemToSelect.selected = true; e.preventDefault(); } }, /** * The selected tree item or null if none. * @type {cr.ui.TreeItem} */ get selectedItem() { return this.selectedItem_ || null; }, set selectedItem(item) { var oldSelectedItem = this.selectedItem_; if (oldSelectedItem != item) { // Set the selectedItem_ before deselecting the old item since we only // want one change when moving between items. this.selectedItem_ = item; if (oldSelectedItem) oldSelectedItem.selected = false; if (item) item.selected = true; cr.dispatchSimpleEvent(this, 'change'); } }, /** * @return {!ClientRect} The rect to use for the context menu. */ getRectForContextMenu: function() { // TODO(arv): Add trait support so we can share more code between trees // and lists. if (this.selectedItem) return this.selectedItem.rowElement.getBoundingClientRect(); return this.getBoundingClientRect(); } }; /** * Determines the visibility of icons next to the treeItem labels. If set to * 'hidden', no space is reserved for icons and no icons are displayed next * to treeItem labels. If set to 'parent', folder icons will be displayed * next to expandable parent nodes. If set to 'all' folder icons will be * displayed next to all nodes. Icons can be set using the treeItem's icon * property. */ cr.defineProperty(Tree, 'iconVisibility', cr.PropertyKind.ATTR); /** * This is used as a blueprint for new tree item elements. * @type {!HTMLElement} */ var treeItemProto = (function() { var treeItem = cr.doc.createElement('div'); treeItem.className = 'tree-item'; treeItem.innerHTML = '<div class=tree-row>' + '<span class=expand-icon></span>' + '<span class=tree-label></span>' + '</div>' + '<div class=tree-children></div>'; treeItem.setAttribute('role', 'treeitem'); return treeItem; })(); /** * Creates a new tree item. * @param {Object=} opt_propertyBag Optional properties. * @constructor * @extends {HTMLElement} */ var TreeItem = cr.ui.define(function() { return treeItemProto.cloneNode(true); }); TreeItem.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the element. */ decorate: function() { }, /** * The tree items children. */ get items() { return this.lastElementChild.children; }, /** * The depth of the tree item. * @type {number} */ depth_: 0, get depth() { return this.depth_; }, /** * Sets the depth. * @param {number} depth The new depth. * @private */ setDepth_: function(depth) { if (depth != this.depth_) { this.rowElement.style.WebkitPaddingStart = Math.max(0, depth - 1) * INDENT + 'px'; this.depth_ = depth; var items = this.items; for (var i = 0, item; item = items[i]; i++) { item.setDepth_(depth + 1); } } }, /** * Adds a tree item as a child. * @param {!cr.ui.TreeItem} child The child to add. */ add: function(child) { this.addAt(child, 0xffffffff); }, /** * Adds a tree item as a child at a given index. * @param {!cr.ui.TreeItem} child The child to add. * @param {number} index The index where to add the child. */ addAt: function(child, index) { this.lastElementChild.insertBefore(child, this.items[index]); if (this.items.length == 1) this.hasChildren = true; child.setDepth_(this.depth + 1); }, /** * Removes a child. * @param {!cr.ui.TreeItem} child The tree item child to remove. */ remove: function(child) { // If we removed the selected item we should become selected. var tree = this.tree; var selectedItem = tree.selectedItem; if (selectedItem && child.contains(selectedItem)) this.selected = true; this.lastElementChild.removeChild(child); if (this.items.length == 0) this.hasChildren = false; }, /** * The parent tree item. * @type {!cr.ui.Tree|cr.ui.TreeItem} */ get parentItem() { var p = this.parentNode; while (p && !(p instanceof TreeItem) && !(p instanceof Tree)) { p = p.parentNode; } return p; }, /** * The tree that the tree item belongs to or null of no added to a tree. * @type {cr.ui.Tree} */ get tree() { var t = this.parentItem; while (t && !(t instanceof Tree)) { t = t.parentItem; } return t; }, /** * Whether the tree item is expanded or not. * @type {boolean} */ get expanded() { return this.hasAttribute('expanded'); }, set expanded(b) { if (this.expanded == b) return; var treeChildren = this.lastElementChild; if (b) { if (this.mayHaveChildren_) { this.setAttribute('expanded', ''); treeChildren.setAttribute('expanded', ''); cr.dispatchSimpleEvent(this, 'expand', true); this.scrollIntoViewIfNeeded(false); } } else { var tree = this.tree; if (tree && !this.selected) { var oldSelected = tree.selectedItem; if (oldSelected && this.contains(oldSelected)) this.selected = true; } this.removeAttribute('expanded'); treeChildren.removeAttribute('expanded'); cr.dispatchSimpleEvent(this, 'collapse', true); } }, /** * Expands all parent items. */ reveal: function() { var pi = this.parentItem; while (pi && !(pi instanceof Tree)) { pi.expanded = true; pi = pi.parentItem; } }, /** * The element representing the row that gets highlighted. * @type {!HTMLElement} */ get rowElement() { return this.firstElementChild; }, /** * The element containing the label text and the icon. * @type {!HTMLElement} */ get labelElement() { return this.firstElementChild.lastElementChild; }, /** * The label text. * @type {string} */ get label() { return this.labelElement.textContent; }, set label(s) { this.labelElement.textContent = s; }, /** * The URL for the icon. * @type {string} */ get icon() { return getComputedStyle(this.labelElement).backgroundImage.slice(4, -1); }, set icon(icon) { return this.labelElement.style.backgroundImage = url(icon); }, /** * Whether the tree item is selected or not. * @type {boolean} */ get selected() { return this.hasAttribute('selected'); }, set selected(b) { if (this.selected == b) return; var rowItem = this.firstElementChild; var tree = this.tree; if (b) { this.setAttribute('selected', ''); rowItem.setAttribute('selected', ''); this.reveal(); this.labelElement.scrollIntoViewIfNeeded(false); if (tree) tree.selectedItem = this; } else { this.removeAttribute('selected'); rowItem.removeAttribute('selected'); if (tree && tree.selectedItem == this) tree.selectedItem = null; } }, /** * Whether the tree item has children. * @type {boolean} */ get mayHaveChildren_() { return this.hasAttribute('may-have-children'); }, set mayHaveChildren_(b) { var rowItem = this.firstElementChild; if (b) { this.setAttribute('may-have-children', ''); rowItem.setAttribute('may-have-children', ''); } else { this.removeAttribute('may-have-children'); rowItem.removeAttribute('may-have-children'); } }, /** * Whether the tree item has children. * @type {boolean} */ get hasChildren() { return !!this.items[0]; }, /** * Whether the tree item has children. * @type {boolean} */ set hasChildren(b) { var rowItem = this.firstElementChild; this.setAttribute('has-children', b); rowItem.setAttribute('has-children', b); if (b) this.mayHaveChildren_ = true; }, /** * Called when the user clicks on a tree item. This is forwarded from the * cr.ui.Tree. * @param {Event} e The click event. */ handleClick: function(e) { if (e.target.className == 'expand-icon') this.expanded = !this.expanded; else this.selected = true; }, /** * Makes the tree item user editable. If the user renamed the item a * bubbling {@code rename} event is fired. * @type {boolean} */ set editing(editing) { var oldEditing = this.editing; if (editing == oldEditing) return; var self = this; var labelEl = this.labelElement; var text = this.label; var input; // Handles enter and escape which trigger reset and commit respectively. function handleKeydown(e) { // Make sure that the tree does not handle the key. e.stopPropagation(); // Calling tree.focus blurs the input which will make the tree item // non editable. switch (e.keyIdentifier) { case 'U+001B': // Esc input.value = text; // fall through case 'Enter': self.tree.focus(); } } function stopPropagation(e) { e.stopPropagation(); } if (editing) { this.selected = true; this.setAttribute('editing', ''); this.draggable = false; // We create an input[type=text] and copy over the label value. When // the input loses focus we set editing to false again. input = this.ownerDocument.createElement('input'); input.value = text; if (labelEl.firstChild) labelEl.replaceChild(input, labelEl.firstChild); else labelEl.appendChild(input); input.addEventListener('keydown', handleKeydown); input.addEventListener('blur', (function() { this.editing = false; }).bind(this)); // Make sure that double clicks do not expand and collapse the tree // item. var eventsToStop = ['mousedown', 'mouseup', 'contextmenu', 'dblclick']; eventsToStop.forEach(function(type) { input.addEventListener(type, stopPropagation); }); // Wait for the input element to recieve focus before sizing it. var rowElement = this.rowElement; function onFocus() { input.removeEventListener('focus', onFocus); // 20 = the padding and border of the tree-row cr.ui.limitInputWidth(input, rowElement, 100); } input.addEventListener('focus', onFocus); input.focus(); input.select(); this.oldLabel_ = text; } else { this.removeAttribute('editing'); this.draggable = true; input = labelEl.firstChild; var value = input.value; if (/^\s*$/.test(value)) { labelEl.textContent = this.oldLabel_; } else { labelEl.textContent = value; if (value != this.oldLabel_) { cr.dispatchSimpleEvent(this, 'rename', true); } } delete this.oldLabel_; } }, get editing() { return this.hasAttribute('editing'); } }; /** * Helper function that returns the next visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getNext(item) { if (item.expanded) { var firstChild = item.items[0]; if (firstChild) { return firstChild; } } return getNextHelper(item); } /** * Another helper function that returns the next visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getNextHelper(item) { if (!item) return null; var nextSibling = item.nextElementSibling; if (nextSibling) { return nextSibling; } return getNextHelper(item.parentItem); } /** * Helper function that returns the previous visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getPrevious(item) { var previousSibling = item.previousElementSibling; return previousSibling ? getLastHelper(previousSibling) : item.parentItem; } /** * Helper function that returns the last visible tree item in the subtree. * @param {cr.ui.TreeItem} item The item to find the last visible item for. * @return {cr.ui.TreeItem} The found item or null. */ function getLastHelper(item) { if (!item) return null; if (item.expanded && item.hasChildren) { var lastChild = item.items[item.items.length - 1]; return getLastHelper(lastChild); } return item; } // Export return { Tree: Tree, TreeItem: TreeItem }; });
aospx-kitkat/platform_external_chromium_org
ui/webui/resources/js/cr/ui/tree.js
JavaScript
bsd-3-clause
18,164
/** * @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); } })); }));
morsaken/webim-cms
views/backend/default/layouts/js/plugins/highcharts/modules/treemap.src.js
JavaScript
mit
24,507
/*! * 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; }));
dlueth/cdnjs
ajax/libs/inferno/0.7.14/inferno-router.js
JavaScript
mit
18,182
/** * 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')); });
SFDevLabs/react-starter-kit
tools/serve.js
JavaScript
mit
825
/* 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
GuilhouT/angular-gantt
dist/angular-gantt-resizeSensor-plugin.js
JavaScript
mit
2,694
/* 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
carlosgonzg/intermapa
public/libraries/angular-touch/angular-touch.min.js
JavaScript
mit
4,041
a enum;
Jazzling/jazzle-parser
test/test-esprima/fixtures/invalid-syntax/migrated_0115.js
JavaScript
mit
7
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 }; })();
pzp1997/cdnjs
ajax/libs/topojson/0.0.28/topojson.js
JavaScript
mit
8,261
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'); });
joannekoong/meteor
packages/github/package.js
JavaScript
mit
598
define( "dijit/form/nls/ca/validate", ({ invalidMessage: "El valor introduït no és vàlid", missingMessage: "Aquest valor és necessari", rangeMessage: "Aquest valor és fora de l'interval" }) );
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dijit/form/nls/ca/validate.js.uncompressed.js
JavaScript
apache-2.0
201
/*! 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)}}});
rteasdale/cdnjs
ajax/libs/interpolate.js/1.0.0/interpolate.min.js
JavaScript
mit
660
!function(a,b){function c(){function a(){"undefined"!=typeof _wpmejsSettings&&(c=b.extend(!0,{},_wpmejsSettings)),c.success=c.success||function(a){var b,c;"flash"===a.pluginType&&(b=a.attributes.autoplay&&"false"!==a.attributes.autoplay,c=a.attributes.loop&&"false"!==a.attributes.loop,b&&a.addEventListener("canplay",function(){a.play()},!1),c&&a.addEventListener("ended",function(){a.play()},!1))},b(".wp-audio-shortcode, .wp-video-shortcode").not(".mejs-container").filter(function(){return!b(this).parent().hasClass(".mejs-mediaelement")}).mediaelementplayer(c)}var c={};return{initialize:a}}a.wp=a.wp||{},mejs.plugins.silverlight[0].types.push("video/x-ms-wmv"),mejs.plugins.silverlight[0].types.push("audio/x-ms-wma"),a.wp.mediaelement=new c,b(a.wp.mediaelement.initialize)}(window,jQuery);
abbasarezoo/wp-starter-pack
www/wp-includes/js/mediaelement/wp-mediaelement.min.js
JavaScript
gpl-3.0
796
declare var a: number; var b: typeof a = "..."; var c: typeof a = "..."; type T = number; var x:T = "..."; // what about recursive unions?
kidaa/kythe
third_party/flow/tests/reflection/type.js
JavaScript
apache-2.0
141
/** * Italian translation for bootstrap-datepicker * Enrico Rubboli <[email protected]> */ ;(function($){ $.fn.datepicker.dates['it'] = { days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"], daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"], daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"], months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"], today: "Oggi", weekStart: 1, format: "dd/mm/yyyy" }; }(jQuery));
zxinStar/footshop
zxAdmin/assets/js/uncompressed/date-time/locales/bootstrap-datepicker.it.js
JavaScript
agpl-3.0
694
'use strict'; var $ = require('jquery'); require('./github-node-cfg.js'); var AddonHelper = require('js/addonHelper'); $(window.contextVars.githubSettingsSelector).on('submit', AddonHelper.onSubmitSettings);
ticklemepierce/osf.io
website/addons/github/static/node-cfg.js
JavaScript
apache-2.0
210
/*! * 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)); } }));
staticmatrix/Triangle
refer/modules/es5-shim/4.2.0/es5-shim.js
JavaScript
mit
61,950
// https://github.com/isaacs/sax-js/issues/124 require(__dirname).test ( { xml : "<!-- stand alone comment -->" , expect : [ [ "comment", " stand alone comment " ] ] , strict : true , opt : {} } )
apere/spark.blog
wp-content/themes/sheri-theme/node_modules/gulp-imagemin/node_modules/imagemin/node_modules/imagemin-svgo/node_modules/svgo/node_modules/sax/test/stand-alone-comment.js
JavaScript
gpl-2.0
225
/* 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;
savchukoleksii/beaversteward
www/settings/tools/mysql/js/openlayers/src/openlayers/lib/OpenLayers/Protocol.js
JavaScript
mit
8,407
(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'); } }) ; } }) ; }); });
ttitto/ttitto.github.io
js-webshim/dev/shims/track-ui.js
JavaScript
mit
10,440
//// [symbolDeclarationEmit8.ts] var obj = { [Symbol.isConcatSpreadable]: 0 } //// [symbolDeclarationEmit8.js] var obj = { [Symbol.isConcatSpreadable]: 0 }; //// [symbolDeclarationEmit8.d.ts] declare var obj: { [Symbol.isConcatSpreadable]: number; };
shanexu/TypeScript
tests/baselines/reference/symbolDeclarationEmit8.js
JavaScript
apache-2.0
279
/* 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)});
ChrisCioffi/ChrisCioffi.github.io
portfolio/Highcharts-5.0.13/code/themes/sunset.js
JavaScript
mit
438
/*! 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);
ristoman/lazysizes
plugins/print/ls.print.min.js
JavaScript
mit
487
/* HISTORY 02-Aug-10 L-05-28 $$1 pdeshmuk Created. */ function deleteItemsInSimpRep () { if (!pfcIsWindows()) netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); /*--------------------------------------------------------------------*\ Get the current assembly \*--------------------------------------------------------------------*/ var session = pfcGetProESession (); var assembly = session.CurrentModel; if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY) throw new Error (0, "Current model is not an assembly"); /*--------------------------------------------------------------------*\ Get the current active simprep. \*--------------------------------------------------------------------*/ var simp_rep = assembly.GetActiveSimpRep(); /*--------------------------------------------------------------------*\ Get the current number of items \*--------------------------------------------------------------------*/ var simp_rep_instructions = simp_rep.GetInstructions(); var number_items = simp_rep_instructions.Items.Count; document.getElementById("numItems").value = number_items; /*--------------------------------------------------------------------*\ Deleting items \*--------------------------------------------------------------------*/ var simp_rep_instructions_item = simp_rep_instructions.Items.Item(number_items-1); simp_rep_instructions_item.Action = null; simp_rep.SetInstructions(simp_rep_instructions); number_items = simp_rep.GetInstructions().Items.Count; document.getElementById("numItems").value = number_items; return; } function addItemsInSimpRep () { if (!pfcIsWindows()) netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); /*--------------------------------------------------------------------*\ Get the current assembly \*--------------------------------------------------------------------*/ var session = pfcGetProESession (); var assembly = session.CurrentModel; if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY) throw new Error (0, "Current model is not an assembly"); /*--------------------------------------------------------------------*\ Get the current active simprep. \*--------------------------------------------------------------------*/ var simp_rep = assembly.GetActiveSimpRep(); /*--------------------------------------------------------------------*\ Get the current number of items \*--------------------------------------------------------------------*/ var simp_rep_instructions = simp_rep.GetInstructions(); var number_items = simp_rep_instructions.Items.Count; document.getElementById("numItems").value = number_items; /*--------------------------------------------------------------------*\ Add an item \*--------------------------------------------------------------------*/ var item_path = pfcCreate ("intseq"); /*--------------------------------------------------------------------*\ Prompt for selection. \*--------------------------------------------------------------------*/ selOptions = pfcCreate ("pfcSelectionOptions").Create ("feature"); selOptions.MaxNumSels = parseInt (1); var selections = void null; try { selections = session.Select (selOptions, void null); } catch (err) { /*--------------------------------------------------------------------*\ Handle the situation where the user didn't make selections, but picked elsewhere instead. \*--------------------------------------------------------------------*/ if (pfcGetExceptionType (err) == "pfcXToolkitUserAbort" || pfcGetExceptionType (err) == "pfcXToolkitPickAbove") return (void null); else throw err; } if (selections.Count == 0) return (void null); var selection = selections.Item(0); var componentpath = selection.Path; var intseqIds = componentpath.ComponentIds; item_path.Append(intseqIds.Item(0)); simp_rep_comp_item_path = pfcCreate("pfcSimpRepCompItemPath").Create(item_path); simp_rep_item = pfcCreate("pfcSimpRepItem").Create(simp_rep_comp_item_path); simp_rep_action = pfcCreate("pfcSimpRepExclude").Create(); simp_rep_item.Action = simp_rep_action; simp_rep_instructions.Items.Append(simp_rep_item); simp_rep.SetInstructions(simp_rep_instructions); simp_rep_instructions = simp_rep.GetInstructions(); number_items = simp_rep_instructions.Items.Count; document.getElementById("numItems").value = number_items; return; }
2014c2g12/c2g12
wsgi/wsgi/static/weblink/examples/jscript/pfcSimpRepExamples.js
JavaScript
gpl-2.0
4,660
/** * 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(); } });
appcodechile/Rockola
webapp/touch/src/picker/Date.js
JavaScript
mit
12,879
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)); }
montanaflynn/phpjs
functions/math/acosh.js
JavaScript
mit
227
/* 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"]});
vousk/jsdelivr
files/yui/3.16.0/router/router.js
JavaScript
mit
59,499
/* 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." }); }
dinubalti/FirstSymfony
web/public/js/lib/ext-3.4.1/src/locale/ext-lang-sk.js
JavaScript
mit
5,418
var hat = require('../'); var assert = require('assert'); exports.rack = function () { var rack = hat.rack(4); var seen = {}; for (var i = 0; i < 8; i++) { var id = rack(); assert.ok(!seen[id], 'seen this id'); seen[id] = true; assert.ok(id.match(/^[0-9a-f]$/)); } assert.throws(function () { for (var i = 0; i < 10; i++) rack() }); }; exports.data = function () { var rack = hat.rack(64); var a = rack('a!'); var b = rack("it's a b!") var c = rack([ 'c', 'c', 'c' ]); assert.equal(rack.get(a), 'a!'); assert.equal(rack.get(b), "it's a b!"); assert.deepEqual(rack.get(c), [ 'c', 'c', 'c' ]); assert.equal(rack.hats[a], 'a!'); assert.equal(rack.hats[b], "it's a b!"); assert.deepEqual(rack.hats[c], [ 'c', 'c', 'c' ]); rack.set(a, 'AAA'); assert.equal(rack.get(a), 'AAA'); }; exports.expandBy = function () { var rack = hat.rack(4, 16, 4); var seen = {}; for (var i = 0; i < 8; i++) { var id = rack(); assert.ok(!seen[id], 'seen this id'); seen[id] = true; assert.ok(id.match(/^[0-9a-f]$/)); } for (var i = 0; i < 8; i++) { var id = rack(); assert.ok(!seen[id], 'seen this id'); seen[id] = true; assert.ok(id.match(/^[0-9a-f]{1,2}$/)); } for (var i = 0; i < 8; i++) { var id = rack(); assert.ok(!seen[id], 'seen this id'); seen[id] = true; assert.ok(id.match(/^[0-9a-f]{2}$/)); } };
hendrikusR/open-layer
widget/assets/draw/hat/test/rack.js
JavaScript
bsd-3-clause
1,569
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) }
hellokidder/js-studying
微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/node.js
JavaScript
mit
1,194
/* 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;
shikun2014010800/manga
web/console/node_modules/webpack/lib/IgnorePlugin.js
JavaScript
mit
1,617
/*! jQuery UI - v1.10.3 - 2013-06-12 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.he={closeText:"סגור",prevText:"&#x3C;הקודם",nextText:"הבא&#x3E;",currentText:"היום",monthNames:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],monthNamesShort:["ינו","פבר","מרץ","אפר","מאי","יוני","יולי","אוג","ספט","אוק","נוב","דצמ"],dayNames:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],dayNamesShort:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],dayNamesMin:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.he)});
jcdude/LamPI-1.8
www/jquery-ui-1.10.3.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-he.min.js
JavaScript
gpl-3.0
934
/*! * 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(); }; };
BrowenChen/classroomDashboard
zzishwebsite/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js
JavaScript
mit
1,440
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@");
BobbieBel/cdnjs
ajax/libs/yui/3.7.0pr1/datatype-date-format/lang/datatype-date-format_es-EC.js
JavaScript
mit
537
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "OD", "OT" ], "DAY": [ "Jumapil", "Wuok Tich", "Tich Ariyo", "Tich Adek", "Tich Ang\u2019wen", "Tich Abich", "Ngeso" ], "ERANAMES": [ "Kapok Kristo obiro", "Ka Kristo osebiro" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Dwe mar Achiel", "Dwe mar Ariyo", "Dwe mar Adek", "Dwe mar Ang\u2019wen", "Dwe mar Abich", "Dwe mar Auchiel", "Dwe mar Abiriyo", "Dwe mar Aboro", "Dwe mar Ochiko", "Dwe mar Apar", "Dwe mar gi achiel", "Dwe mar Apar gi ariyo" ], "SHORTDAY": [ "JMP", "WUT", "TAR", "TAD", "TAN", "TAB", "NGS" ], "SHORTMONTH": [ "DAC", "DAR", "DAD", "DAN", "DAH", "DAU", "DAO", "DAB", "DOC", "DAP", "DGI", "DAG" ], "STANDALONEMONTH": [ "Dwe mar Achiel", "Dwe mar Ariyo", "Dwe mar Adek", "Dwe mar Ang\u2019wen", "Dwe mar Abich", "Dwe mar Auchiel", "Dwe mar Abiriyo", "Dwe mar Aboro", "Dwe mar Ochiko", "Dwe mar Apar", "Dwe mar gi achiel", "Dwe mar Apar gi ariyo" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Ksh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "luo", "localeID": "luo", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
okboy5555/demo
基于angular的图书管理/src/framework/angular-1.5.8/i18n/angular-locale_luo.js
JavaScript
apache-2.0
2,946
/*! 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:"&#xAB; Luna precedentă",nextText:"Luna următoare &#xBB;",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)});
ninjablocks/ninja-sentinel
yeoman/components/jquery-ui/ui/minified/i18n/jquery.ui.datepicker-ro.min.js
JavaScript
mit
888
/** * @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>&nbsp;</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>&nbsp;</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">&nbsp;</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; });
siscia/jsdelivr
files/ink/3.0.0/js/ink.datepicker.js
JavaScript
mit
52,609
/** * @license AngularJS v1.3.16 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc... * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = function() { return new angular.mock.$Browser(); }; }; angular.mock.$Browser = function() { var self = this; this.isMock = true; self.$$url = "http://server/"; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = angular.noop; self.$$incOutstandingRequestCount = angular.noop; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$checkUrlChange = angular.noop; self.cookieHash = {}; self.lastCookieHash = {}; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay) { delay = delay || 0; self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); self.deferredFns.sort(function(a, b) { return a.time - b.time;}); return self.deferredNextId++; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var fnIndex; angular.forEach(self.deferredFns, function(fn, index) { if (fn.id === deferId) fnIndex = index; }); if (fnIndex !== undefined) { self.deferredFns.splice(fnIndex, 1); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { if (angular.isDefined(delay)) { self.defer.now += delay; } else { if (self.deferredFns.length) { self.defer.now = self.deferredFns[self.deferredFns.length - 1].time; } else { throw new Error('No deferred tasks to be flushed'); } } while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { self.deferredFns.shift().fn(); } }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, addPollFn: function(pollFn) { this.pollFns.push(pollFn); return pollFn; }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { this.$$url = url; // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; }, cookies: function(name, value) { if (name) { if (angular.isUndefined(value)) { delete this.cookieHash[name]; } else { if (angular.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { this.lastCookieHash = angular.copy(this.cookieHash); this.cookieHash = angular.copy(this.cookieHash); } return this.cookieHash; } }, notifyWhenNoOutstandingRequests: function(fn) { fn(); } }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()} * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. * For any implementations that expect exceptions to be thrown, the `rethrow` mode * will also maintain a log of thrown errors. */ this.mode = function(mode) { switch (mode) { case 'log': case 'rethrow': var errors = []; handler = function(e) { if (arguments.length == 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } if (mode === "rethrow") { throw e; } }; handler.errors = errors; break; default: throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " + "an expected log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$rootScope', '$q', '$$q', function($browser, $rootScope, $q, $$q) { var repeatFns = [], nextRepeatId = 0, now = 0; var $interval = function(fn, delay, count, invokeApply) { var iteration = 0, skipApply = (angular.isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = (angular.isDefined(count)) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = nextRepeatId; function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { var fnIndex; deferred.resolve(iteration); angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns.splice(fnIndex, 1); } } if (skipApply) { $browser.defer.flush(); } else { $rootScope.$apply(); } } repeatFns.push({ nextTime:(now + delay), delay: delay, fn: tick, id: nextRepeatId, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); nextRepeatId++; return promise; }; /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; var fnIndex; angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns[fnIndex].deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number=} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; /* jshint -W101 */ /* The R_ISO8061_STR regex is never going to fit into the 100 char limit! * This directive should go inside the anonymous function but a bug in JSHint means that it would * not be enacted early enough to prevent the warning. */ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8061_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4] || 0) - tzHour, int(match[5] || 0) - tzMin, int(match[6] || 0), int(match[7] || 0)); return date; } return string; } function int(str) { return parseInt(str, 10); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) throw { name: "Illegal Argument", message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" }; } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumber(self.origDate.getUTCDate(), 2) + 'T' + padNumber(self.origDate.getUTCHours(), 2) + ':' + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /* jshint +W101 */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .config(['$provide', function($provide) { var reflowQueue = []; $provide.value('$$animateReflow', function(fn) { var index = reflowQueue.length; reflowQueue.push(fn); return function cancel() { reflowQueue.splice(index, 1); }; }); $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser', function($delegate, $$asyncCallback, $timeout, $browser) { var animate = { queue: [], cancel: $delegate.cancel, enabled: $delegate.enabled, triggerCallbackEvents: function() { $$asyncCallback.flush(); }, triggerCallbackPromise: function() { $timeout.flush(0); }, triggerCallbacks: function() { this.triggerCallbackEvents(); this.triggerCallbackPromise(); }, triggerReflow: function() { angular.forEach(reflowQueue, function(fn) { fn(); }); reflowQueue = []; } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: this is not an injectable instance, just a globally available function. * * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for * debugging. * * This method is also available on window, where it can be used to display objects on debug * console. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an Angular application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * # Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * # Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * # Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').success(function(data, status, headers) { authToken = headers('A-Token'); $scope.user = data; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) { $scope.status = ''; }).error(function() { $scope.status = 'ERROR!'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was send, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] == 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` */ angular.mock.$HttpBackendProvider = function() { this.$get = ['$rootScope', '$timeout', createHttpBackendMock]; }; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { var definitions = [], expectations = [], responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText] : [200, status, data, headers]; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout) { timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout); } return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || '')); } function handleTimeout() { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, ''); break; } } } } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); if (!expectation.matchHeaders(headers)) throw new Error('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = -1, definition; while ((definition = definitions[++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { $delegate(method, url, data, callback, headers, timeout, withCredentials); } else throw new Error('No response defined !'); return; } } throw wasExpected ? new Error('No response defined !') : new Error('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.when = function(method, url, data, headers) { var definition = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { definition.passThrough = undefined; definition.response = createResponse(status, data, headers, statusText); return chain; } }; if ($browser) { chain.passThrough = function() { definition.response = undefined; definition.passThrough = true; return chain; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.expect = function(method, url, data, headers) { var expectation = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { expectation.response = createResponse(status, data, headers, statusText); return chain; } }; expectations.push(expectation); return chain; }; /** * @ngdoc method * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ /** * @ngdoc method * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name $httpBackend#flush * @description * Flushes all pending requests using the trained responses. * * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, * all pending requests will be flushed. If there are no pending requests when the flush method * is called an exception is thrown (as this typically a sign of programming error). */ $httpBackend.flush = function(count, digest) { if (digest !== false) $rootScope.$digest(); if (!responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count) && count !== null) { while (count--) { if (!responses.length) throw new Error('No more pending request to flush !'); responses.shift()(); } } else { while (responses.length) { responses.shift()(); } } $httpBackend.verifyNoOutstandingExpectation(digest); }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingExpectation); * ``` */ $httpBackend.verifyNoOutstandingExpectation = function(digest) { if (digest !== false) $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingRequest); * ``` */ $httpBackend.verifyNoOutstandingRequest = function() { if (responses.length) { throw new Error('Unflushed requests: ' + responses.length); } }; /** * @ngdoc method * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { $httpBackend[prefix + method] = function(url, headers) { return $httpBackend[prefix](method, url, undefined, headers); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers) { return $httpBackend[prefix](method, url, data, headers); }; }); } } function MockHttpExpectation(method, url, data, headers) { this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method != m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); if (angular.isFunction(url)) return url(u); return url == u; }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) { return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); } return data == d; }; this.toString = function() { return method + ' ' + url; }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.lowercase(headerName) == name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = angular.noop; } /** * @ngdoc service * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { /** * @ngdoc method * @name $timeout#flush * @description * * Flushes the queue of pending tasks. * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { $browser.defer.flush(delay); }; /** * @ngdoc method * @name $timeout#verifyNoPendingTasks * @description * * Verifies that there are no pending tasks that need to be flushed. */ $delegate.verifyNoPendingTasks = function() { if ($browser.deferredFns.length) { throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + formatPendingTasksAsString($browser.deferredFns)); } }; function formatPendingTasksAsString(tasks) { var result = []; angular.forEach(tasks, function(task) { result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); }); return result.join(', '); } return $delegate; }]; angular.mock.$RAFDecorator = ['$delegate', function($delegate) { var queue = []; var rafFn = function(fn) { var index = queue.length; queue.push(fn); return function() { queue.splice(index, 1); }; }; rafFn.supported = $delegate.supported; rafFn.flush = function() { if (queue.length === 0) { throw new Error('No rAF callbacks present'); } var length = queue.length; for (var i = 0; i < length; i++) { queue[i](); } queue = []; }; return rafFn; }]; angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) { var callbacks = []; var addFn = function(fn) { callbacks.push(fn); }; addFn.flush = function() { angular.forEach(callbacks, function(fn) { fn(); }); callbacks = []; }; return addFn; }]; /** * */ angular.mock.$RootElementProvider = function() { this.$get = function() { return angular.element('<div ng-app></div>'); }; }; /** * @ngdoc service * @name $controller * @description * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. * * * ## Example * * ```js * * // Directive definition ... * * myMod.directive('myDirective', { * controller: 'MyDirectiveController', * bindToController: { * name: '@' * } * }); * * * // Controller definition ... * * myMod.controller('MyDirectiveController', ['log', function($log) { * $log.info(this.name); * })]; * * * // In a test ... * * describe('myDirectiveController', function() { * it('should write the bound name to the log', inject(function($controller, $log) { * var ctrl = $controller('MyDirective', { /* no locals &#42;/ }, { name: 'Clark Kent' }); * expect(ctrl.name).toEqual('Clark Kent'); * expect($log.info.logs).toEqual(['Clark Kent']); * }); * }); * * ``` * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global * `window` object (not recommended) * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used * to simulate the `bindToController` feature and simplify certain kinds of tests. * @return {Object} Instance of given controller. */ angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { return function(expression, locals, later, ident) { if (later && typeof later === 'object') { var create = $delegate(expression, locals, true, ident); angular.extend(create.instance, later); return create(); } return $delegate(expression, locals, later, ident); }; }]; /** * @ngdoc module * @name ngMock * @packageName angular-mocks * @description * * # ngMock * * The `ngMock` module provides support to inject and mock Angular services into unit tests. * In addition, ngMock also extends various core ng services such that they can be * inspected and controlled in a synchronous manner within test code. * * * <div doc-module-components="ngMock"></div> * */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $httpBackend: angular.mock.$HttpBackendProvider, $rootElement: angular.mock.$RootElementProvider }).config(['$provide', function($provide) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); $provide.decorator('$$rAF', angular.mock.$RAFDecorator); $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); $provide.decorator('$controller', angular.mock.$ControllerDecorator); }]); /** * @ngdoc module * @name ngMockE2E * @module ngMockE2E * @packageName angular-mocks * @description * * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]); /** * @ngdoc service * @name $httpBackend * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * *Note*: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * ```js * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); * //... * }); * ``` * * Afterwards, bootstrap your app with this new module. */ /** * @ngdoc method * @name $httpBackend#when * @module ngMockE2E * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string), response headers * (Object), and the text for the status (string). * - passThrough – `{function()}` – Any request matching a backend definition with * `passThrough` handler will be passed through to the real backend (an XHR request will be made * to the server.) * - Both methods return the `requestHandler` object for possible overrides. */ /** * @ngdoc method * @name $httpBackend#whenGET * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPATCH * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; /** * @ngdoc type * @name $rootScope.Scope * @module ngMock * @description * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when * `ngMock` module is loaded. * * In addition to all the regular `Scope` methods, the following helper methods are available: */ angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { var $rootScopePrototype = Object.getPrototypeOf($delegate); $rootScopePrototype.$countChildScopes = countChildScopes; $rootScopePrototype.$countWatchers = countWatchers; return $delegate; // ------------------------------------------------------------------------------------------ // /** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes() { // jshint validthis: true var count = 0; // exclude the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } /** * @ngdoc method * @name $rootScope.Scope#$countWatchers * @module ngMock * @description * Counts all the watchers of direct and indirect child scopes of the current scope. * * The watchers of the current scope are included in the count and so are all the watchers of * isolate child scopes. * * @returns {number} Total number of watchers. */ function countWatchers() { // jshint validthis: true var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } }]; if (window.jasmine || window.mocha) { var currentSpec = null, annotatedFunctions = [], isSpecRunning = function() { return !!currentSpec; }; angular.mock.$$annotate = angular.injector.$$annotate; angular.injector.$$annotate = function(fn) { if (typeof fn === 'function' && !fn.$inject) { annotatedFunctions.push(fn); } return angular.mock.$$annotate.apply(this, arguments); }; (window.beforeEach || window.setup)(function() { annotatedFunctions = []; currentSpec = this; }); (window.afterEach || window.teardown)(function() { var injector = currentSpec.$injector; annotatedFunctions.forEach(function(fn) { delete fn.$inject; }); angular.forEach(currentSpec.$modules, function(module) { if (module && module.$$hashKey) { module.$$hashKey = undefined; } }); currentSpec.$injector = null; currentSpec.$modules = null; currentSpec = null; if (injector) { injector.get('$rootElement').off(); injector.get('$browser').pollFns.length = 0; } // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.counter = 0; }); /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed they will be registered as values in the module, the key being * the module name and the value being what is returned. */ window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return isSpecRunning() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { modules.push(function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }); } else { modules.push(module); } }); } } }; /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as _myService_, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * ```js * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); return isSpecRunning() ? workFn.call(currentSpec) : workFn; ///////////////////// function workFn() { var modules = currentSpec.$modules || []; var strictDi = !!currentSpec.$injectorStrict; modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { if (strictDi) { // If strictDi is enabled, annotate the providerInjector blocks angular.forEach(modules, function(moduleFn) { if (typeof moduleFn === "function") { angular.injector.$$annotate(moduleFn); } }); } injector = currentSpec.$injector = angular.injector(modules, strictDi); currentSpec.$injectorStrict = strictDi; } for (var i = 0, ii = blockFns.length; i < ii; i++) { if (currentSpec.$injectorStrict) { // If the injector is strict / strictDi, and the spec wants to inject using automatic // annotation, then annotate the function here. injector.annotate(blockFns[i]); } try { /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ injector.invoke(blockFns[i] || angular.noop, this); /* jshint +W040 */ } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; angular.mock.inject.strictDi = function(value) { value = arguments.length ? !!value : true; return isSpecRunning() ? workFn() : workFn; function workFn() { if (value !== currentSpec.$injectorStrict) { if (currentSpec.$injector) { throw new Error('Injector already created, can not modify strict annotations'); } else { currentSpec.$injectorStrict = value; } } } }; } })(window, window.angular);
DreamInSun/OneRing
xdiamond/bower_components/angular-mocks/angular-mocks.js
JavaScript
apache-2.0
82,636
let arr = []; for(let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) { arr.push(() => i); } }
ellbee/babel
test/core/fixtures/transformation/es6.block-scoping/issue-973/actual.js
JavaScript
mit
106
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.3 (11-JUL-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.3'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { /*global console */ if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animInDelay: 0, // allows delay before next slide transitions in animOut: null, // properties that define how the slide animates out animOutDelay: 0, // allows delay before current slide transitions out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
delfintrinidadIV/firstproject
wp-content/themes/simple-catch/js/jquery.cycle.all.js
JavaScript
gpl-2.0
52,026
/** * 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;
tspires/personal
zillow/node_modules/xml2js/node_modules/xmlbuilder/node_modules/lodash-node/modern/internals/baseUniq.js
JavaScript
mit
2,014
jQuery.extend(jQuery.fn.pickadate.defaults,{monthsFull:["janúar","febrúar","mars","apríl","maí","júní","júlí","ágúst","september","október","nóvember","desember"],monthsShort:["jan","feb","mar","apr","maí","jún","júl","ágú","sep","okt","nóv","des"],weekdaysFull:["sunnudagur","mánudagur","þriðjudagur","miðvikudagur","fimmtudagur","föstudagur","laugardagur"],weekdaysShort:["sun","mán","þri","mið","fim","fös","lau"],today:"Í dag",clear:"Hreinsa",firstDay:1,format:"dd. mmmm yyyy",formatSubmit:"yyyy/mm/dd"}),jQuery.extend(jQuery.fn.pickatime.defaults,{clear:"Hreinsa"});
enketosurvey/mo
www/lib/pickadate.js-3.5.6/lib/compressed/translations/is_IS.js
JavaScript
apache-2.0
599
var browser_history_support = (window.history != null ? window.history.pushState : null) != null; createTest('Nested route with the many children as a tokens, callbacks should yield historic params', { '/a': { '/:id': { '/:id': function(a, b) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), a, b); } else { shared.fired.push(location.pathname, a, b); } } } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['/a/b/c', 'b', 'c']); this.finish(); }); }); createTest('Nested route with the first child as a token, callback should yield a param', { '/foo': { '/:id': { on: function(id) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), id); } else { shared.fired.push(location.pathname, id); } } } } }, function() { this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the first child as a regexp, callback should yield a param', { '/foo': { '/(\\w+)': { on: function(value) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), value); } else { shared.fired.push(location.pathname, value); } } } } }, function() { this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the several regular expressions, callback should yield a param', { '/a': { '/(\\w+)': { '/(\\w+)': function(a, b) { shared.fired.push(a, b); } } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['b', 'c']); this.finish(); }); }); createTest('Single nested route with on member containing function value', { '/a': { '/b': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b']); this.finish(); }); }); createTest('Single non-nested route with on member containing function value', { '/a/b': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b']); this.finish(); }); }); createTest('Single nested route with on member containing array of function values', { '/a': { '/b': { on: [function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }, function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }] } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b', '/a/b']); this.finish(); }); }); createTest('method should only fire once on the route.', { '/a': { '/b': { once: function() { shared.fired_count++; } } } }, function() { this.navigate('/a/b', function() { this.navigate('/a/b', function() { this.navigate('/a/b', function() { deepEqual(shared.fired_count, 1); this.finish(); }); }); }); }); createTest('method should only fire once on the route, multiple nesting.', { '/a': { on: function() { shared.fired_count++; }, once: function() { shared.fired_count++; } }, '/b': { on: function() { shared.fired_count++; }, once: function() { shared.fired_count++; } } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired_count, 6); this.finish(); }); }); }); }); }); createTest('overlapping routes with tokens.', { '/a/:b/c' : function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }, '/a/:b/c/:d' : function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } }, function() { this.navigate('/a/b/c', function() { this.navigate('/a/b/c/d', function() { deepEqual(shared.fired, ['/a/b/c', '/a/b/c/d']); this.finish(); }); }); }); // // // // // // Recursion features // // // ---------------------------------------------------------- createTest('Nested routes with no recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c']); this.finish(); }); }); createTest('Nested routes with backward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b', 'a']); this.finish(); }); }); createTest('Breaking out of nested routes with backward recursion', { '/a': { '/:b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b']); this.finish(); }); }); createTest('Nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b', 'c']); this.finish(); }); }); createTest('Nested routes with forward recursion, single route with an after event.', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); }, after: function() { shared.fired.push('c-after'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['a', 'b', 'c', 'c-after', 'a', 'b']); this.finish(); }); }); }); createTest('Breaking out of nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b']); this.finish(); }); }); // // ABOVE IS WORKING // // // // // Special Events // // ---------------------------------------------------------- createTest('All global event should fire after every route', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { '/c': { on: function a() { shared.fired.push('a'); } } }, '/d': { '/:e': { on: function a() { shared.fired.push('a'); } } } }, { after: function() { shared.fired.push('b'); } }, function() { this.navigate('/a', function() { this.navigate('/b/c', function() { this.navigate('/d/e', function() { deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a']); this.finish(); }); }); }); }); createTest('Not found.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { notfound: function() { shared.fired.push('notfound'); } }, function() { this.navigate('/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['notfound', 'notfound']); this.finish(); }); }); }); createTest('On all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { on: function() { shared.fired.push('c'); } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b', 'c']); this.finish(); }); }); }); createTest('After all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { after: function() { shared.fired.push('c'); } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b']); this.finish(); }); }); }); createTest('resource object.', { '/a': { '/b/:c': { on: 'f1' }, on: 'f2' }, '/d': { on: ['f1', 'f2'] } }, { resource: { f1: function (name){ shared.fired.push("f1-" + name); }, f2: function (name){ shared.fired.push("f2"); } } }, function() { this.navigate('/a/b/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']); this.finish(); }); }); }); createTest('argument matching should be case agnostic', { '/fooBar/:name': { on: function(name) { shared.fired.push("fooBar-" + name); } } }, function() { this.navigate('/fooBar/tesTing', function() { deepEqual(shared.fired, ['fooBar-tesTing']); this.finish(); }); }); createTest('sanity test', { '/is/:this/:sane': { on: function(a, b) { shared.fired.push('yes ' + a + ' is ' + b); } }, '/': { on: function() { shared.fired.push('is there sanity?'); } } }, function() { this.navigate('/is/there/sanity', function() { deepEqual(shared.fired, ['yes there is sanity']); this.finish(); }); }); createTest('`/` route should be navigable from the routing table', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { this.navigate('/', function root() { deepEqual(shared.fired, ['/']); this.finish(); }); }); createTest('`/` route should not override a `/:token` route', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { this.navigate('/a', function afunc() { deepEqual(shared.fired, ['/a']); this.finish(); }); }); createTest('should accept the root as a token.', { '/:a': { on: function root() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a', function root() { deepEqual(shared.fired, ['/a']); this.finish(); }); }); createTest('routes should allow wildcards.', { '/:a/b*d': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a/bcd', function root() { deepEqual(shared.fired, ['/a/bcd']); this.finish(); }); }); createTest('functions should have |this| context of the router instance.', { '/': { on: function root() { shared.fired.push(!!this.routes); } } }, function() { this.navigate('/', function root() { deepEqual(shared.fired, [true]); this.finish(); }); }); createTest('setRoute with a single parameter should change location correctly', { '/bonk': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(window.location.pathname); } } } }, function() { var self = this; this.router.setRoute('/bonk'); setTimeout(function() { deepEqual(shared.fired, ['/bonk']); self.finish(); }, 14) }); createTest('route should accept _ and . within parameters', { '/:a': { on: function root() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a_complex_route.co.uk', function root() { deepEqual(shared.fired, ['/a_complex_route.co.uk']); this.finish(); }); });
WAPMADRID/server
wapmadrid/node_modules/forever/node_modules/flatiron/node_modules/director/test/browser/html5-routes-test.js
JavaScript
gpl-2.0
14,089