code stringlengths 2 1.05M |
|---|
// Generated by CoffeeScript 1.3.3
(function() {
var ACCESSOR, CoffeeScript, Module, REPL_PROMPT, REPL_PROMPT_CONTINUATION, REPL_PROMPT_MULTILINE, SIMPLEVAR, Script, autocomplete, backlog, completeAttribute, completeVariable, enableColours, error, getCompletions, inspect, multilineMode, pipedInput, readline, repl, run, stdin, stdout,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
stdin = process.openStdin();
stdout = process.stdout;
CoffeeScript = require('./coffee-script');
readline = require('readline');
inspect = require('util').inspect;
Script = require('vm').Script;
Module = require('module');
REPL_PROMPT = 'coffee> ';
REPL_PROMPT_MULTILINE = '------> ';
REPL_PROMPT_CONTINUATION = '......> ';
enableColours = false;
if (process.platform !== 'win32') {
enableColours = !process.env.NODE_DISABLE_COLORS;
}
error = function(err) {
return stdout.write((err.stack || err.toString()) + '\n');
};
ACCESSOR = /\s*([\w\.]+)(?:\.(\w*))$/;
SIMPLEVAR = /(\w+)$/i;
autocomplete = function(text) {
return completeAttribute(text) || completeVariable(text) || [[], text];
};
completeAttribute = function(text) {
var all, candidates, completions, key, match, obj, prefix, _i, _len, _ref;
if (match = text.match(ACCESSOR)) {
all = match[0], obj = match[1], prefix = match[2];
try {
obj = Script.runInThisContext(obj);
} catch (e) {
return;
}
if (obj == null) {
return;
}
obj = Object(obj);
candidates = Object.getOwnPropertyNames(obj);
while (obj = Object.getPrototypeOf(obj)) {
_ref = Object.getOwnPropertyNames(obj);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
if (__indexOf.call(candidates, key) < 0) {
candidates.push(key);
}
}
}
completions = getCompletions(prefix, candidates);
return [completions, prefix];
}
};
completeVariable = function(text) {
var candidates, completions, free, key, keywords, r, vars, _i, _len, _ref;
free = (_ref = text.match(SIMPLEVAR)) != null ? _ref[1] : void 0;
if (text === "") {
free = "";
}
if (free != null) {
vars = Script.runInThisContext('Object.getOwnPropertyNames(Object(this))');
keywords = (function() {
var _i, _len, _ref1, _results;
_ref1 = CoffeeScript.RESERVED;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
r = _ref1[_i];
if (r.slice(0, 2) !== '__') {
_results.push(r);
}
}
return _results;
})();
candidates = vars;
for (_i = 0, _len = keywords.length; _i < _len; _i++) {
key = keywords[_i];
if (__indexOf.call(candidates, key) < 0) {
candidates.push(key);
}
}
completions = getCompletions(free, candidates);
return [completions, free];
}
};
getCompletions = function(prefix, candidates) {
var el, _i, _len, _results;
_results = [];
for (_i = 0, _len = candidates.length; _i < _len; _i++) {
el = candidates[_i];
if (0 === el.indexOf(prefix)) {
_results.push(el);
}
}
return _results;
};
process.on('uncaughtException', error);
backlog = '';
run = function(buffer) {
var code, returnValue, _;
buffer = buffer.replace(/(^|[\r\n]+)(\s*)##?(?:[^#\r\n][^\r\n]*|)($|[\r\n])/, "$1$2$3");
buffer = buffer.replace(/[\r\n]+$/, "");
if (multilineMode) {
backlog += "" + buffer + "\n";
repl.setPrompt(REPL_PROMPT_CONTINUATION);
repl.prompt();
return;
}
if (!buffer.toString().trim() && !backlog) {
repl.prompt();
return;
}
code = backlog += buffer;
if (code[code.length - 1] === '\\') {
backlog = "" + backlog.slice(0, -1) + "\n";
repl.setPrompt(REPL_PROMPT_CONTINUATION);
repl.prompt();
return;
}
repl.setPrompt(REPL_PROMPT);
backlog = '';
try {
_ = global._;
returnValue = CoffeeScript["eval"]("_=(" + code + "\n)", {
filename: 'repl',
modulename: 'repl'
});
if (returnValue === void 0) {
global._ = _;
}
repl.output.write("" + (inspect(returnValue, false, 2, enableColours)) + "\n");
} catch (err) {
error(err);
}
return repl.prompt();
};
if (stdin.readable && stdin.isRaw) {
pipedInput = '';
repl = {
prompt: function() {
return stdout.write(this._prompt);
},
setPrompt: function(p) {
return this._prompt = p;
},
input: stdin,
output: stdout,
on: function() {}
};
stdin.on('data', function(chunk) {
var line, lines, _i, _len, _ref;
pipedInput += chunk;
if (!/\n/.test(pipedInput)) {
return;
}
lines = pipedInput.split("\n");
pipedInput = lines[lines.length - 1];
_ref = lines.slice(0, -1);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (!(line)) {
continue;
}
stdout.write("" + line + "\n");
run(line);
}
});
stdin.on('end', function() {
var line, _i, _len, _ref;
_ref = pipedInput.trim().split("\n");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (!(line)) {
continue;
}
stdout.write("" + line + "\n");
run(line);
}
stdout.write('\n');
return process.exit(0);
});
} else {
if (readline.createInterface.length < 3) {
repl = readline.createInterface(stdin, autocomplete);
stdin.on('data', function(buffer) {
return repl.write(buffer);
});
} else {
repl = readline.createInterface(stdin, stdout, autocomplete);
}
}
multilineMode = false;
repl.input.on('keypress', function(char, key) {
var cursorPos, newPrompt;
if (!(key && key.ctrl && !key.meta && !key.shift && key.name === 'v')) {
return;
}
cursorPos = repl.cursor;
repl.output.cursorTo(0);
repl.output.clearLine(1);
multilineMode = !multilineMode;
if (!multilineMode && backlog) {
repl._line();
}
backlog = '';
repl.setPrompt((newPrompt = multilineMode ? REPL_PROMPT_MULTILINE : REPL_PROMPT));
repl.prompt();
return repl.output.cursorTo(newPrompt.length + (repl.cursor = cursorPos));
});
repl.input.on('keypress', function(char, key) {
if (!(multilineMode && repl.line)) {
return;
}
if (!(key && key.ctrl && !key.meta && !key.shift && key.name === 'd')) {
return;
}
multilineMode = false;
return repl._line();
});
repl.on('attemptClose', function() {
if (multilineMode) {
multilineMode = false;
repl.output.cursorTo(0);
repl.output.clearLine(1);
repl._onLine(repl.line);
return;
}
if (backlog || repl.line) {
backlog = '';
repl.historyIndex = -1;
repl.setPrompt(REPL_PROMPT);
repl.output.write('\n(^C again to quit)');
return repl._line((repl.line = ''));
} else {
return repl.close();
}
});
repl.on('close', function() {
repl.output.write('\n');
return repl.input.destroy();
});
repl.on('line', run);
repl.setPrompt(REPL_PROMPT);
repl.prompt();
}).call(this);
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'undo', 'ar', {
redo: 'إعادة',
undo: 'تراجع'
});
|
'use strict';
var angularFiles = require('./angularFiles');
var sharedConfig = require('./karma-shared.conf');
module.exports = function(config) {
sharedConfig(config, {testName: 'AngularJS: isolated module tests (ngMock)', logFile: 'karma-ngMock-isolated.log'});
config.set({
files: angularFiles.mergeFilesFor('karmaModules-ngMock')
});
};
|
// try {
exports.BSONPure = require('./bson');
// exports.BSONNative = require('../../ext');
// } catch(err) {
// // do nothing
// }
[ './binary_parser'
, './binary'
, './code'
, './db_ref'
, './double'
, './max_key'
, './min_key'
, './objectid'
, './symbol'
, './timestamp'
, './long'].forEach(function (path) {
var module = require('./' + path);
for (var i in module) {
exports[i] = module[i];
}
});
// // Exports all the classes for the NATIVE JS BSON Parser
// exports.native = function() {
// var classes = {};
// // Map all the classes
// [ './binary_parser'
// , './binary'
// , './code'
// , './db_ref'
// , './double'
// , './max_key'
// , './min_key'
// , './objectid'
// , './symbol'
// , './timestamp'
// , './long'
// , '../../ext'
// ].forEach(function (path) {
// var module = require('./' + path);
// for (var i in module) {
// classes[i] = module[i];
// }
// });
// // Return classes list
// return classes;
// }
// Exports all the classes for the PURE JS BSON Parser
exports.pure = function() {
var classes = {};
// Map all the classes
[ './binary_parser'
, './binary'
, './code'
, './db_ref'
, './double'
, './max_key'
, './min_key'
, './objectid'
, './symbol'
, './timestamp'
, './long'
, '././bson'].forEach(function (path) {
var module = require('./' + path);
for (var i in module) {
classes[i] = module[i];
}
});
// Return classes list
return classes;
}
|
define({
"numPerPage": "Broj stavaka po stranici",
"scopeOptions": {
"defaultScope": "Zadani opseg pretraživanja",
"labelPlaceholder": "Neobavezna oznaka",
"MyContent": "Omogući Moj sadržaj",
"MyOrganization": "Omogući Moju organizaciju",
"ArcGISOnline": "Omogući ArcGIS Online",
"Curated": "Omogući nadzirano",
"CuratedFilter": "Nadzirani filtar",
"livingAtlasExample": "Primjer za Living atlas:"
},
"addFromUrl": {
"caption": "Omogući URL"
},
"addFromFile": {
"caption": "Omogući datoteku",
"maxRecordCount": "Maksimalno zapisa po datoteci"
},
"_default": "Zadano",
"makeDefault": "Postavi zadano"
}); |
/*!
* CanJS - 1.1.5 (2013-03-27)
* http://canjs.us/
* Copyright (c) 2013 Bitovi
* Licensed MIT
*/
define(function () {
var can = window.can || {};
if (typeof GLOBALCAN === 'undefined' || GLOBALCAN !== false) {
window.can = can;
}
can.isDeferred = function (obj) {
var isFunction = this.isFunction;
// Returns `true` if something looks like a deferred.
return obj && isFunction(obj.then) && isFunction(obj.pipe);
};
var cid = 0;
can.cid = function (object, name) {
if (object._cid) {
return object._cid
} else {
return object._cid = (name || "") + (++cid)
}
}
return can;
}); |
/*!
* toc - jQuery Table of Contents Plugin
* v0.3.2
* http://projects.jga.me/toc/
* copyright Greg Allen 2014
* MIT License
*/
/*!
* smooth-scroller - Javascript lib to handle smooth scrolling
* v0.1.2
* https://github.com/firstandthird/smooth-scroller
* copyright First+Third 2014
* MIT License
*/
//smooth-scroller.js
(function($) {
$.fn.smoothScroller = function(options) {
options = $.extend({}, $.fn.smoothScroller.defaults, options);
var el = $(this);
$(options.scrollEl).animate({
scrollTop: el.offset().top - $(options.scrollEl).offset().top - options.offset
}, options.speed, options.ease, function() {
var hash = el.attr('id');
if(hash.length) {
if(history.pushState) {
history.pushState(null, null, '#' + hash);
} else {
document.location.hash = hash;
}
}
el.trigger('smoothScrollerComplete');
});
return this;
};
$.fn.smoothScroller.defaults = {
speed: 400,
ease: 'swing',
scrollEl: 'body,html',
offset: 0
};
$('body').on('click', '[data-smoothscroller]', function(e) {
e.preventDefault();
var href = $(this).attr('href');
if(href.indexOf('#') === 0) {
$(href).smoothScroller();
}
});
}(jQuery));
(function($) {
var verboseIdCache = {};
$.fn.toc = function(options) {
var self = this;
var opts = $.extend({}, jQuery.fn.toc.defaults, options);
var container = $(opts.container);
var headings = $(opts.selectors, container);
var headingOffsets = [];
var activeClassName = opts.activeClass;
var scrollTo = function(e, callback) {
if (opts.smoothScrolling && typeof opts.smoothScrolling === 'function') {
e.preventDefault();
var elScrollTo = $(e.target).attr('href');
opts.smoothScrolling(elScrollTo, opts, callback);
}
$('li', self).removeClass(activeClassName);
$(e.target).parent().addClass(activeClassName);
};
//highlight on scroll
var timeout;
var highlightOnScroll = function(e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
var top = $(window).scrollTop(),
highlighted, closest = Number.MAX_VALUE, index = 0;
for (var i = 0, c = headingOffsets.length; i < c; i++) {
var currentClosest = Math.abs(headingOffsets[i] - top);
if (currentClosest < closest) {
index = i;
closest = currentClosest;
}
}
$('li', self).removeClass(activeClassName);
highlighted = $('li:eq('+ index +')', self).addClass(activeClassName);
opts.onHighlight(highlighted);
}, 50);
};
if (opts.highlightOnScroll) {
$(window).bind('scroll', highlightOnScroll);
highlightOnScroll();
}
return this.each(function() {
//build TOC
var el = $(this);
var ul = $(opts.listType);
headings.each(function(i, heading) {
var $h = $(heading);
headingOffsets.push($h.offset().top - opts.highlightOffset);
var anchorName = opts.anchorName(i, heading, opts.prefix);
//add anchor
if(heading.id !== anchorName) {
var anchor = $('<span/>').attr('id', anchorName).insertBefore($h);
}
//build TOC item
var a = $('<a/>')
.text(opts.headerText(i, heading, $h))
.attr('href', '#' + anchorName)
.bind('click', function(e) {
$(window).unbind('scroll', highlightOnScroll);
scrollTo(e, function() {
$(window).bind('scroll', highlightOnScroll);
});
el.trigger('selected', $(this).attr('href'));
});
var li = $('<li/>')
.addClass(opts.itemClass(i, heading, $h, opts.prefix))
.append(a);
ul.append(li);
});
el.html(ul);
});
};
jQuery.fn.toc.defaults = {
container: 'body',
listType: '<ul/>',
selectors: 'h1,h2,h3',
smoothScrolling: function(target, options, callback) {
$(target).smoothScroller({
offset: options.scrollToOffset
}).on('smoothScrollerComplete', function() {
callback();
});
},
scrollToOffset: 0,
prefix: 'toc',
activeClass: 'toc-active',
onHighlight: function() {},
highlightOnScroll: true,
highlightOffset: 100,
anchorName: function(i, heading, prefix) {
if(heading.id.length) {
return heading.id;
}
var candidateId = $(heading).text().replace(/[^a-z0-9]/ig, ' ').replace(/\s+/g, '-').toLowerCase();
if (verboseIdCache[candidateId]) {
var j = 2;
while(verboseIdCache[candidateId + j]) {
j++;
}
candidateId = candidateId + '-' + j;
}
verboseIdCache[candidateId] = true;
return prefix + '-' + candidateId;
},
headerText: function(i, heading, $heading) {
return $heading.text();
},
itemClass: function(i, heading, $heading, prefix) {
return prefix + '-' + $heading[0].tagName.toLowerCase();
}
};
})(jQuery);
|
'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js']
},
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
}
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
import { Matrix3 } from './Matrix3.js';
import { Vector3 } from './Vector3.js';
/**
* @author bhouston / http://clara.io
*/
function Plane( normal, constant ) {
// normal is assumed to be normalized
this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
this.constant = ( constant !== undefined ) ? constant : 0;
}
Object.assign( Plane.prototype, {
set: function ( normal, constant ) {
this.normal.copy( normal );
this.constant = constant;
return this;
},
setComponents: function ( x, y, z, w ) {
this.normal.set( x, y, z );
this.constant = w;
return this;
},
setFromNormalAndCoplanarPoint: function ( normal, point ) {
this.normal.copy( normal );
this.constant = - point.dot( this.normal );
return this;
},
setFromCoplanarPoints: function () {
var v1 = new Vector3();
var v2 = new Vector3();
return function setFromCoplanarPoints( a, b, c ) {
var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
this.setFromNormalAndCoplanarPoint( normal, a );
return this;
};
}(),
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( plane ) {
this.normal.copy( plane.normal );
this.constant = plane.constant;
return this;
},
normalize: function () {
// Note: will lead to a divide by zero if the plane is invalid.
var inverseNormalLength = 1.0 / this.normal.length();
this.normal.multiplyScalar( inverseNormalLength );
this.constant *= inverseNormalLength;
return this;
},
negate: function () {
this.constant *= - 1;
this.normal.negate();
return this;
},
distanceToPoint: function ( point ) {
return this.normal.dot( point ) + this.constant;
},
distanceToSphere: function ( sphere ) {
return this.distanceToPoint( sphere.center ) - sphere.radius;
},
projectPoint: function ( point, optionalTarget ) {
var result = optionalTarget || new Vector3();
return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
},
intersectLine: function () {
var v1 = new Vector3();
return function intersectLine( line, optionalTarget ) {
var result = optionalTarget || new Vector3();
var direction = line.delta( v1 );
var denominator = this.normal.dot( direction );
if ( denominator === 0 ) {
// line is coplanar, return origin
if ( this.distanceToPoint( line.start ) === 0 ) {
return result.copy( line.start );
}
// Unsure if this is the correct method to handle this case.
return undefined;
}
var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
if ( t < 0 || t > 1 ) {
return undefined;
}
return result.copy( direction ).multiplyScalar( t ).add( line.start );
};
}(),
intersectsLine: function ( line ) {
// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
var startSign = this.distanceToPoint( line.start );
var endSign = this.distanceToPoint( line.end );
return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
},
intersectsBox: function ( box ) {
return box.intersectsPlane( this );
},
intersectsSphere: function ( sphere ) {
return sphere.intersectsPlane( this );
},
coplanarPoint: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
return result.copy( this.normal ).multiplyScalar( - this.constant );
},
applyMatrix4: function () {
var v1 = new Vector3();
var m1 = new Matrix3();
return function applyMatrix4( matrix, optionalNormalMatrix ) {
var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
this.constant = - referencePoint.dot( normal );
return this;
};
}(),
translate: function ( offset ) {
this.constant -= offset.dot( this.normal );
return this;
},
equals: function ( plane ) {
return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
}
} );
export { Plane };
|
version https://git-lfs.github.com/spec/v1
oid sha256:60c8964f55424d6ed6f53c45330e80e08815e89656b5d96695676ddd2b781450
size 6019
|
/* globals EmberDev */
import { getDebugFunction, setDebugFunction } from '@ember/debug';
import { Libraries } from '..';
import { EMBER_LIBRARIES_ISREGISTERED } from '@ember/canary-features';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
let libs, registry;
let originalWarn = getDebugFunction('warn');
function noop() {}
moduleFor(
'Libraries registry',
class extends AbstractTestCase {
beforeEach() {
libs = new Libraries();
registry = libs._registry;
}
afterEach() {
libs = null;
registry = null;
setDebugFunction('warn', originalWarn);
}
['@test core libraries come before other libraries'](assert) {
assert.expect(2);
libs.register('my-lib', '2.0.0a');
libs.registerCoreLibrary('DS', '1.0.0-beta.2');
assert.equal(registry[0].name, 'DS');
assert.equal(registry[1].name, 'my-lib');
}
['@test only the first registration of a library is stored'](assert) {
assert.expect(3);
// overwrite warn to supress the double registration warning (see https://github.com/emberjs/ember.js/issues/16391)
setDebugFunction('warn', noop);
libs.register('magic', 1.23);
libs.register('magic', 2.23);
assert.equal(registry[0].name, 'magic');
assert.equal(registry[0].version, 1.23);
assert.equal(registry.length, 1);
}
['@test isRegistered returns correct value'](assert) {
if (EMBER_LIBRARIES_ISREGISTERED) {
assert.expect(3);
assert.equal(libs.isRegistered('magic'), false);
libs.register('magic', 1.23);
assert.equal(libs.isRegistered('magic'), true);
libs.deRegister('magic');
assert.equal(libs.isRegistered('magic'), false);
} else {
assert.expect(0);
}
}
['@test attempting to register a library that is already registered warns you'](assert) {
if (EmberDev && EmberDev.runningProdBuild) {
assert.ok(true, 'Logging does not occur in production builds');
return;
}
assert.expect(1);
libs.register('magic', 1.23);
setDebugFunction('warn', function(msg, test) {
if (!test) {
assert.equal(msg, 'Library "magic" is already registered with Ember.');
}
});
// Should warn us
libs.register('magic', 2.23);
}
['@test libraries can be de-registered'](assert) {
assert.expect(2);
libs.register('lib1', '1.0.0b');
libs.register('lib2', '1.0.0b');
libs.register('lib3', '1.0.0b');
libs.deRegister('lib1');
libs.deRegister('lib3');
assert.equal(registry[0].name, 'lib2');
assert.equal(registry.length, 1);
}
}
);
|
import { deprecate } from '../utils/deprecate';
import isArray from '../utils/is-array';
import { createLocal } from '../create/local';
import { createInvalid } from '../create/valid';
export var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
);
export var prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
export function min () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
export function max () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v15.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var rowRenderer_1 = require("./rowRenderer");
var gridPanel_1 = require("../gridPanel/gridPanel");
var context_1 = require("../context/context");
var headerRenderer_1 = require("../headerRendering/headerRenderer");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var headerWrapperComp_1 = require("../headerRendering/header/headerWrapperComp");
var AutoWidthCalculator = (function () {
function AutoWidthCalculator() {
}
// this is the trick: we create a dummy container and clone all the cells
// into the dummy, then check the dummy's width. then destroy the dummy
// as we don't need it any more.
// drawback: only the cells visible on the screen are considered
AutoWidthCalculator.prototype.getPreferredWidthForColumn = function (column) {
var eHeaderCell = this.getHeaderCellForColumn(column);
// cell isn't visible
if (!eHeaderCell) {
return -1;
}
var eDummyContainer = document.createElement('span');
// position fixed, so it isn't restricted to the boundaries of the parent
eDummyContainer.style.position = 'fixed';
// we put the dummy into the body container, so it will inherit all the
// css styles that the real cells are inheriting
var eBodyContainer = this.gridPanel.getBodyContainer();
eBodyContainer.appendChild(eDummyContainer);
// get all the cells that are currently displayed (this only brings back
// rendered cells, rows not rendered due to row visualisation will not be here)
this.putRowCellsIntoDummyContainer(column, eDummyContainer);
// also put header cell in
// we only consider the lowest level cell, not the group cell. in 99% of the time, this
// will be enough. if we consider groups, then it gets to complicated for what it's worth,
// as the groups can span columns and this class only considers one column at a time.
this.cloneItemIntoDummy(eHeaderCell, eDummyContainer);
// at this point, all the clones are lined up vertically with natural widths. the dummy
// container will have a width wide enough just to fit the largest.
var dummyContainerWidth = eDummyContainer.offsetWidth;
// we are finished with the dummy container, so get rid of it
eBodyContainer.removeChild(eDummyContainer);
// we add padding as I found sometimes the gui still put '...' after some of the texts. so the
// user can configure the grid to add a few more pixels after the calculated width
var autoSizePadding = this.gridOptionsWrapper.getAutoSizePadding();
return dummyContainerWidth + autoSizePadding;
};
AutoWidthCalculator.prototype.getHeaderCellForColumn = function (column) {
var comp = null;
// find the rendered header cell
this.headerRenderer.forEachHeaderElement(function (headerElement) {
if (headerElement instanceof headerWrapperComp_1.HeaderWrapperComp) {
var headerWrapperComp = headerElement;
if (headerWrapperComp.getColumn() === column) {
comp = headerWrapperComp;
}
}
});
return comp ? comp.getGui() : null;
};
AutoWidthCalculator.prototype.putRowCellsIntoDummyContainer = function (column, eDummyContainer) {
var _this = this;
var eCells = this.rowRenderer.getAllCellsForColumn(column);
eCells.forEach(function (eCell) { return _this.cloneItemIntoDummy(eCell, eDummyContainer); });
};
AutoWidthCalculator.prototype.cloneItemIntoDummy = function (eCell, eDummyContainer) {
// make a deep clone of the cell
var eCellClone = eCell.cloneNode(true);
// the original has a fixed width, we remove this to allow the natural width based on content
eCellClone.style.width = '';
// the original has position = absolute, we need to remove this so it's positioned normally
eCellClone.style.position = 'static';
eCellClone.style.left = '';
// we put the cell into a containing div, as otherwise the cells would just line up
// on the same line, standard flow layout, by putting them into divs, they are laid
// out one per line
var eCloneParent = document.createElement('div');
// table-row, so that each cell is on a row. i also tried display='block', but this
// didn't work in IE
eCloneParent.style.display = 'table-row';
// the twig on the branch, the branch on the tree, the tree in the hole,
// the hole in the bog, the bog in the clone, the clone in the parent,
// the parent in the dummy, and the dummy down in the vall-e-ooo, OOOOOOOOO! Oh row the rattling bog....
eCloneParent.appendChild(eCellClone);
eDummyContainer.appendChild(eCloneParent);
};
__decorate([
context_1.Autowired('rowRenderer'),
__metadata("design:type", rowRenderer_1.RowRenderer)
], AutoWidthCalculator.prototype, "rowRenderer", void 0);
__decorate([
context_1.Autowired('headerRenderer'),
__metadata("design:type", headerRenderer_1.HeaderRenderer)
], AutoWidthCalculator.prototype, "headerRenderer", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata("design:type", gridPanel_1.GridPanel)
], AutoWidthCalculator.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], AutoWidthCalculator.prototype, "gridOptionsWrapper", void 0);
AutoWidthCalculator = __decorate([
context_1.Bean('autoWidthCalculator')
], AutoWidthCalculator);
return AutoWidthCalculator;
}());
exports.AutoWidthCalculator = AutoWidthCalculator;
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'hiddenfield', function( editor )
{
return {
title : editor.lang.hidden.title,
minWidth : 350,
minHeight : 110,
onShow : function()
{
delete this.hiddenField;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == "input" && element.getAttribute( 'type' ) == "checkbox" )
{
this.hiddenField = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.hiddenField,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
element.setAttribute( 'type', 'hidden' );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( element );
},
contents : [
{
id : 'info',
label : editor.lang.hidden.title,
title : editor.lang.hidden.title,
elements : [
{
id : '_cke_saved_name',
type : 'text',
label : editor.lang.hidden.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.getAttribute( '_cke_saved_name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( '_cke_saved_name', this.getValue() );
else
{
element.removeAttribute( '_cke_saved_name' );
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.hidden.value,
'default' : '',
accessKey : 'V',
setup : function( element )
{
this.setValue( element.getAttribute( 'value' ) || '' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'value', this.getValue() );
else
element.removeAttribute( 'value' );
}
}
]
}
]
};
});
|
module.exports={A:{A:{"1":"E B A","2":"J C G UB"},B:{"1":"D X g H L"},C:{"1":"0 1 4 5 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s","2":"2 SB","132":"F I J C G E B A D X g H L M N O QB PB"},D:{"1":"0 1 4 5 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s EB BB TB CB"},E:{"1":"F I J C G E B A FB GB HB IB JB KB","2":"9 DB"},F:{"1":"6 7 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB OB RB y","2":"E","4":"LB MB"},G:{"1":"3 G A AB VB WB XB YB ZB aB bB cB","2":"9"},H:{"2":"dB"},I:{"1":"2 3 F s gB hB iB jB","2":"eB fB"},J:{"1":"C B"},K:{"1":"6 7 A D K y","2":"B"},L:{"1":"8"},M:{"1":"t"},N:{"1":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"1":"lB"},R:{"1":"mB"}},B:1,C:"Audio element"};
|
import createBlob from '../../deps/binary/blob';
function readAsBlobOrBuffer(storedObject, type) {
// In the browser, we've stored a binary string. This now comes back as a
// browserified Node-style Buffer, but we want a Blob instead.
return createBlob([storedObject.toArrayBuffer()], {type: type});
}
export default readAsBlobOrBuffer; |
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
var toString = Object.prototype.toString;
function defined(value) {
return typeof value !== 'undefined';
}
exports.defined = defined;
function undefined(value) {
return typeof value === 'undefined';
}
exports.undefined = undefined;
function nil(value) {
return value === null;
}
exports.nil = nil;
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return toString.call(value) === '[object String]';
}
exports.string = string;
function number(value) {
return toString.call(value) === '[object Number]';
}
exports.number = number;
function error(value) {
return toString.call(value) === '[object Error]';
}
exports.error = error;
function func(value) {
return toString.call(value) === '[object Function]';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(function (elem) { return string(elem); });
}
exports.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function thenable(value) {
return value && func(value.then);
}
exports.thenable = thenable;
|
// i18next, v1.7.5
// Copyright (c)2014 Jan Mühlemann (jamuhl).
// Distributed under MIT license
// http://i18next.com
//////////////////////
// HINT
//
// you need to replace '_fetchOne' with 'fetchOne' to use this on server
// fix line 351 'sendMissing' -> 'saveMissing'
//
var i18n = require('../index')
, expect = require('expect.js')
, sinon = require('sinon');
describe('i18next.init', function() {
var opts;
beforeEach(function(done) {
opts = {
lng: 'en-US',
fallbackLng: 'dev',
fallbackNS: [],
fallbackToDefaultNS: false,
fallbackOnNull: true,
fallbackOnEmpty: false,
load: 'all',
preload: [],
supportedLngs: [],
lowerCaseLng: false,
ns: 'translation',
resGetPath: 'test/locales/__lng__/__ns__.json',
resSetPath: 'test/locales/__lng__/new.__ns__.json',
saveMissing: false,
sendMissingTo: 'fallback',
resStore: false,
returnObjectTrees: false,
interpolationPrefix: '__',
interpolationSuffix: '__',
postProcess: '',
parseMissingKey: '',
debug: false,
objectTreeKeyHandler: null,
lngWhitelist: null
};
i18n.init(opts, function(t) {
i18n.sync.resStore = {};
done();
});
});
// init/init.load.spec.js
describe('advanced initialisation options', function() {
describe('setting fallbackLng', function() {
var resStore = {
dev1: { translation: { 'simple_dev1': 'ok_from_dev1' } },
en: { translation: { 'simple_en': 'ok_from_en' } },
'en-US': { translation: { 'simple_en-US': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore, fallbackLng: 'dev1' }),
function(err, t) { done(); });
});
it('it should provide passed in resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_en');
expect(i18n.t('simple_dev1')).to.be('ok_from_dev1');
});
});
describe('multiple fallbackLng', function() {
var resStore = {
dev1: { translation: { 'simple_dev1': 'ok_from_dev1', 'simple_dev': 'ok_from_dev1' } },
dev2: { translation: { 'simple_dev2': 'ok_from_dev2', 'simple_dev': 'ok_from_dev2' } },
en: { translation: { 'simple_en': 'ok_from_en' } },
'en-US': { translation: { 'simple_en-US': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore, fallbackLng: ['dev1', 'dev2'] }),
function(err, t) { done(); });
});
it('it should provide passed in resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_en');
// in one
expect(i18n.t('simple_dev1')).to.be('ok_from_dev1');
expect(i18n.t('simple_dev2')).to.be('ok_from_dev2');
// in both
expect(i18n.t('simple_dev')).to.be('ok_from_dev1');
});
});
describe('adding resources after init', function() {
var resStore = {
dev: { translation: { 'simple_dev': 'ok_from_dev' } },
en: { translation: { 'simple_en': 'ok_from_en' } }//,
//'en-US': { translation: { 'simple_en-US': 'ok_from_en-US' } }
};
describe('resources', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(err, t) {
i18n.addResource('en-US', 'translation', 'some.deep.thing', 'ok_from_en-US');
done();
});
});
it('it should provide passed in resources for translation', function() {
expect(i18n.t('some.deep.thing')).to.be('ok_from_en-US');
});
describe('multiple resources', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(err, t) {
i18n.addResources('en-US', 'translation', {
'some.other.deep.thing': 'ok_from_en-US_1',
'some.other.deep.deeper.thing': 'ok_from_en-US_2'
});
done();
});
});
it('it should add the new namespace to the namespace array', function() {
expect(i18n.t('some.other.deep.thing')).to.be('ok_from_en-US_1');
expect(i18n.t('some.other.deep.deeper.thing')).to.be('ok_from_en-US_2');
});
});
});
describe('bundles', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(err, t) {
i18n.addResourceBundle('en-US', 'translation', { 'simple_en-US': 'ok_from_en-US' });
done();
});
});
it('it should provide passed in resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_en');
expect(i18n.t('simple_dev')).to.be('ok_from_dev');
});
describe('with a additional namespace', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(err, t) {
i18n.addResourceBundle('en-US', 'newNamespace', { 'simple_en-US': 'ok_from_en-US' });
done();
});
});
it('it should add the new namespace to the namespace array', function() {
expect(i18n.options.ns.namespaces).to.contain('newNamespace');
});
});
describe('with using deep switch', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(t) {
i18n.addResourceBundle('en-US', 'translation', { 'deep': { 'simple_en-US_1': 'ok_from_en-US_1' }});
i18n.addResourceBundle('en-US', 'translation', { 'deep': { 'simple_en-US_2': 'ok_from_en-US_2' }}, true);
done();
});
});
it('it should add the new namespace to the namespace array', function() {
expect(i18n.t('deep.simple_en-US_1')).to.be('ok_from_en-US_1');
expect(i18n.t('deep.simple_en-US_2')).to.be('ok_from_en-US_2');
});
});
describe('check if exists', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(err, t) {
i18n.addResourceBundle('en-US', 'translation', { 'deep': { 'simple_en-US_1': 'ok_from_en-US_1' }});
i18n.addResourceBundle('en-US', 'translation', { 'deep': { 'simple_en-US_2': 'ok_from_en-US_2' }}, true);
done();
});
});
it('it should return true for existing bundle', function() {
expect(i18n.hasResourceBundle('en-US', 'translation')).to.be.ok();
});
it('it should return false for non-existing bundle', function() {
expect(i18n.hasResourceBundle('de-CH', 'translation')).to.not.be.ok();
});
});
});
});
describe('removing resources after init', function() {
var resStore = {
dev: { translation: { 'test': 'ok_from_dev' } },
en: { translation: { 'test': 'ok_from_en' } },
'en-US': { translation: { 'test': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { resStore: resStore }),
function(t) {
i18n.removeResourceBundle('en-US', 'translation');
done();
});
});
it('it should remove resources', function() {
expect(i18n.t('test')).to.be('ok_from_en');
});
});
describe('setting load', function() {
describe('to current', function() {
var spy;
beforeEach(function(done) {
spy = sinon.spy(i18n.sync, 'fetchOne');
i18n.init(i18n.functions.extend(opts, {
load: 'current' }),
function(t) { done(); });
});
afterEach(function() {
spy.restore();
});
it('it should load only current and fallback language', function() {
expect(spy.callCount).to.be(2); // en-US, en
});
it('it should provide loaded resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('simple_en')).not.to.be('ok_from_en');
expect(i18n.t('simple_dev')).to.be('ok_from_dev');
});
});
describe('to unspecific', function() {
var spy;
beforeEach(function(done) {
spy = sinon.spy(i18n.sync, 'fetchOne');
i18n.init(i18n.functions.extend(opts, {
load: 'unspecific' }),
function(t) { done(); });
});
afterEach(function() {
spy.restore();
});
it('it should load only unspecific and fallback language', function() {
expect(spy.callCount).to.be(2); // en-US, en
});
it('it should provide loaded resources for translation', function() {
expect(i18n.t('simple_en-US')).not.to.be('ok_from_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_en');
expect(i18n.t('simple_dev')).to.be('ok_from_dev');
});
it('it should return unspecific language', function() {
expect(i18n.lng()).to.be('en');
});
});
});
describe('with fallback language set to false', function() {
var spy;
beforeEach(function(done) {
spy = sinon.spy(i18n.sync, 'fetchOne');
i18n.init(i18n.functions.extend(opts, {
fallbackLng: false }),
function(t) { done(); });
});
afterEach(function() {
spy.restore();
});
it('it should load only specific and unspecific languages', function() {
expect(spy.callCount).to.be(2); // en-US, en
});
it('it should provide loaded resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_en');
expect(i18n.t('simple_dev')).not.to.be('ok_from_dev');
});
});
describe('preloading multiple languages', function() {
var spy;
beforeEach(function(done) {
spy = sinon.spy(i18n.sync, 'fetchOne');
i18n.init(i18n.functions.extend(opts, {
preload: ['fr', 'de-DE'] }),
function(t) { done(); });
});
afterEach(function() {
spy.restore();
});
it('it should load additional languages', function() {
expect(spy.callCount).to.be(6); // en-US, en, de-DE, de, fr, dev
});
describe('changing the language', function() {
beforeEach(function(done) {
spy.reset();
if (i18n.sync.resStore) i18n.sync.resStore = {}; // to reset for test on server!
i18n.setLng('de-DE',
function(t) { done(); });
});
it('it should reload the preloaded languages', function() {
expect(spy.callCount).to.be(4); // de-DE, de, fr, dev
});
});
});
// init/init.syncFlag.spec.js
describe('with namespace', function() {
describe('with one namespace set', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { ns: 'ns.special'} ),
function(t) { done(); });
});
it('it should provide loaded resources for translation', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_special_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_special_en');
expect(i18n.t('simple_dev')).to.be('ok_from_special_dev');
});
});
describe('with more than one namespace set', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, { ns: { namespaces: ['ns.common', 'ns.special'], defaultNs: 'ns.special'} } ),
function(t) { done(); });
});
it('it should provide loaded resources for translation', function() {
// default ns
expect(i18n.t('simple_en-US')).to.be('ok_from_special_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_special_en');
expect(i18n.t('simple_dev')).to.be('ok_from_special_dev');
// ns prefix
expect(i18n.t('ns.common:simple_en-US')).to.be('ok_from_common_en-US');
expect(i18n.t('ns.common:simple_en')).to.be('ok_from_common_en');
expect(i18n.t('ns.common:simple_dev')).to.be('ok_from_common_dev');
// ns in options
expect(i18n.t('simple_en-US', { ns: 'ns.common' })).to.be('ok_from_common_en-US');
expect(i18n.t('simple_en', { ns: 'ns.common' })).to.be('ok_from_common_en');
expect(i18n.t('simple_dev', { ns: 'ns.common' })).to.be('ok_from_common_dev');
});
describe('and fallbacking to default namespace', function() {
var resStore = {
dev: { 'ns.special': { 'simple_dev': 'ok_from_dev' } },
en: { 'ns.special': { 'simple_en': 'ok_from_en' } },
'en-US': { 'ns.special': { 'simple_en-US': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, {
fallbackToDefaultNS: true,
resStore: resStore,
ns: { namespaces: ['ns.common', 'ns.special'], defaultNs: 'ns.special'} } ),
function(t) { done(); });
});
it('it should fallback to default ns', function() {
// default ns fallback lookup
expect(i18n.t('ns.common:simple_en-US')).to.be('ok_from_en-US');
expect(i18n.t('ns.common:simple_en')).to.be('ok_from_en');
expect(i18n.t('ns.common:simple_dev')).to.be('ok_from_dev');
});
});
describe('and fallbacking to set namespace', function() {
var resStore = {
dev: {
'ns.special': { 'simple_dev': 'ok_from_dev' },
'ns.fallback': { 'simple_fallback': 'ok_from_fallback' }
},
en: { 'ns.special': { 'simple_en': 'ok_from_en' } },
'en-US': { 'ns.special': { 'simple_en-US': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, {
fallbackNS: 'ns.fallback',
resStore: resStore,
ns: { namespaces: ['ns.common', 'ns.special', 'ns.fallback'], defaultNs: 'ns.special'} } ),
function(t) { done(); });
});
it('it should fallback to set fallback namespace', function() {
expect(i18n.t('ns.common:simple_fallback')).to.be('ok_from_fallback');
});
});
describe('and fallbacking to multiple set namespace', function() {
var resStore = {
dev: {
'ns.common': {},
'ns.special': { 'simple_dev': 'ok_from_dev' },
'ns.fallback1': {
'simple_fallback': 'ok_from_fallback1',
'simple_fallback1': 'ok_from_fallback1'
}
},
en: {
'ns.special': { 'simple_en': 'ok_from_en' },
'ns.fallback2': {
'simple_fallback': 'ok_from_fallback2',
'simple_fallback2': 'ok_from_fallback2'
}
},
'en-US': { 'ns.special': { 'simple_en-US': 'ok_from_en-US' } }
};
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, {
fallbackNS: ['ns.fallback1', 'ns.fallback2'],
resStore: resStore,
ns: { namespaces: ['ns.common', 'ns.special', 'ns.fallback'], defaultNs: 'ns.special'} } ),
function(t) { done(); });
});
it('it should fallback to set fallback namespace', function() {
expect(i18n.t('ns.common:simple_fallback')).to.be('ok_from_fallback1'); /* first wins */
expect(i18n.t('ns.common:simple_fallback1')).to.be('ok_from_fallback1');
expect(i18n.t('ns.common:simple_fallback2')).to.be('ok_from_fallback2');
});
describe('and post missing', function() {
var spy;
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, {
fallbackNS: ['ns.fallback1', 'ns.fallback2'],
resStore: resStore,
saveMissing: true, /* must be changed to saveMissing */
ns: { namespaces: ['ns.common', 'ns.special', 'ns.fallback'], defaultNs: 'ns.special'} } ),
function(err, t) {
spy = sinon.spy(i18n.options, 'missingKeyHandler');
t('ns.common:notExisting');
done();
});
});
afterEach(function() {
spy.restore();
});
it('it should post only to origin namespace', function() {
expect(spy.callCount).to.be(1);
expect(spy.args[0][0]).to.be('en-US');
expect(spy.args[0][1]).to.be('ns.common');
expect(spy.args[0][2]).to.be('notExisting');
expect(spy.args[0][3]).to.be('ns.common:notExisting');
});
});
});
});
describe('with reloading additional namespace', function() {
describe('without using localStorage', function() {
beforeEach(function(done) {
i18n.init(opts,
function(t) {
i18n.setDefaultNamespace('ns.special');
i18n.loadNamespaces(['ns.common', 'ns.special'], done);
});
});
it('it should provide loaded resources for translation', function() {
// default ns
expect(i18n.t('simple_en-US')).to.be('ok_from_special_en-US');
expect(i18n.t('simple_en')).to.be('ok_from_special_en');
expect(i18n.t('simple_dev')).to.be('ok_from_special_dev');
// ns prefix
expect(i18n.t('ns.common:simple_en-US')).to.be('ok_from_common_en-US');
expect(i18n.t('ns.common:simple_en')).to.be('ok_from_common_en');
expect(i18n.t('ns.common:simple_dev')).to.be('ok_from_common_dev');
// ns in options
expect(i18n.t('simple_en-US', { ns: 'ns.common' })).to.be('ok_from_common_en-US');
expect(i18n.t('simple_en', { ns: 'ns.common' })).to.be('ok_from_common_en');
expect(i18n.t('simple_dev', { ns: 'ns.common' })).to.be('ok_from_common_dev');
});
it('it should add the new namespaces to the namespace array', function() {
expect(i18n.options.ns.namespaces).to.contain('ns.common');
expect(i18n.options.ns.namespaces).to.contain('ns.special');
});
describe('and fallbackToDefaultNS turned on', function() {
beforeEach(function(done) {
i18n.init(i18n.functions.extend(opts, {
ns: 'ns.common',
fallbackToDefaultNS: true
}),
function(t) {
i18n.loadNamespaces(['ns.special'], done);
});
});
it('it should fallback to default namespace', function() {
expect(i18n.t('ns.special:test.fallback_en')).to.be('ok_from_common_en-fallback');
expect(i18n.t('ns.special:test.fallback_dev')).to.be('ok_from_common_dev-fallback');
});
});
});
describe('with using localStorage', function() {
var spy;
before(function() {
if (typeof window !== 'undefined') { // safe use on server
window.localStorage.removeItem('res_en-US');
window.localStorage.removeItem('res_en');
window.localStorage.removeItem('res_dev');
}
});
beforeEach(function(done) {
spy = sinon.spy(i18n.sync, 'fetchOne');
i18n.init(i18n.functions.extend(opts, {
useLocalStorage: true
}), function(t) {
i18n.setDefaultNamespace('ns.special');
i18n.loadNamespaces(['ns.common', 'ns.special'], done);
});
});
afterEach(function() {
spy.restore();
});
it('it should load language', function() {
expect(spy.callCount).to.be(9); // en-US, en, de-DE, de, fr, dev * 3 namespaces (translate, common, special)
});
describe('on later reload of namespaces', function() {
beforeEach(function(done) {
spy.reset();
i18n.init(i18n.functions.extend(opts, {
useLocalStorage: true,
ns: 'translation'
}), function(t) {
i18n.setDefaultNamespace('ns.special');
i18n.loadNamespaces(['ns.common', 'ns.special'], done);
});
});
it('it should not reload language', function() {
expect(spy.callCount).to.be(0);
});
});
});
});
});
// init/init.localstorage.spec.js
describe('using function provided in callback\'s argument', function() {
var cbT;
beforeEach(function(done) {
i18n.init(opts, function(err, t) { cbT = t; done(); });
});
it('it should provide loaded resources for translation', function() {
expect(cbT('simple_en-US')).to.be('ok_from_en-US');
expect(cbT('simple_en')).to.be('ok_from_en');
expect(cbT('simple_dev')).to.be('ok_from_dev');
});
});
describe('with lowercase flag', function() {
describe('default behaviour will uppercase specifc country part.', function() {
beforeEach(function() {
i18n.init(i18n.functions.extend(opts, {
lng: 'en-us',
resStore: {
'en-US': { translation: { 'simple_en-US': 'ok_from_en-US' } }
}
}, function(t) { done(); }) );
});
it('it should translate the uppercased lng value', function() {
expect(i18n.t('simple_en-US')).to.be('ok_from_en-US');
});
it('it should get uppercased set language', function() {
expect(i18n.lng()).to.be('en-US');
});
});
describe('overridden behaviour will accept lowercased country part.', function() {
beforeEach(function() {
i18n.init(i18n.functions.extend(opts, {
lng: 'en-us',
lowerCaseLng: true,
resStore: {
'en-us': { translation: { 'simple_en-us': 'ok_from_en-us' } }
}
}, function(t) { done(); }) );
});
it('it should translate the lowercase lng value', function() {
expect(i18n.t('simple_en-us')).to.be('ok_from_en-us');
});
it('it should get lowercased set language', function() {
expect(i18n.lng()).to.be('en-us');
});
});
});
});
});
|
define(function() {
/*
* activate the language links in main navbar
*/
return function() {
$('a[href|=#lang]').click(function(evt) {
evt.preventDefault();
$.ajax({
url: '/api/account/lang',
type: 'PUT',
data: JSON.stringify({ lang: $(evt.target).attr('href').substr(6) }),
processData: false,
success: function(data) {
location.reload();
}
});
});
};
}); |
var findTabbable = require('../helpers/tabbable');
module.exports = function(node, event) {
var tabbable = findTabbable(node);
if (!tabbable.length) {
event.preventDefault();
return;
}
var finalTabbable = tabbable[event.shiftKey ? 0 : tabbable.length - 1];
var leavingFinalTabbable = (
finalTabbable === document.activeElement ||
// handle immediate shift+tab after opening with mouse
node === document.activeElement
);
if (!leavingFinalTabbable) return;
event.preventDefault();
var target = tabbable[event.shiftKey ? tabbable.length - 1 : 0];
target.focus();
};
|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKToolbarPanelButton Class: Handles the Fonts combo selector.
*/
var FCKToolbarFontsCombo = function( tooltip, style )
{
this.CommandName = 'FontName' ;
this.Label = this.GetLabel() ;
this.Tooltip = tooltip ? tooltip : this.Label ;
this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT ;
}
// Inherit from FCKToolbarSpecialCombo.
FCKToolbarFontsCombo.prototype = new FCKToolbarSpecialCombo ;
FCKToolbarFontsCombo.prototype.GetLabel = function()
{
return FCKLang.Font ;
}
FCKToolbarFontsCombo.prototype.CreateItems = function( targetSpecialCombo )
{
var aFonts = FCKConfig.FontNames.split(';') ;
for ( var i = 0 ; i < aFonts.length ; i++ )
this._Combo.AddItem( aFonts[i], '<font face="' + aFonts[i] + '" style="font-size: 12px">' + aFonts[i] + '</font>' ) ;
} |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.9
* Revision: d96a669
*
* Copyright (c) 2009-2016 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
var arrayMax = function( array ){
return Math.max.apply( Math, array );
};
var arrayMin = function( array ){
return Math.min.apply( Math, array );
};
/**
* Class: $.jqplot.BubbleRenderer
* Plugin renderer to draw a bubble chart. A Bubble chart has data points displayed as
* colored circles with an optional text label inside. To use
* the bubble renderer, you must include the bubble renderer like:
*
* > <script language="javascript" type="text/javascript" src="../src/plugins/jqplot.bubbleRenderer.js"></script>
*
* Data must be supplied in
* the form:
*
* > [[x1, y1, r1, <label or {label:'text', color:color}>], ...]
*
* where the label or options
* object is optional.
*
* Note that all bubble colors will be the same
* unless the "varyBubbleColors" option is set to true. Colors can be specified in the data array
* or in the seriesColors array option on the series. If no colors are defined, the default jqPlot
* series of 16 colors are used. Colors are automatically cycled around again if there are more
* bubbles than colors.
*
* Bubbles are autoscaled by default to fit within the chart area while maintaining
* relative sizes. If the "autoscaleBubbles" option is set to false, the r(adius) values
* in the data array a treated as literal pixel values for the radii of the bubbles.
*
* Properties are passed into the bubble renderer in the rendererOptions object of
* the series options like:
*
* > seriesDefaults: {
* > renderer: $.jqplot.BubbleRenderer,
* > rendererOptions: {
* > bubbleAlpha: 0.7,
* > varyBubbleColors: false
* > }
* > }
*
*/
$.jqplot.BubbleRenderer = function(){
$.jqplot.LineRenderer.call(this);
};
$.jqplot.BubbleRenderer.prototype = new $.jqplot.LineRenderer();
$.jqplot.BubbleRenderer.prototype.constructor = $.jqplot.BubbleRenderer;
// called with scope of a series
$.jqplot.BubbleRenderer.prototype.init = function(options, plot) {
// Group: Properties
//
// prop: varyBubbleColors
// True to vary the color of each bubble in this series according to
// the seriesColors array. False to set each bubble to the color
// specified on this series. This has no effect if a css background color
// option is specified in the renderer css options.
this.varyBubbleColors = true;
// prop: autoscaleBubbles
// True to scale the bubble radius based on plot size.
// False will use the radius value as provided as a raw pixel value for
// bubble radius.
this.autoscaleBubbles = true;
// prop: autoscaleMultiplier
// Multiplier the bubble size if autoscaleBubbles is true.
this.autoscaleMultiplier = 1.0;
// prop: autoscalePointsFactor
// Factor which decreases bubble size based on how many bubbles on on the chart.
// 0 means no adjustment for number of bubbles. Negative values will decrease
// size of bubbles as more bubbles are added. Values between 0 and -0.2
// should work well.
this.autoscalePointsFactor = -0.07;
// prop: escapeHtml
// True to escape html in bubble label text.
this.escapeHtml = true;
// prop: highlightMouseOver
// True to highlight bubbles when moused over.
// This must be false to enable highlightMouseDown to highlight when clicking on a slice.
this.highlightMouseOver = true;
// prop: highlightMouseDown
// True to highlight when a mouse button is pressed over a bubble.
// This will be disabled if highlightMouseOver is true.
this.highlightMouseDown = false;
// prop: highlightColors
// An array of colors to use when highlighting a slice. Calculated automatically
// if not supplied.
this.highlightColors = [];
// prop: bubbleAlpha
// Alpha transparency to apply to all bubbles in this series.
this.bubbleAlpha = 1.0;
// prop: highlightAlpha
// Alpha transparency to apply when highlighting bubble.
// Set to value of bubbleAlpha by default.
this.highlightAlpha = null;
// prop: bubbleGradients
// True to color the bubbles with gradient fills instead of flat colors.
// NOT AVAILABLE IN IE due to lack of excanvas support for radial gradient fills.
// will be ignored in IE.
this.bubbleGradients = false;
// prop: showLabels
// True to show labels on bubbles (if any), false to not show.
this.showLabels = true;
// array of [point index, radius] which will be sorted in descending order to plot
// largest points below smaller points.
this.radii = [];
this.maxRadius = 0;
// index of the currenty highlighted point, if any
this._highlightedPoint = null;
// array of jQuery labels.
this.labels = [];
this.bubbleCanvases = [];
this._type = 'bubble';
// if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
if (options.highlightMouseDown && options.highlightMouseOver == null) {
options.highlightMouseOver = false;
}
$.extend(true, this, options);
if (this.highlightAlpha == null) {
this.highlightAlpha = this.bubbleAlpha;
if (this.bubbleGradients) {
this.highlightAlpha = 0.35;
}
}
this.autoscaleMultiplier = this.autoscaleMultiplier * Math.pow(this.data.length, this.autoscalePointsFactor);
// index of the currenty highlighted point, if any
this._highlightedPoint = null;
// adjust the series colors for options colors passed in with data or for alpha.
// note, this can leave undefined holes in the seriesColors array.
var comps;
for (var i=0; i<this.data.length; i++) {
var color = null;
var d = this.data[i];
this.maxRadius = Math.max(this.maxRadius, d[2]);
if (d[3]) {
if (typeof(d[3]) == 'object') {
color = d[3]['color'];
}
}
if (color == null) {
if (this.seriesColors[i] != null) {
color = this.seriesColors[i];
}
}
if (color && this.bubbleAlpha < 1.0) {
comps = $.jqplot.getColorComponents(color);
color = 'rgba('+comps[0]+', '+comps[1]+', '+comps[2]+', '+this.bubbleAlpha+')';
}
if (color) {
this.seriesColors[i] = color;
}
}
if (!this.varyBubbleColors) {
this.seriesColors = [this.color];
}
this.colorGenerator = new $.jqplot.ColorGenerator(this.seriesColors);
// set highlight colors if none provided
if (this.highlightColors.length == 0) {
for (var i=0; i<this.seriesColors.length; i++){
var rgba = $.jqplot.getColorComponents(this.seriesColors[i]);
var newrgb = [rgba[0], rgba[1], rgba[2]];
var sum = newrgb[0] + newrgb[1] + newrgb[2];
for (var j=0; j<3; j++) {
// when darkening, lowest color component can be is 60.
newrgb[j] = (sum > 570) ? newrgb[j] * 0.8 : newrgb[j] + 0.3 * (255 - newrgb[j]);
newrgb[j] = parseInt(newrgb[j], 10);
}
this.highlightColors.push('rgba('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+', '+this.highlightAlpha+')');
}
}
this.highlightColorGenerator = new $.jqplot.ColorGenerator(this.highlightColors);
var sopts = {fill:true, isarc:true, angle:this.shadowAngle, alpha:this.shadowAlpha, closePath:true};
this.renderer.shadowRenderer.init(sopts);
this.canvas = new $.jqplot.DivCanvas();
this.canvas._plotDimensions = this._plotDimensions;
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
plot.postDrawHooks.addOnce(postPlotDraw);
};
// converts the user data values to grid coordinates and stores them
// in the gridData array.
// Called with scope of a series.
$.jqplot.BubbleRenderer.prototype.setGridData = function(plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var data = this._plotData;
this.gridData = [];
var radii = [];
this.radii = [];
var dim = Math.min(plot._height, plot._width);
for (var i=0; i<this.data.length; i++) {
if (data[i] != null) {
this.gridData.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1]), data[i][2]]);
this.radii.push([i, data[i][2]]);
radii.push(data[i][2]);
}
}
var r, val, maxr = this.maxRadius = arrayMax(radii);
var l = this.gridData.length;
if (this.autoscaleBubbles) {
for (var i=0; i<l; i++) {
val = radii[i]/maxr;
r = this.autoscaleMultiplier * dim / 6;
this.gridData[i][2] = r * val;
}
}
this.radii.sort(function(a, b) { return b[1] - a[1]; });
};
// converts any arbitrary data values to grid coordinates and
// returns them. This method exists so that plugins can use a series'
// linerenderer to generate grid data points without overwriting the
// grid data associated with that series.
// Called with scope of a series.
$.jqplot.BubbleRenderer.prototype.makeGridData = function(data, plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var gd = [];
var radii = [];
this.radii = [];
var dim = Math.min(plot._height, plot._width);
for (var i=0; i<data.length; i++) {
if (data[i] != null) {
gd.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1]), data[i][2]]);
radii.push(data[i][2]);
this.radii.push([i, data[i][2]]);
}
}
var r, val, maxr = this.maxRadius = arrayMax(radii);
var l = this.gridData.length;
if (this.autoscaleBubbles) {
for (var i=0; i<l; i++) {
val = radii[i]/maxr;
r = this.autoscaleMultiplier * dim / 6;
gd[i][2] = r * val;
}
}
this.radii.sort(function(a, b) { return b[1] - a[1]; });
return gd;
};
// called with scope of series
$.jqplot.BubbleRenderer.prototype.draw = function (ctx, gd, options) {
if (this.plugins.pointLabels) {
this.plugins.pointLabels.show = false;
}
var opts = (options != undefined) ? options : {};
var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
this.canvas._elem.empty();
for (var i=0; i<this.radii.length; i++) {
var idx = this.radii[i][0];
var t=null;
var color = null;
var el = null;
var tel = null;
var d = this.data[idx];
var gd = this.gridData[idx];
if (d[3]) {
if (typeof(d[3]) == 'object') {
t = d[3]['label'];
}
else if (typeof(d[3]) == 'string') {
t = d[3];
}
}
// color = (this.varyBubbleColors) ? this.colorGenerator.get(idx) : this.color;
color = this.colorGenerator.get(idx);
// If we're drawing a shadow, expand the canvas dimensions to accomodate.
var canvasRadius = gd[2];
var offset, depth;
if (this.shadow) {
offset = (0.7 + gd[2]/40).toFixed(1);
depth = 1 + Math.ceil(gd[2]/15);
canvasRadius += offset*depth;
}
this.bubbleCanvases[idx] = new $.jqplot.BubbleCanvas();
this.canvas._elem.append(this.bubbleCanvases[idx].createElement(gd[0], gd[1], canvasRadius));
this.bubbleCanvases[idx].setContext();
var ctx = this.bubbleCanvases[idx]._ctx;
var x = ctx.canvas.width/2;
var y = ctx.canvas.height/2;
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, [x, y, gd[2], 0, 2*Math.PI], {offset: offset, depth: depth});
}
this.bubbleCanvases[idx].draw(gd[2], color, this.bubbleGradients, this.shadowAngle/180*Math.PI);
// now draw label.
if (t && this.showLabels) {
tel = $('<div style="position:absolute;" class="jqplot-bubble-label"></div>');
if (this.escapeHtml) {
tel.text(t);
}
else {
tel.html(t);
}
this.canvas._elem.append(tel);
var h = $(tel).outerHeight();
var w = $(tel).outerWidth();
var top = gd[1] - 0.5*h;
var left = gd[0] - 0.5*w;
tel.css({top: top, left: left});
this.labels[idx] = $(tel);
}
}
};
$.jqplot.DivCanvas = function() {
$.jqplot.ElemContainer.call(this);
this._ctx;
};
$.jqplot.DivCanvas.prototype = new $.jqplot.ElemContainer();
$.jqplot.DivCanvas.prototype.constructor = $.jqplot.DivCanvas;
$.jqplot.DivCanvas.prototype.createElement = function(offsets, clss, plotDimensions) {
this._offsets = offsets;
var klass = 'jqplot-DivCanvas';
if (clss != undefined) {
klass = clss;
}
var elem;
// if this canvas already has a dom element, don't make a new one.
if (this._elem) {
elem = this._elem.get(0);
}
else {
elem = document.createElement('div');
}
// if new plotDimensions supplied, use them.
if (plotDimensions != undefined) {
this._plotDimensions = plotDimensions;
}
var w = this._plotDimensions.width - this._offsets.left - this._offsets.right + 'px';
var h = this._plotDimensions.height - this._offsets.top - this._offsets.bottom + 'px';
this._elem = $(elem);
this._elem.css({ position: 'absolute', width:w, height:h, left: this._offsets.left, top: this._offsets.top });
this._elem.addClass(klass);
return this._elem;
};
$.jqplot.DivCanvas.prototype.setContext = function() {
this._ctx = {
canvas:{
width:0,
height:0
},
clearRect:function(){return null;}
};
return this._ctx;
};
$.jqplot.BubbleCanvas = function() {
$.jqplot.ElemContainer.call(this);
this._ctx;
};
$.jqplot.BubbleCanvas.prototype = new $.jqplot.ElemContainer();
$.jqplot.BubbleCanvas.prototype.constructor = $.jqplot.BubbleCanvas;
// initialize with the x,y pont of bubble center and the bubble radius.
$.jqplot.BubbleCanvas.prototype.createElement = function(x, y, r) {
var klass = 'jqplot-bubble-point';
var elem;
// if this canvas already has a dom element, don't make a new one.
if (this._elem) {
elem = this._elem.get(0);
}
else {
elem = document.createElement('canvas');
}
elem.width = (r != null) ? 2*r : elem.width;
elem.height = (r != null) ? 2*r : elem.height;
this._elem = $(elem);
var l = (x != null && r != null) ? x - r : this._elem.css('left');
var t = (y != null && r != null) ? y - r : this._elem.css('top');
this._elem.css({ position: 'absolute', left: l, top: t });
this._elem.addClass(klass);
if ($.jqplot.use_excanvas) {
window.G_vmlCanvasManager.init_(document);
elem = window.G_vmlCanvasManager.initElement(elem);
}
return this._elem;
};
$.jqplot.BubbleCanvas.prototype.draw = function(r, color, gradients, angle) {
var ctx = this._ctx;
// r = Math.floor(r*1.04);
// var x = Math.round(ctx.canvas.width/2);
// var y = Math.round(ctx.canvas.height/2);
var x = ctx.canvas.width/2;
var y = ctx.canvas.height/2;
ctx.save();
if (gradients && !$.jqplot.use_excanvas) {
r = r*1.04;
var comps = $.jqplot.getColorComponents(color);
var colorinner = 'rgba('+Math.round(comps[0]+0.8*(255-comps[0]))+', '+Math.round(comps[1]+0.8*(255-comps[1]))+', '+Math.round(comps[2]+0.8*(255-comps[2]))+', '+comps[3]+')';
var colorend = 'rgba('+comps[0]+', '+comps[1]+', '+comps[2]+', 0)';
// var rinner = Math.round(0.35 * r);
// var xinner = Math.round(x - Math.cos(angle) * 0.33 * r);
// var yinner = Math.round(y - Math.sin(angle) * 0.33 * r);
var rinner = 0.35 * r;
var xinner = x - Math.cos(angle) * 0.33 * r;
var yinner = y - Math.sin(angle) * 0.33 * r;
var radgrad = ctx.createRadialGradient(xinner, yinner, rinner, x, y, r);
radgrad.addColorStop(0, colorinner);
radgrad.addColorStop(0.93, color);
radgrad.addColorStop(0.96, colorend);
radgrad.addColorStop(1, colorend);
// radgrad.addColorStop(.98, colorend);
ctx.fillStyle = radgrad;
ctx.fillRect(0,0, ctx.canvas.width, ctx.canvas.height);
}
else {
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
var ang = 2*Math.PI;
ctx.arc(x, y, r, 0, ang, 0);
ctx.closePath();
ctx.fill();
}
ctx.restore();
};
$.jqplot.BubbleCanvas.prototype.setContext = function() {
this._ctx = this._elem.get(0).getContext("2d");
return this._ctx;
};
$.jqplot.BubbleAxisRenderer = function() {
$.jqplot.LinearAxisRenderer.call(this);
};
$.jqplot.BubbleAxisRenderer.prototype = new $.jqplot.LinearAxisRenderer();
$.jqplot.BubbleAxisRenderer.prototype.constructor = $.jqplot.BubbleAxisRenderer;
// called with scope of axis object.
$.jqplot.BubbleAxisRenderer.prototype.init = function(options){
$.extend(true, this, options);
var db = this._dataBounds;
var minsidx = 0,
minpidx = 0,
maxsidx = 0,
maxpidx = 0,
maxr = 0,
minr = 0,
minMaxRadius = 0,
maxMaxRadius = 0,
maxMult = 0,
minMult = 0;
// Go through all the series attached to this axis and find
// the min/max bounds for this axis.
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
var d = s._plotData;
for (var j=0; j<d.length; j++) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
if (d[j][0] < db.min || db.min == null) {
db.min = d[j][0];
minsidx=i;
minpidx=j;
minr = d[j][2];
minMaxRadius = s.maxRadius;
minMult = s.autoscaleMultiplier;
}
if (d[j][0] > db.max || db.max == null) {
db.max = d[j][0];
maxsidx=i;
maxpidx=j;
maxr = d[j][2];
maxMaxRadius = s.maxRadius;
maxMult = s.autoscaleMultiplier;
}
}
else {
if (d[j][1] < db.min || db.min == null) {
db.min = d[j][1];
minsidx=i;
minpidx=j;
minr = d[j][2];
minMaxRadius = s.maxRadius;
minMult = s.autoscaleMultiplier;
}
if (d[j][1] > db.max || db.max == null) {
db.max = d[j][1];
maxsidx=i;
maxpidx=j;
maxr = d[j][2];
maxMaxRadius = s.maxRadius;
maxMult = s.autoscaleMultiplier;
}
}
}
}
var minRatio = minr/minMaxRadius;
var maxRatio = maxr/maxMaxRadius;
// need to estimate the effect of the radius on total axis span and adjust axis accordingly.
var span = db.max - db.min;
// var dim = (this.name == 'xaxis' || this.name == 'x2axis') ? this._plotDimensions.width : this._plotDimensions.height;
var dim = Math.min(this._plotDimensions.width, this._plotDimensions.height);
var minfact = minRatio * minMult/3 * span;
var maxfact = maxRatio * maxMult/3 * span;
db.max += maxfact;
db.min -= minfact;
};
function highlight (plot, sidx, pidx) {
plot.plugins.bubbleRenderer.highlightLabelCanvas.empty();
var s = plot.series[sidx];
var canvas = plot.plugins.bubbleRenderer.highlightCanvas;
var ctx = canvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
s._highlightedPoint = pidx;
plot.plugins.bubbleRenderer.highlightedSeriesIndex = sidx;
var color = s.highlightColorGenerator.get(pidx);
var x = s.gridData[pidx][0],
y = s.gridData[pidx][1],
r = s.gridData[pidx][2];
ctx.save();
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x, y, r, 0, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
ctx.restore();
// bring label to front
if (s.labels[pidx]) {
plot.plugins.bubbleRenderer.highlightLabel = s.labels[pidx].clone();
plot.plugins.bubbleRenderer.highlightLabel.appendTo(plot.plugins.bubbleRenderer.highlightLabelCanvas);
plot.plugins.bubbleRenderer.highlightLabel.addClass('jqplot-bubble-label-highlight');
}
}
function unhighlight (plot) {
var canvas = plot.plugins.bubbleRenderer.highlightCanvas;
var sidx = plot.plugins.bubbleRenderer.highlightedSeriesIndex;
plot.plugins.bubbleRenderer.highlightLabelCanvas.empty();
canvas._ctx.clearRect(0,0, canvas._ctx.canvas.width, canvas._ctx.canvas.height);
for (var i=0; i<plot.series.length; i++) {
plot.series[i]._highlightedPoint = null;
}
plot.plugins.bubbleRenderer.highlightedSeriesIndex = null;
plot.target.trigger('jqplotDataUnhighlight');
}
function handleMove(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var si = neighbor.seriesIndex;
var pi = neighbor.pointIndex;
var ins = [si, pi, neighbor.data, plot.series[si].gridData[pi][2]];
var evt1 = jQuery.Event('jqplotDataMouseOver');
evt1.pageX = ev.pageX;
evt1.pageY = ev.pageY;
plot.target.trigger(evt1, ins);
if (plot.series[ins[0]].highlightMouseOver && !(ins[0] == plot.plugins.bubbleRenderer.highlightedSeriesIndex && ins[1] == plot.series[ins[0]]._highlightedPoint)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.which = ev.which;
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, ins[0], ins[1]);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var si = neighbor.seriesIndex;
var pi = neighbor.pointIndex;
var ins = [si, pi, neighbor.data, plot.series[si].gridData[pi][2]];
if (plot.series[ins[0]].highlightMouseDown && !(ins[0] == plot.plugins.bubbleRenderer.highlightedSeriesIndex && ins[1] == plot.series[ins[0]]._highlightedPoint)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.which = ev.which;
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, ins[0], ins[1]);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseUp(ev, gridpos, datapos, neighbor, plot) {
var idx = plot.plugins.bubbleRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
}
function handleClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var si = neighbor.seriesIndex;
var pi = neighbor.pointIndex;
var ins = [si, pi, neighbor.data, plot.series[si].gridData[pi][2]];
var evt = jQuery.Event('jqplotDataClick');
evt.which = ev.which;
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
function handleRightClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var si = neighbor.seriesIndex;
var pi = neighbor.pointIndex;
var ins = [si, pi, neighbor.data, plot.series[si].gridData[pi][2]];
var idx = plot.plugins.bubbleRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
var evt = jQuery.Event('jqplotDataRightClick');
evt.which = ev.which;
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
// called within context of plot
// create a canvas which we can draw on.
// insert it before the eventCanvas, so eventCanvas will still capture events.
function postPlotDraw() {
// Memory Leaks patch
if (this.plugins.bubbleRenderer && this.plugins.bubbleRenderer.highlightCanvas) {
this.plugins.bubbleRenderer.highlightCanvas.resetCanvas();
this.plugins.bubbleRenderer.highlightCanvas = null;
}
this.plugins.bubbleRenderer = {highlightedSeriesIndex:null};
this.plugins.bubbleRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
this.plugins.bubbleRenderer.highlightLabel = null;
this.plugins.bubbleRenderer.highlightLabelCanvas = $('<div style="position:absolute;"></div>');
var top = this._gridPadding.top;
var left = this._gridPadding.left;
var width = this._plotDimensions.width - this._gridPadding.left - this._gridPadding.right;
var height = this._plotDimensions.height - this._gridPadding.top - this._gridPadding.bottom;
this.plugins.bubbleRenderer.highlightLabelCanvas.css({top:top, left:left, width:width+'px', height:height+'px'});
this.eventCanvas._elem.before(this.plugins.bubbleRenderer.highlightCanvas.createElement(this._gridPadding, 'jqplot-bubbleRenderer-highlight-canvas', this._plotDimensions, this));
this.eventCanvas._elem.before(this.plugins.bubbleRenderer.highlightLabelCanvas);
var hctx = this.plugins.bubbleRenderer.highlightCanvas.setContext();
}
// setup default renderers for axes and legend so user doesn't have to
// called with scope of plot
function preInit(target, data, options) {
options = options || {};
options.axesDefaults = options.axesDefaults || {};
options.seriesDefaults = options.seriesDefaults || {};
// only set these if there is a Bubble series
var setopts = false;
if (options.seriesDefaults.renderer == $.jqplot.BubbleRenderer) {
setopts = true;
}
else if (options.series) {
for (var i=0; i < options.series.length; i++) {
if (options.series[i].renderer == $.jqplot.BubbleRenderer) {
setopts = true;
}
}
}
if (setopts) {
options.axesDefaults.renderer = $.jqplot.BubbleAxisRenderer;
options.sortData = false;
}
}
$.jqplot.preInitHooks.push(preInit);
})(jQuery);
|
// Generated by CoffeeScript 1.8.0
(function() {
var $;
$ = this.jQuery;
$.fn.extend({
confirmWithReveal: function(options) {
var defaults, do_confirm, handler, settings;
if (options == null) {
options = {};
}
defaults = {
modal_class: 'medium',
title: 'Are you sure?',
title_class: '',
body: 'This action cannot be undone.',
body_class: '',
password: false,
prompt: 'Type <strong>%s</strong> to continue:',
footer_class: '',
ok: 'Confirm',
ok_class: 'button alert',
cancel: 'Cancel',
cancel_class: 'button secondary'
};
settings = $.extend({}, defaults, options);
do_confirm = function($el) {
var confirm_button, confirm_html, confirm_label, el_options, modal, option, password, _ref;
el_options = $el.data('confirm');
if ($el.attr('data-confirm') == null) {
return true;
}
if ((typeof el_options === 'string') && (el_options.length > 0)) {
return (((_ref = $.rails) != null ? _ref.confirm : void 0) || window.confirm).call(window, el_options);
}
option = function(name) {
return el_options[name] || settings[name];
};
modal = $("<div data-reveal class='reveal-modal " + (option('modal_class')) + "'>\n <h2 data-confirm-title class='" + (option('title_class')) + "'></h2>\n <p data-confirm-body class='" + (option('body_class')) + "'></p>\n <div data-confirm-footer class='" + (option('footer_class')) + "'>\n <a data-confirm-cancel class='" + (option('cancel_class')) + "'></a>\n </div>\n</div>");
confirm_button = $el.is('a') ? $el.clone() : $('<a/>');
confirm_button.removeAttr('data-confirm').attr('class', option('ok_class')).html(option('ok')).on('click', function(e) {
if ($(this).prop('disabled')) {
return false;
}
$el.trigger('confirm.reveal', e);
if ($el.is('form, :input')) {
return $el.closest('form').removeAttr('data-confirm').submit();
}
});
modal.find('[data-confirm-title]').html(option('title'));
modal.find('[data-confirm-body]').html(option('body'));
modal.find('[data-confirm-cancel]').html(option('cancel')).on('click', function(e) {
modal.foundation('reveal', 'close');
return $el.trigger('cancel.reveal', e);
});
modal.find('[data-confirm-footer]').append(confirm_button);
if ((password = option('password'))) {
confirm_label = (option('prompt')).replace('%s', password);
confirm_html = "<label>\n " + confirm_label + "\n <input data-confirm-password type='text'/>\n</label>";
modal.find('[data-confirm-body]').after($(confirm_html));
modal.find('[data-confirm-password]').on('keyup', function(e) {
var disabled;
disabled = $(this).val() !== password;
return confirm_button.toggleClass('disabled', disabled).prop('disabled', disabled);
}).trigger('keyup');
}
modal.appendTo($('body')).foundation().foundation('reveal', 'open').on('closed.fndtn.reveal', function(e) {
return modal.remove();
});
return false;
};
if ($.rails) {
$.rails.allowAction = function(link) {
return do_confirm($(link));
};
return $(this);
} else {
handler = function(e) {
if (!(do_confirm($(this)))) {
e.preventDefault();
return e.stopImmediatePropagation();
}
};
return this.each(function() {
var $el;
$el = $(this);
$el.on('click', 'a[data-confirm], :input[data-confirm]', handler);
$el.on('submit', 'form[data-confirm]', handler);
return $el;
});
}
}
});
}).call(this);
|
'use strict';
/**
* Watcher for separate Js files files
*/
module.exports = function () {
return tars.packages.chokidar.watch('markup/' + tars.config.fs.staticFolderName + '/js/separate-js/**/*.js', {
ignored: '',
persistent: true,
ignoreInitial: true
}).on('all', function (event, path) {
tars.helpers.watcherLog(event, path);
tars.packages.gulp.start('js:move-separate');
});
};
|
// Stringifier based on css-stringify
var emit = function (str) {
return str.toString();
};
var visit = function (node, last) {
return traverse[node.type](node, last);
};
var mapVisit = function (nodes) {
var buf = "";
for (var i = 0, length = nodes.length; i < length; i++) {
buf += visit(nodes[i], i === length - 1);
}
return buf;
};
MinifyAst = function(node) {
return node.stylesheet
.rules.map(function (rule) { return visit(rule); })
.join('');
};
var traverse = {};
traverse.comment = function(node) {
return emit('', node.position);
};
traverse.import = function(node) {
return emit('@import ' + node.import + ';', node.position);
};
traverse.media = function(node) {
return emit('@media ' + node.media, node.position, true)
+ emit('{')
+ mapVisit(node.rules)
+ emit('}');
};
traverse.document = function(node) {
var doc = '@' + (node.vendor || '') + 'document ' + node.document;
return emit(doc, node.position, true)
+ emit('{')
+ mapVisit(node.rules)
+ emit('}');
};
traverse.charset = function(node) {
return emit('@charset ' + node.charset + ';', node.position);
};
traverse.namespace = function(node) {
return emit('@namespace ' + node.namespace + ';', node.position);
};
traverse.supports = function(node){
return emit('@supports ' + node.supports, node.position, true)
+ emit('{')
+ mapVisit(node.rules)
+ emit('}');
};
traverse.keyframes = function(node) {
return emit('@'
+ (node.vendor || '')
+ 'keyframes '
+ node.name, node.position, true)
+ emit('{')
+ mapVisit(node.keyframes)
+ emit('}');
};
traverse.keyframe = function(node) {
var decls = node.declarations;
return emit(node.values.join(','), node.position, true)
+ emit('{')
+ mapVisit(decls)
+ emit('}');
};
traverse.page = function(node) {
var sel = node.selectors.length
? node.selectors.join(', ')
: '';
return emit('@page ' + sel, node.position, true)
+ emit('{')
+ mapVisit(node.declarations)
+ emit('}');
};
traverse['font-face'] = function(node){
return emit('@font-face', node.position, true)
+ emit('{')
+ mapVisit(node.declarations)
+ emit('}');
};
traverse.rule = function(node) {
var decls = node.declarations;
if (!decls.length) return '';
var selectors = node.selectors.map(function (selector) {
// removes universal selectors like *.class => .class
// removes optional whitespace around '>' and '+'
return selector.replace(/\*\./, '.')
.replace(/\s*>\s*/g, '>')
.replace(/\s*\+\s*/g, '+');
});
return emit(selectors.join(','), node.position, true)
+ emit('{')
+ mapVisit(decls)
+ emit('}');
};
traverse.declaration = function(node, last) {
var value = node.value;
// remove optional quotes around font name
if (node.property === 'font') {
value = value.replace(/\'[^\']+\'/g, function (m) {
if (m.indexOf(' ') !== -1)
return m;
return m.replace(/\'/g, '');
});
value = value.replace(/\"[^\"]+\"/g, function (m) {
if (m.indexOf(' ') !== -1)
return m;
return m.replace(/\"/g, '');
});
}
// remove url quotes if possible
// in case it is the last declaration, we can omit the semicolon
return emit(node.property + ':' + value, node.position)
+ (last ? '' : emit(';'));
};
|
var po = org.polymaps;
var map = po.map()
.container(document.getElementById("map").appendChild(po.svg("svg")))
.zoomRange([1, 10])
.zoom(3)
.add(po.image().url(tilestache("http://s3.amazonaws.com/info.aaronland.tiles.shapetiles/{Z}/{X}/{Y}.png")))
.add(po.interact())
.add(po.compass().pan("none"));
/** Returns a TileStache URL template given a string. */
function tilestache(template) {
/** Pads the specified string to length n with character c. */
function pad(s, n, c) {
var m = n - s.length;
return (m < 1) ? s : new Array(m + 1).join(c) + s;
}
/** Formats the specified number per TileStache. */
function format(i) {
var s = pad(String(i), 6, "0");
return s.substr(0, 3) + "/" + s.substr(3);
}
return function(c) {
var max = 1 << c.zoom, column = c.column % max;
if (column < 0) column += max;
return template.replace(/{(.)}/g, function(s, v) {
switch (v) {
case "Z": return c.zoom;
case "X": return format(column);
case "Y": return format(c.row);
}
return v;
});
};
}
|
// Copyright 2011 The Closure Library 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.
/**
* @fileoverview Wrapper for an IndexedDB database.
*
*/
goog.provide('goog.db.IndexedDb');
goog.require('goog.db.Error');
goog.require('goog.db.ObjectStore');
goog.require('goog.db.Transaction');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
/**
* Creates an IDBDatabase wrapper object. The database object has methods for
* setting the version to change the structure of the database and for creating
* transactions to get or modify the stored records. Should not be created
* directly, call {@link goog.db.openDatabase} to set up the connection.
*
* @param {!IDBDatabase} db Underlying IndexedDB database object.
* @constructor
* @extends {goog.events.EventTarget}
* @final
*/
goog.db.IndexedDb = function(db) {
goog.db.IndexedDb.base(this, 'constructor');
/**
* Underlying IndexedDB database object.
*
* @type {!IDBDatabase}
* @private
*/
this.db_ = db;
/**
* Internal event handler that listens to IDBDatabase events.
* @type {!goog.events.EventHandler<!goog.db.IndexedDb>}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
this.eventHandler_.listen(
this.db_, goog.db.IndexedDb.EventType.ABORT,
goog.bind(this.dispatchEvent, this, goog.db.IndexedDb.EventType.ABORT));
this.eventHandler_.listen(
this.db_, goog.db.IndexedDb.EventType.ERROR, this.dispatchError_);
this.eventHandler_.listen(
this.db_, goog.db.IndexedDb.EventType.VERSION_CHANGE,
this.dispatchVersionChange_);
this.eventHandler_.listen(
this.db_, goog.db.IndexedDb.EventType.CLOSE,
goog.bind(this.dispatchEvent, this, goog.db.IndexedDb.EventType.CLOSE));
};
goog.inherits(goog.db.IndexedDb, goog.events.EventTarget);
/**
* True iff the database connection is open.
*
* @type {boolean}
* @private
*/
goog.db.IndexedDb.prototype.open_ = true;
/**
* Dispatches a wrapped error event based on the given event.
*
* @param {Event} ev The error event given to the underlying IDBDatabase.
* @private
*/
goog.db.IndexedDb.prototype.dispatchError_ = function(ev) {
this.dispatchEvent({
type: goog.db.IndexedDb.EventType.ERROR,
errorCode: /** @type {IDBRequest} */ (ev.target).error.severity
});
};
/**
* Dispatches a wrapped version change event based on the given event.
*
* @param {Event} ev The version change event given to the underlying
* IDBDatabase.
* @private
*/
goog.db.IndexedDb.prototype.dispatchVersionChange_ = function(ev) {
this.dispatchEvent(
new goog.db.IndexedDb.VersionChangeEvent(ev.oldVersion, ev.newVersion));
};
/**
* Closes the database connection. Metadata queries can still be made after this
* method is called, but otherwise this wrapper should not be used further.
*/
goog.db.IndexedDb.prototype.close = function() {
if (this.open_) {
this.db_.close();
this.open_ = false;
}
};
/**
* @return {boolean} Whether a connection is open and the database can be used.
*/
goog.db.IndexedDb.prototype.isOpen = function() {
return this.open_;
};
/**
* @return {string} The name of this database.
*/
goog.db.IndexedDb.prototype.getName = function() {
return this.db_.name;
};
/**
* @return {string} The current database version.
*/
goog.db.IndexedDb.prototype.getVersion = function() {
return this.db_.version;
};
/**
* @return {DOMStringList} List of object stores in this database.
*/
goog.db.IndexedDb.prototype.getObjectStoreNames = function() {
return this.db_.objectStoreNames;
};
/**
* Creates an object store in this database. Can only be called inside a
* {@link goog.db.UpgradeNeededCallback}.
*
* @param {string} name Name for the new object store.
* @param {Object=} opt_params Options object. The available options are:
* keyPath, which is a string and determines what object attribute
* to use as the key when storing objects in this object store; and
* autoIncrement, which is a boolean, which defaults to false and determines
* whether the object store should automatically generate keys for stored
* objects. If keyPath is not provided and autoIncrement is false, then all
* insert operations must provide a key as a parameter.
* @return {!goog.db.ObjectStore} The newly created object store.
* @throws {goog.db.Error} If there's a problem creating the object store.
*/
goog.db.IndexedDb.prototype.createObjectStore = function(name, opt_params) {
try {
return new goog.db.ObjectStore(
this.db_.createObjectStore(name, opt_params));
} catch (ex) {
throw goog.db.Error.fromException(ex, 'creating object store ' + name);
}
};
/**
* Deletes an object store. Can only be called inside a
* {@link goog.db.UpgradeNeededCallback}.
*
* @param {string} name Name of the object store to delete.
* @throws {goog.db.Error} If there's a problem deleting the object store.
*/
goog.db.IndexedDb.prototype.deleteObjectStore = function(name) {
try {
this.db_.deleteObjectStore(name);
} catch (ex) {
throw goog.db.Error.fromException(ex, 'deleting object store ' + name);
}
};
/**
* Creates a new transaction.
*
* @param {!Array<string>} storeNames A list of strings that contains the
* transaction's scope, the object stores that this transaction can operate
* on.
* @param {goog.db.Transaction.TransactionMode=} opt_mode The mode of the
* transaction. If not present, the default is READ_ONLY.
* @return {!goog.db.Transaction} The wrapper for the newly created transaction.
* @throws {goog.db.Error} If there's a problem creating the transaction.
*/
goog.db.IndexedDb.prototype.createTransaction = function(storeNames, opt_mode) {
try {
// IndexedDB on Chrome 22+ requires that opt_mode not be passed rather than
// be explicitly passed as undefined.
var transaction = opt_mode ? this.db_.transaction(storeNames, opt_mode) :
this.db_.transaction(storeNames);
return new goog.db.Transaction(transaction, this);
} catch (ex) {
throw goog.db.Error.fromException(ex, 'creating transaction');
}
};
/** @override */
goog.db.IndexedDb.prototype.disposeInternal = function() {
goog.db.IndexedDb.base(this, 'disposeInternal');
this.eventHandler_.dispose();
};
/**
* Event types fired by a database.
*
* @enum {string} The event types for the web socket.
*/
goog.db.IndexedDb.EventType = {
/**
* Fired when a transaction is aborted and the event bubbles to its database.
*/
ABORT: 'abort',
/**
* Fired when the database connection is forcibly closed by the browser,
* without an explicit call to IDBDatabase#close. This behavior is not in the
* spec yet but will be added since it is necessary, see
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=22540.
*/
CLOSE: 'close',
/**
* Fired when a transaction has an error.
*/
ERROR: 'error',
/**
* Fired when someone (possibly in another window) is attempting to modify the
* structure of the database. Since a change can only be made when there are
* no active database connections, this usually means that the database should
* be closed so that the other client can make its changes.
*/
VERSION_CHANGE: 'versionchange'
};
/**
* Event representing a (possibly attempted) change in the database structure.
*
* At time of writing, no Chrome versions support oldVersion or newVersion. See
* http://crbug.com/153122.
*
* @param {number} oldVersion The previous version of the database.
* @param {number} newVersion The version the database is being or has been
* updated to.
* @constructor
* @extends {goog.events.Event}
* @final
*/
goog.db.IndexedDb.VersionChangeEvent = function(oldVersion, newVersion) {
goog.db.IndexedDb.VersionChangeEvent.base(
this, 'constructor', goog.db.IndexedDb.EventType.VERSION_CHANGE);
/**
* The previous version of the database.
* @type {number}
*/
this.oldVersion = oldVersion;
/**
* The version the database is being or has been updated to.
* @type {number}
*/
this.newVersion = newVersion;
};
goog.inherits(goog.db.IndexedDb.VersionChangeEvent, goog.events.Event);
|
version https://git-lfs.github.com/spec/v1
oid sha256:cb99cdf338f4cf391995c90fe5da7c4ca989bfc54ed7dfd0b63ebfa2cba1897e
size 1518
|
(function (root, factory) {
// Browser Global.
if(typeof root.navigator === "object") {
if (!root.Terraformer){
throw new Error("Terraformer.GeoStore.LocalStorage requires the core Terraformer library. https://github.com/esri/Terraformer");
}
if (!root.Terraformer.GeoStore){
throw new Error("Terraformer.GeoStore.LocalStorage requires the Terraformer GeoStore library. https://github.com/esri/terraformer-geostore");
}
root.Terraformer.GeoStore.LocalStorage = factory(root.Terraformer).LocalStorage;
}
}(this, function() {
var exports = { };
var callback;
// These methods get called in context of the geostore
function LocalStorage(){
var opts = arguments[0] || {};
this._key = opts.key || "_terraformer";
}
// store the data at id returns true if stored successfully
LocalStorage.prototype.add = function(geojson, callback){
if(geojson.type === "FeatureCollection"){
for (var i = 0; i < geojson.features.length; i++) {
this.set(geojson.features[i]);
}
} else {
this.set(geojson);
}
if (callback) {
callback( null, geojson );
}
};
LocalStorage.prototype.key = function(id){
return this._key +"_"+id;
};
// remove the data from the index and data with id returns true if removed successfully.
LocalStorage.prototype.remove = function( id, callback ){
localStorage.removeItem( this.key( id ) );
if (callback) {
callback( null, id );
}
};
// return the data stored at id
LocalStorage.prototype.get = function(id, callback){
if (callback) {
callback( null, JSON.parse(localStorage.getItem(this.key(id))));
}
};
LocalStorage.prototype.set = function(feature){
localStorage.setItem(this.key(feature.id), JSON.stringify(feature));
};
LocalStorage.prototype.update = function(geojson, callback){
this.set(geojson);
if (callback) {
callback( null, geojson );
}
};
LocalStorage.prototype.serialize = function(callback){
var objs = [];
for (var key in localStorage){
if(key.match(this._key)){
objs.push(JSON.parse(localStorage.getItem(key)));
}
}
if (callback) {
callback(null, JSON.stringify(objs));
}
};
LocalStorage.prototype.deserialize = function(serial, callback){
var data = JSON.parse(serial);
for (var i = data.length - 1; i >= 0; i--) {
this.set(data[i]);
}
if (callback) {
callback();
}
};
exports.LocalStorage = LocalStorage;
return exports;
}));
|
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
(function (global) {
"use strict";
if (typeof (WinJS) !== "undefined") {
WinJS.UI.Pages.define("$(TESTDATA)/FragmentControlNotSelfHost.html", {
init: function () {
this.runWithoutSelfHost = true;
}
});
}
}(this)); |
(function ($) {
$.Redactor.opts.langs['by'] = {
html: 'Код',
video: 'Відэа',
image: 'Малюнак',
table: 'Табліца',
link: 'Спасылка',
link_insert: 'Уставіць спасылку ...',
link_edit: 'Edit link',
unlink: 'Выдаліць спасылку',
formatting: 'Стылі',
paragraph: 'Звычайны тэкст',
quote: 'Цытата',
code: 'Код',
header1: 'Загаловак 1',
header2: 'Загаловак 2',
bold: 'Паўтлусты',
italic: 'Нахільны',
fontcolor: 'Колер тэксту',
backcolor: 'Заліванне тэксту',
unorderedlist: 'Звычайны спіс',
orderedlist: 'Нумараваны спіс',
outdent: 'Паменьшыць водступ',
indent: 'Павялічыць водступ',
cancel: 'Адмяніць',
insert: 'Уставіць',
save: 'Захаваць',
_delete: 'Выдаліць',
insert_table: 'Уставіць табліцу',
insert_row_above: 'Дадаць радок зверху',
insert_row_below: 'Дадаць радок знізу',
insert_column_left: 'Дадаць слупок злева',
insert_column_right: 'Дадаць слупок справа',
delete_column: 'Выдаліць слупок',
delete_row: 'Выдаліць радок',
delete_table: 'Выдаліць табліцу',
rows: 'Радкі',
columns: 'Стаўбцы',
add_head: 'Дадаць загаловак',
delete_head: 'Выдаліць загаловак',
title: 'Падказка',
image_view: 'Запампаваць малюнак',
image_position: 'Абцяканне тэкстам',
none: 'Няма',
left: 'Злева',
right: 'Справа',
image_web_link: 'Спасылка на малюнак',
text: 'Тэкст',
mailto: 'Эл. пошта ',
web: 'URL',
video_html_code: 'Код відэа роліка',
file: 'Файл',
upload: 'Загрузіць',
download: 'Запампаваць',
choose: 'Выбраць',
or_choose: 'Ці іншае',
drop_file_here: 'Перацягніце файл сюды',
align_left: 'Па левым краі',
align_center: 'Па цэнтры',
align_right: 'Па правым краі',
align_justify: 'Выраўнаваць тэкст па шырыні',
horizontalrule: 'Гарызантальная лінейка',
fullscreen: 'Ва ўвесь экран',
deleted: 'Закрэслены',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit'
};
})( jQuery ); |
module.exports={title:"Infiniti",slug:"infiniti",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Infiniti icon</title><path d="M6.893 14.606C5.17 14.46 2.18 13.33 2.18 11.359c0-2.5 4.343-4.818 9.819-4.818 5.75 0 9.82 2.318 9.82 4.818 0 1.97-2.978 3.087-4.702 3.233-.475-.609-5.118-6.791-5.118-6.791s-4.662 6.232-5.106 6.805zm13.744 2.115C22.921 15.6 24 13.734 24 12.088c0-3.533-4.928-6.264-12.001-6.264C4.927 5.824 0 8.555 0 12.088c0 1.646 1.079 3.511 3.363 4.633 2.118 1.041 5.116 1.403 5.55 1.455l3.086-8.982 3.118 8.982c.432-.052 3.401-.414 5.52-1.455z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.infinitiusa.com",hex:"000000",guidelines:void 0,license:void 0}; |
._1_1
|
/*!
* # Semantic UI - Dropdown
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
window = (typeof window != 'undefined' && window.Math == Math)
? window
: (typeof self != 'undefined' && self.Math == Math)
? self
: Function('return this')()
;
$.fn.dropdown = function(parameters) {
var
$allModules = $(this),
$document = $(document),
moduleSelector = $allModules.selector || '',
hasTouch = ('ontouchstart' in document.documentElement),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function(elementIndex) {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.dropdown.settings, parameters)
: $.extend({}, $.fn.dropdown.settings),
className = settings.className,
message = settings.message,
fields = settings.fields,
keys = settings.keys,
metadata = settings.metadata,
namespace = settings.namespace,
regExp = settings.regExp,
selector = settings.selector,
error = settings.error,
templates = settings.templates,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$text = $module.find(selector.text),
$search = $module.find(selector.search),
$sizer = $module.find(selector.sizer),
$input = $module.find(selector.input),
$icon = $module.find(selector.icon),
$combo = ($module.prev().find(selector.text).length > 0)
? $module.prev().find(selector.text)
: $module.prev(),
$menu = $module.children(selector.menu),
$item = $menu.find(selector.item),
activated = false,
itemActivated = false,
internalChange = false,
element = this,
instance = $module.data(moduleNamespace),
initialLoad,
pageLostFocus,
willRefocus,
elementNamespace,
id,
selectObserver,
menuObserver,
module
;
module = {
initialize: function() {
module.debug('Initializing dropdown', settings);
if( module.is.alreadySetup() ) {
module.setup.reference();
}
else {
module.setup.layout();
module.refreshData();
module.save.defaults();
module.restore.selected();
module.create.id();
module.bind.events();
module.observeChanges();
module.instantiate();
}
},
instantiate: function() {
module.verbose('Storing instance of dropdown', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous dropdown', $module);
module.remove.tabbable();
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
$menu
.off(eventNamespace)
;
$document
.off(elementNamespace)
;
module.disconnect.menuObserver();
module.disconnect.selectObserver();
},
observeChanges: function() {
if('MutationObserver' in window) {
selectObserver = new MutationObserver(module.event.select.mutation);
menuObserver = new MutationObserver(module.event.menu.mutation);
module.debug('Setting up mutation observer', selectObserver, menuObserver);
module.observe.select();
module.observe.menu();
}
},
disconnect: {
menuObserver: function() {
if(menuObserver) {
menuObserver.disconnect();
}
},
selectObserver: function() {
if(selectObserver) {
selectObserver.disconnect();
}
}
},
observe: {
select: function() {
if(module.has.input()) {
selectObserver.observe($input[0], {
childList : true,
subtree : true
});
}
},
menu: function() {
if(module.has.menu()) {
menuObserver.observe($menu[0], {
childList : true,
subtree : true
});
}
}
},
create: {
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2, 8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
},
userChoice: function(values) {
var
$userChoices,
$userChoice,
isUserValue,
html
;
values = values || module.get.userValues();
if(!values) {
return false;
}
values = $.isArray(values)
? values
: [values]
;
$.each(values, function(index, value) {
if(module.get.item(value) === false) {
html = settings.templates.addition( module.add.variables(message.addResult, value) );
$userChoice = $('<div />')
.html(html)
.attr('data-' + metadata.value, value)
.attr('data-' + metadata.text, value)
.addClass(className.addition)
.addClass(className.item)
;
if(settings.hideAdditions) {
$userChoice.addClass(className.hidden);
}
$userChoices = ($userChoices === undefined)
? $userChoice
: $userChoices.add($userChoice)
;
module.verbose('Creating user choices for value', value, $userChoice);
}
});
return $userChoices;
},
userLabels: function(value) {
var
userValues = module.get.userValues()
;
if(userValues) {
module.debug('Adding user labels', userValues);
$.each(userValues, function(index, value) {
module.verbose('Adding custom user value');
module.add.label(value, value);
});
}
},
menu: function() {
$menu = $('<div />')
.addClass(className.menu)
.appendTo($module)
;
},
sizer: function() {
$sizer = $('<span />')
.addClass(className.sizer)
.insertAfter($search)
;
}
},
search: function(query) {
query = (query !== undefined)
? query
: module.get.query()
;
module.verbose('Searching for query', query);
if(module.has.minCharacters(query)) {
module.filter(query);
}
else {
module.hide();
}
},
select: {
firstUnfiltered: function() {
module.verbose('Selecting first non-filtered element');
module.remove.selectedItem();
$item
.not(selector.unselectable)
.not(selector.addition + selector.hidden)
.eq(0)
.addClass(className.selected)
;
},
nextAvailable: function($selected) {
$selected = $selected.eq(0);
var
$nextAvailable = $selected.nextAll(selector.item).not(selector.unselectable).eq(0),
$prevAvailable = $selected.prevAll(selector.item).not(selector.unselectable).eq(0),
hasNext = ($nextAvailable.length > 0)
;
if(hasNext) {
module.verbose('Moving selection to', $nextAvailable);
$nextAvailable.addClass(className.selected);
}
else {
module.verbose('Moving selection to', $prevAvailable);
$prevAvailable.addClass(className.selected);
}
}
},
setup: {
api: function() {
var
apiSettings = {
debug : settings.debug,
urlData : {
value : module.get.value(),
query : module.get.query()
},
on : false
}
;
module.verbose('First request, initializing API');
$module
.api(apiSettings)
;
},
layout: function() {
if( $module.is('select') ) {
module.setup.select();
module.setup.returnedObject();
}
if( !module.has.menu() ) {
module.create.menu();
}
if( module.is.search() && !module.has.search() ) {
module.verbose('Adding search input');
$search = $('<input />')
.addClass(className.search)
.prop('autocomplete', 'off')
.insertBefore($text)
;
}
if( module.is.multiple() && module.is.searchSelection() && !module.has.sizer()) {
module.create.sizer();
}
if(settings.allowTab) {
module.set.tabbable();
}
},
select: function() {
var
selectValues = module.get.selectValues()
;
module.debug('Dropdown initialized on a select', selectValues);
if( $module.is('select') ) {
$input = $module;
}
// see if select is placed correctly already
if($input.parent(selector.dropdown).length > 0) {
module.debug('UI dropdown already exists. Creating dropdown menu only');
$module = $input.closest(selector.dropdown);
if( !module.has.menu() ) {
module.create.menu();
}
$menu = $module.children(selector.menu);
module.setup.menu(selectValues);
}
else {
module.debug('Creating entire dropdown from select');
$module = $('<div />')
.attr('class', $input.attr('class') )
.addClass(className.selection)
.addClass(className.dropdown)
.html( templates.dropdown(selectValues) )
.insertBefore($input)
;
if($input.hasClass(className.multiple) && $input.prop('multiple') === false) {
module.error(error.missingMultiple);
$input.prop('multiple', true);
}
if($input.is('[multiple]')) {
module.set.multiple();
}
if ($input.prop('disabled')) {
module.debug('Disabling dropdown');
$module.addClass(className.disabled);
}
$input
.removeAttr('class')
.detach()
.prependTo($module)
;
}
module.refresh();
},
menu: function(values) {
$menu.html( templates.menu(values, fields));
$item = $menu.find(selector.item);
},
reference: function() {
module.debug('Dropdown behavior was called on select, replacing with closest dropdown');
// replace module reference
$module = $module.parent(selector.dropdown);
module.refresh();
module.setup.returnedObject();
// invoke method in context of current instance
if(methodInvoked) {
instance = module;
module.invoke(query);
}
},
returnedObject: function() {
var
$firstModules = $allModules.slice(0, elementIndex),
$lastModules = $allModules.slice(elementIndex + 1)
;
// adjust all modules to use correct reference
$allModules = $firstModules.add($module).add($lastModules);
}
},
refresh: function() {
module.refreshSelectors();
module.refreshData();
},
refreshItems: function() {
$item = $menu.find(selector.item);
},
refreshSelectors: function() {
module.verbose('Refreshing selector cache');
$text = $module.find(selector.text);
$search = $module.find(selector.search);
$input = $module.find(selector.input);
$icon = $module.find(selector.icon);
$combo = ($module.prev().find(selector.text).length > 0)
? $module.prev().find(selector.text)
: $module.prev()
;
$menu = $module.children(selector.menu);
$item = $menu.find(selector.item);
},
refreshData: function() {
module.verbose('Refreshing cached metadata');
$item
.removeData(metadata.text)
.removeData(metadata.value)
;
},
clearData: function() {
module.verbose('Clearing metadata');
$item
.removeData(metadata.text)
.removeData(metadata.value)
;
$module
.removeData(metadata.defaultText)
.removeData(metadata.defaultValue)
.removeData(metadata.placeholderText)
;
},
toggle: function() {
module.verbose('Toggling menu visibility');
if( !module.is.active() ) {
module.show();
}
else {
module.hide();
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(!module.can.show() && module.is.remote()) {
module.debug('No API results retrieved, searching before show');
module.queryRemote(module.get.query(), module.show);
}
if( module.can.show() && !module.is.active() ) {
module.debug('Showing dropdown');
if(module.has.message() && !(module.has.maxSelections() || module.has.allResultsFiltered()) ) {
module.remove.message();
}
if(module.is.allFiltered()) {
return true;
}
if(settings.onShow.call(element) !== false) {
module.animate.show(function() {
if( module.can.click() ) {
module.bind.intent();
}
if(module.has.menuSearch()) {
module.focusSearch();
}
module.set.visible();
callback.call(element);
});
}
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.active() ) {
module.debug('Hiding dropdown');
if(settings.onHide.call(element) !== false) {
module.animate.hide(function() {
module.remove.visible();
callback.call(element);
});
}
}
},
hideOthers: function() {
module.verbose('Finding other dropdowns to hide');
$allModules
.not($module)
.has(selector.menu + '.' + className.visible)
.dropdown('hide')
;
},
hideMenu: function() {
module.verbose('Hiding menu instantaneously');
module.remove.active();
module.remove.visible();
$menu.transition('hide');
},
hideSubMenus: function() {
var
$subMenus = $menu.children(selector.item).find(selector.menu)
;
module.verbose('Hiding sub menus', $subMenus);
$subMenus.transition('hide');
},
bind: {
events: function() {
if(hasTouch) {
module.bind.touchEvents();
}
module.bind.keyboardEvents();
module.bind.inputEvents();
module.bind.mouseEvents();
},
touchEvents: function() {
module.debug('Touch device detected binding additional touch events');
if( module.is.searchSelection() ) {
// do nothing special yet
}
else if( module.is.single() ) {
$module
.on('touchstart' + eventNamespace, module.event.test.toggle)
;
}
$menu
.on('touchstart' + eventNamespace, selector.item, module.event.item.mouseenter)
;
},
keyboardEvents: function() {
module.verbose('Binding keyboard events');
$module
.on('keydown' + eventNamespace, module.event.keydown)
;
if( module.has.search() ) {
$module
.on(module.get.inputEvent() + eventNamespace, selector.search, module.event.input)
;
}
if( module.is.multiple() ) {
$document
.on('keydown' + elementNamespace, module.event.document.keydown)
;
}
},
inputEvents: function() {
module.verbose('Binding input change events');
$module
.on('change' + eventNamespace, selector.input, module.event.change)
;
},
mouseEvents: function() {
module.verbose('Binding mouse events');
if(module.is.multiple()) {
$module
.on('click' + eventNamespace, selector.label, module.event.label.click)
.on('click' + eventNamespace, selector.remove, module.event.remove.click)
;
}
if( module.is.searchSelection() ) {
$module
.on('mousedown' + eventNamespace, module.event.mousedown)
.on('mouseup' + eventNamespace, module.event.mouseup)
.on('mousedown' + eventNamespace, selector.menu, module.event.menu.mousedown)
.on('mouseup' + eventNamespace, selector.menu, module.event.menu.mouseup)
.on('click' + eventNamespace, selector.icon, module.event.icon.click)
.on('focus' + eventNamespace, selector.search, module.event.search.focus)
.on('click' + eventNamespace, selector.search, module.event.search.focus)
.on('blur' + eventNamespace, selector.search, module.event.search.blur)
.on('click' + eventNamespace, selector.text, module.event.text.focus)
;
if(module.is.multiple()) {
$module
.on('click' + eventNamespace, module.event.click)
;
}
}
else {
if(settings.on == 'click') {
$module
.on('click' + eventNamespace, selector.icon, module.event.icon.click)
.on('click' + eventNamespace, module.event.test.toggle)
;
}
else if(settings.on == 'hover') {
$module
.on('mouseenter' + eventNamespace, module.delay.show)
.on('mouseleave' + eventNamespace, module.delay.hide)
;
}
else {
$module
.on(settings.on + eventNamespace, module.toggle)
;
}
$module
.on('mousedown' + eventNamespace, module.event.mousedown)
.on('mouseup' + eventNamespace, module.event.mouseup)
.on('focus' + eventNamespace, module.event.focus)
;
if(module.has.menuSearch() ) {
$module
.on('blur' + eventNamespace, selector.search, module.event.search.blur)
;
}
else {
$module
.on('blur' + eventNamespace, module.event.blur)
;
}
}
$menu
.on('mouseenter' + eventNamespace, selector.item, module.event.item.mouseenter)
.on('mouseleave' + eventNamespace, selector.item, module.event.item.mouseleave)
.on('click' + eventNamespace, selector.item, module.event.item.click)
;
},
intent: function() {
module.verbose('Binding hide intent event to document');
if(hasTouch) {
$document
.on('touchstart' + elementNamespace, module.event.test.touch)
.on('touchmove' + elementNamespace, module.event.test.touch)
;
}
$document
.on('click' + elementNamespace, module.event.test.hide)
;
}
},
unbind: {
intent: function() {
module.verbose('Removing hide intent event from document');
if(hasTouch) {
$document
.off('touchstart' + elementNamespace)
.off('touchmove' + elementNamespace)
;
}
$document
.off('click' + elementNamespace)
;
}
},
filter: function(query) {
var
searchTerm = (query !== undefined)
? query
: module.get.query(),
afterFiltered = function() {
if(module.is.multiple()) {
module.filterActive();
}
module.select.firstUnfiltered();
if( module.has.allResultsFiltered() ) {
if( settings.onNoResults.call(element, searchTerm) ) {
if(settings.allowAdditions) {
if(settings.hideAdditions) {
module.verbose('User addition with no menu, setting empty style');
module.set.empty();
module.hideMenu();
}
}
else {
module.verbose('All items filtered, showing message', searchTerm);
module.add.message(message.noResults);
}
}
else {
module.verbose('All items filtered, hiding dropdown', searchTerm);
module.hideMenu();
}
}
else {
module.remove.empty();
module.remove.message();
}
if(settings.allowAdditions) {
module.add.userSuggestion(query);
}
if(module.is.searchSelection() && module.can.show() && module.is.focusedOnSearch() ) {
module.show();
}
}
;
if(settings.useLabels && module.has.maxSelections()) {
return;
}
if(settings.apiSettings) {
if( module.can.useAPI() ) {
module.queryRemote(searchTerm, function() {
if(settings.filterRemoteData) {
module.filterItems(searchTerm);
}
afterFiltered();
});
}
else {
module.error(error.noAPI);
}
}
else {
module.filterItems(searchTerm);
afterFiltered();
}
},
queryRemote: function(query, callback) {
var
apiSettings = {
errorDuration : false,
cache : 'local',
throttle : settings.throttle,
urlData : {
query: query
},
onError: function() {
module.add.message(message.serverError);
callback();
},
onFailure: function() {
module.add.message(message.serverError);
callback();
},
onSuccess : function(response) {
module.remove.message();
module.setup.menu({
values: response[fields.remoteValues]
});
callback();
}
}
;
if( !$module.api('get request') ) {
module.setup.api();
}
apiSettings = $.extend(true, {}, apiSettings, settings.apiSettings);
$module
.api('setting', apiSettings)
.api('query')
;
},
filterItems: function(query) {
var
searchTerm = (query !== undefined)
? query
: module.get.query(),
results = null,
escapedTerm = module.escape.string(searchTerm),
beginsWithRegExp = new RegExp('^' + escapedTerm, 'igm')
;
// avoid loop if we're matching nothing
if( module.has.query() ) {
results = [];
module.verbose('Searching for matching values', searchTerm);
$item
.each(function(){
var
$choice = $(this),
text,
value
;
if(settings.match == 'both' || settings.match == 'text') {
text = String(module.get.choiceText($choice, false));
if(text.search(beginsWithRegExp) !== -1) {
results.push(this);
return true;
}
else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, text)) {
results.push(this);
return true;
}
else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, text)) {
results.push(this);
return true;
}
}
if(settings.match == 'both' || settings.match == 'value') {
value = String(module.get.choiceValue($choice, text));
if(value.search(beginsWithRegExp) !== -1) {
results.push(this);
return true;
}
else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, value)) {
results.push(this);
return true;
}
else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, value)) {
results.push(this);
return true;
}
}
})
;
}
module.debug('Showing only matched items', searchTerm);
module.remove.filteredItem();
if(results) {
$item
.not(results)
.addClass(className.filtered)
;
}
},
fuzzySearch: function(query, term) {
var
termLength = term.length,
queryLength = query.length
;
query = query.toLowerCase();
term = term.toLowerCase();
if(queryLength > termLength) {
return false;
}
if(queryLength === termLength) {
return (query === term);
}
search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
var
queryCharacter = query.charCodeAt(characterIndex)
;
while(nextCharacterIndex < termLength) {
if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
continue search;
}
}
return false;
}
return true;
},
exactSearch: function (query, term) {
query = query.toLowerCase();
term = term.toLowerCase();
if(term.indexOf(query) > -1) {
return true;
}
return false;
},
filterActive: function() {
if(settings.useLabels) {
$item.filter('.' + className.active)
.addClass(className.filtered)
;
}
},
focusSearch: function(skipHandler) {
if( module.has.search() && !module.is.focusedOnSearch() ) {
if(skipHandler) {
$module.off('focus' + eventNamespace, selector.search);
$search.focus();
$module.on('focus' + eventNamespace, selector.search, module.event.search.focus);
}
else {
$search.focus();
}
}
},
forceSelection: function() {
var
$currentlySelected = $item.not(className.filtered).filter('.' + className.selected).eq(0),
$activeItem = $item.not(className.filtered).filter('.' + className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0)
? $currentlySelected
: $activeItem,
hasSelected = ($selectedItem.length > 0)
;
if(hasSelected && !module.is.multiple()) {
module.debug('Forcing partial selection to selected item', $selectedItem);
module.event.item.click.call($selectedItem, {}, true);
return;
}
else {
if(settings.allowAdditions) {
module.set.selected(module.get.query());
module.remove.searchTerm();
}
else {
module.remove.searchTerm();
}
}
},
event: {
change: function() {
if(!internalChange) {
module.debug('Input changed, updating selection');
module.set.selected();
}
},
focus: function() {
if(settings.showOnFocus && !activated && module.is.hidden() && !pageLostFocus) {
module.show();
}
},
blur: function(event) {
pageLostFocus = (document.activeElement === this);
if(!activated && !pageLostFocus) {
module.remove.activeLabel();
module.hide();
}
},
mousedown: function() {
if(module.is.searchSelection()) {
// prevent menu hiding on immediate re-focus
willRefocus = true;
}
else {
// prevents focus callback from occurring on mousedown
activated = true;
}
},
mouseup: function() {
if(module.is.searchSelection()) {
// prevent menu hiding on immediate re-focus
willRefocus = false;
}
else {
activated = false;
}
},
click: function(event) {
var
$target = $(event.target)
;
// focus search
if($target.is($module)) {
if(!module.is.focusedOnSearch()) {
module.focusSearch();
}
else {
module.show();
}
}
},
search: {
focus: function() {
activated = true;
if(module.is.multiple()) {
module.remove.activeLabel();
}
if(settings.showOnFocus) {
module.search();
}
},
blur: function(event) {
pageLostFocus = (document.activeElement === this);
if(!willRefocus) {
if(!itemActivated && !pageLostFocus) {
if(settings.forceSelection) {
module.forceSelection();
}
module.hide();
}
}
willRefocus = false;
}
},
icon: {
click: function(event) {
module.toggle();
}
},
text: {
focus: function(event) {
activated = true;
module.focusSearch();
}
},
input: function(event) {
if(module.is.multiple() || module.is.searchSelection()) {
module.set.filtered();
}
clearTimeout(module.timer);
module.timer = setTimeout(module.search, settings.delay.search);
},
label: {
click: function(event) {
var
$label = $(this),
$labels = $module.find(selector.label),
$activeLabels = $labels.filter('.' + className.active),
$nextActive = $label.nextAll('.' + className.active),
$prevActive = $label.prevAll('.' + className.active),
$range = ($nextActive.length > 0)
? $label.nextUntil($nextActive).add($activeLabels).add($label)
: $label.prevUntil($prevActive).add($activeLabels).add($label)
;
if(event.shiftKey) {
$activeLabels.removeClass(className.active);
$range.addClass(className.active);
}
else if(event.ctrlKey) {
$label.toggleClass(className.active);
}
else {
$activeLabels.removeClass(className.active);
$label.addClass(className.active);
}
settings.onLabelSelect.apply(this, $labels.filter('.' + className.active));
}
},
remove: {
click: function() {
var
$label = $(this).parent()
;
if( $label.hasClass(className.active) ) {
// remove all selected labels
module.remove.activeLabels();
}
else {
// remove this label only
module.remove.activeLabels( $label );
}
}
},
test: {
toggle: function(event) {
var
toggleBehavior = (module.is.multiple())
? module.show
: module.toggle
;
if(module.is.bubbledLabelClick(event) || module.is.bubbledIconClick(event)) {
return;
}
if( module.determine.eventOnElement(event, toggleBehavior) ) {
event.preventDefault();
}
},
touch: function(event) {
module.determine.eventOnElement(event, function() {
if(event.type == 'touchstart') {
module.timer = setTimeout(function() {
module.hide();
}, settings.delay.touch);
}
else if(event.type == 'touchmove') {
clearTimeout(module.timer);
}
});
event.stopPropagation();
},
hide: function(event) {
module.determine.eventInModule(event, module.hide);
}
},
select: {
mutation: function(mutations) {
module.debug('<select> modified, recreating menu');
module.setup.select();
}
},
menu: {
mutation: function(mutations) {
var
mutation = mutations[0],
$addedNode = mutation.addedNodes
? $(mutation.addedNodes[0])
: $(false),
$removedNode = mutation.removedNodes
? $(mutation.removedNodes[0])
: $(false),
$changedNodes = $addedNode.add($removedNode),
isUserAddition = $changedNodes.is(selector.addition) || $changedNodes.closest(selector.addition).length > 0,
isMessage = $changedNodes.is(selector.message) || $changedNodes.closest(selector.message).length > 0
;
if(isUserAddition || isMessage) {
module.debug('Updating item selector cache');
module.refreshItems();
}
else {
module.debug('Menu modified, updating selector cache');
module.refresh();
}
},
mousedown: function() {
itemActivated = true;
},
mouseup: function() {
itemActivated = false;
}
},
item: {
mouseenter: function(event) {
var
$target = $(event.target),
$item = $(this),
$subMenu = $item.children(selector.menu),
$otherMenus = $item.siblings(selector.item).children(selector.menu),
hasSubMenu = ($subMenu.length > 0),
isBubbledEvent = ($subMenu.find($target).length > 0)
;
if( !isBubbledEvent && hasSubMenu ) {
clearTimeout(module.itemTimer);
module.itemTimer = setTimeout(function() {
module.verbose('Showing sub-menu', $subMenu);
$.each($otherMenus, function() {
module.animate.hide(false, $(this));
});
module.animate.show(false, $subMenu);
}, settings.delay.show);
event.preventDefault();
}
},
mouseleave: function(event) {
var
$subMenu = $(this).children(selector.menu)
;
if($subMenu.length > 0) {
clearTimeout(module.itemTimer);
module.itemTimer = setTimeout(function() {
module.verbose('Hiding sub-menu', $subMenu);
module.animate.hide(false, $subMenu);
}, settings.delay.hide);
}
},
click: function (event, skipRefocus) {
var
$choice = $(this),
$target = (event)
? $(event.target)
: $(''),
$subMenu = $choice.find(selector.menu),
text = module.get.choiceText($choice),
value = module.get.choiceValue($choice, text),
hasSubMenu = ($subMenu.length > 0),
isBubbledEvent = ($subMenu.find($target).length > 0)
;
if(!isBubbledEvent && (!hasSubMenu || settings.allowCategorySelection)) {
if(module.is.searchSelection()) {
if(settings.allowAdditions) {
module.remove.userAddition();
}
module.remove.searchTerm();
if(!module.is.focusedOnSearch() && !(skipRefocus == true)) {
module.focusSearch(true);
}
}
if(!settings.useLabels) {
module.remove.filteredItem();
module.set.scrollPosition($choice);
}
module.determine.selectAction.call(this, text, value);
}
}
},
document: {
// label selection should occur even when element has no focus
keydown: function(event) {
var
pressedKey = event.which,
isShortcutKey = module.is.inObject(pressedKey, keys)
;
if(isShortcutKey) {
var
$label = $module.find(selector.label),
$activeLabel = $label.filter('.' + className.active),
activeValue = $activeLabel.data(metadata.value),
labelIndex = $label.index($activeLabel),
labelCount = $label.length,
hasActiveLabel = ($activeLabel.length > 0),
hasMultipleActive = ($activeLabel.length > 1),
isFirstLabel = (labelIndex === 0),
isLastLabel = (labelIndex + 1 == labelCount),
isSearch = module.is.searchSelection(),
isFocusedOnSearch = module.is.focusedOnSearch(),
isFocused = module.is.focused(),
caretAtStart = (isFocusedOnSearch && module.get.caretPosition() === 0),
$nextLabel
;
if(isSearch && !hasActiveLabel && !isFocusedOnSearch) {
return;
}
if(pressedKey == keys.leftArrow) {
// activate previous label
if((isFocused || caretAtStart) && !hasActiveLabel) {
module.verbose('Selecting previous label');
$label.last().addClass(className.active);
}
else if(hasActiveLabel) {
if(!event.shiftKey) {
module.verbose('Selecting previous label');
$label.removeClass(className.active);
}
else {
module.verbose('Adding previous label to selection');
}
if(isFirstLabel && !hasMultipleActive) {
$activeLabel.addClass(className.active);
}
else {
$activeLabel.prev(selector.siblingLabel)
.addClass(className.active)
.end()
;
}
event.preventDefault();
}
}
else if(pressedKey == keys.rightArrow) {
// activate first label
if(isFocused && !hasActiveLabel) {
$label.first().addClass(className.active);
}
// activate next label
if(hasActiveLabel) {
if(!event.shiftKey) {
module.verbose('Selecting next label');
$label.removeClass(className.active);
}
else {
module.verbose('Adding next label to selection');
}
if(isLastLabel) {
if(isSearch) {
if(!isFocusedOnSearch) {
module.focusSearch();
}
else {
$label.removeClass(className.active);
}
}
else if(hasMultipleActive) {
$activeLabel.next(selector.siblingLabel).addClass(className.active);
}
else {
$activeLabel.addClass(className.active);
}
}
else {
$activeLabel.next(selector.siblingLabel).addClass(className.active);
}
event.preventDefault();
}
}
else if(pressedKey == keys.deleteKey || pressedKey == keys.backspace) {
if(hasActiveLabel) {
module.verbose('Removing active labels');
if(isLastLabel) {
if(isSearch && !isFocusedOnSearch) {
module.focusSearch();
}
}
$activeLabel.last().next(selector.siblingLabel).addClass(className.active);
module.remove.activeLabels($activeLabel);
event.preventDefault();
}
else if(caretAtStart && !hasActiveLabel && pressedKey == keys.backspace) {
module.verbose('Removing last label on input backspace');
$activeLabel = $label.last().addClass(className.active);
module.remove.activeLabels($activeLabel);
}
}
else {
$activeLabel.removeClass(className.active);
}
}
}
},
keydown: function(event) {
var
pressedKey = event.which,
isShortcutKey = module.is.inObject(pressedKey, keys)
;
if(isShortcutKey) {
var
$currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0),
$activeItem = $menu.children('.' + className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0)
? $currentlySelected
: $activeItem,
$visibleItems = ($selectedItem.length > 0)
? $selectedItem.siblings(':not(.' + className.filtered +')').addBack()
: $menu.children(':not(.' + className.filtered +')'),
$subMenu = $selectedItem.children(selector.menu),
$parentMenu = $selectedItem.closest(selector.menu),
inVisibleMenu = ($parentMenu.hasClass(className.visible) || $parentMenu.hasClass(className.animating) || $parentMenu.parent(selector.menu).length > 0),
hasSubMenu = ($subMenu.length> 0),
hasSelectedItem = ($selectedItem.length > 0),
selectedIsSelectable = ($selectedItem.not(selector.unselectable).length > 0),
delimiterPressed = (pressedKey == keys.delimiter && settings.allowAdditions && module.is.multiple()),
isAdditionWithoutMenu = (settings.allowAdditions && settings.hideAdditions && (pressedKey == keys.enter || delimiterPressed) && selectedIsSelectable),
$nextItem,
isSubMenuItem,
newIndex
;
// allow selection with menu closed
if(isAdditionWithoutMenu) {
module.verbose('Selecting item from keyboard shortcut', $selectedItem);
module.event.item.click.call($selectedItem, event);
if(module.is.searchSelection()) {
module.remove.searchTerm();
}
}
// visible menu keyboard shortcuts
if( module.is.visible() ) {
// enter (select or open sub-menu)
if(pressedKey == keys.enter || delimiterPressed) {
if(pressedKey == keys.enter && hasSelectedItem && hasSubMenu && !settings.allowCategorySelection) {
module.verbose('Pressed enter on unselectable category, opening sub menu');
pressedKey = keys.rightArrow;
}
else if(selectedIsSelectable) {
module.verbose('Selecting item from keyboard shortcut', $selectedItem);
module.event.item.click.call($selectedItem, event);
if(module.is.searchSelection()) {
module.remove.searchTerm();
}
}
event.preventDefault();
}
// sub-menu actions
if(hasSelectedItem) {
if(pressedKey == keys.leftArrow) {
isSubMenuItem = ($parentMenu[0] !== $menu[0]);
if(isSubMenuItem) {
module.verbose('Left key pressed, closing sub-menu');
module.animate.hide(false, $parentMenu);
$selectedItem
.removeClass(className.selected)
;
$parentMenu
.closest(selector.item)
.addClass(className.selected)
;
event.preventDefault();
}
}
// right arrow (show sub-menu)
if(pressedKey == keys.rightArrow) {
if(hasSubMenu) {
module.verbose('Right key pressed, opening sub-menu');
module.animate.show(false, $subMenu);
$selectedItem
.removeClass(className.selected)
;
$subMenu
.find(selector.item).eq(0)
.addClass(className.selected)
;
event.preventDefault();
}
}
}
// up arrow (traverse menu up)
if(pressedKey == keys.upArrow) {
$nextItem = (hasSelectedItem && inVisibleMenu)
? $selectedItem.prevAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
: $item.eq(0)
;
if($visibleItems.index( $nextItem ) < 0) {
module.verbose('Up key pressed but reached top of current menu');
event.preventDefault();
return;
}
else {
module.verbose('Up key pressed, changing active item');
$selectedItem
.removeClass(className.selected)
;
$nextItem
.addClass(className.selected)
;
module.set.scrollPosition($nextItem);
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextItem);
}
}
event.preventDefault();
}
// down arrow (traverse menu down)
if(pressedKey == keys.downArrow) {
$nextItem = (hasSelectedItem && inVisibleMenu)
? $nextItem = $selectedItem.nextAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
: $item.eq(0)
;
if($nextItem.length === 0) {
module.verbose('Down key pressed but reached bottom of current menu');
event.preventDefault();
return;
}
else {
module.verbose('Down key pressed, changing active item');
$item
.removeClass(className.selected)
;
$nextItem
.addClass(className.selected)
;
module.set.scrollPosition($nextItem);
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextItem);
}
}
event.preventDefault();
}
// page down (show next page)
if(pressedKey == keys.pageUp) {
module.scrollPage('up');
event.preventDefault();
}
if(pressedKey == keys.pageDown) {
module.scrollPage('down');
event.preventDefault();
}
// escape (close menu)
if(pressedKey == keys.escape) {
module.verbose('Escape key pressed, closing dropdown');
module.hide();
}
}
else {
// delimiter key
if(delimiterPressed) {
event.preventDefault();
}
// down arrow (open menu)
if(pressedKey == keys.downArrow && !module.is.visible()) {
module.verbose('Down key pressed, showing dropdown');
module.select.firstUnfiltered();
module.show();
event.preventDefault();
}
}
}
else {
if( !module.has.search() ) {
module.set.selectedLetter( String.fromCharCode(pressedKey) );
}
}
}
},
trigger: {
change: function() {
var
events = document.createEvent('HTMLEvents'),
inputElement = $input[0]
;
if(inputElement) {
module.verbose('Triggering native change event');
events.initEvent('change', true, false);
inputElement.dispatchEvent(events);
}
}
},
determine: {
selectAction: function(text, value) {
module.verbose('Determining action', settings.action);
if( $.isFunction( module.action[settings.action] ) ) {
module.verbose('Triggering preset action', settings.action, text, value);
module.action[ settings.action ].call(element, text, value, this);
}
else if( $.isFunction(settings.action) ) {
module.verbose('Triggering user action', settings.action, text, value);
settings.action.call(element, text, value, this);
}
else {
module.error(error.action, settings.action);
}
},
eventInModule: function(event, callback) {
var
$target = $(event.target),
inDocument = ($target.closest(document.documentElement).length > 0),
inModule = ($target.closest($module).length > 0)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(inDocument && !inModule) {
module.verbose('Triggering event', callback);
callback();
return true;
}
else {
module.verbose('Event occurred in dropdown, canceling callback');
return false;
}
},
eventOnElement: function(event, callback) {
var
$target = $(event.target),
$label = $target.closest(selector.siblingLabel),
inVisibleDOM = document.body.contains(event.target),
notOnLabel = ($module.find($label).length === 0),
notInMenu = ($target.closest($menu).length === 0)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(inVisibleDOM && notOnLabel && notInMenu) {
module.verbose('Triggering event', callback);
callback();
return true;
}
else {
module.verbose('Event occurred in dropdown menu, canceling callback');
return false;
}
}
},
action: {
nothing: function() {},
activate: function(text, value, element) {
value = (value !== undefined)
? value
: text
;
if( module.can.activate( $(element) ) ) {
module.set.selected(value, $(element));
if(module.is.multiple() && !module.is.allFiltered()) {
return;
}
else {
module.hideAndClear();
}
}
},
select: function(text, value, element) {
value = (value !== undefined)
? value
: text
;
if( module.can.activate( $(element) ) ) {
module.set.value(value, $(element));
if(module.is.multiple() && !module.is.allFiltered()) {
return;
}
else {
module.hideAndClear();
}
}
},
combo: function(text, value, element) {
value = (value !== undefined)
? value
: text
;
module.set.selected(value, $(element));
module.hideAndClear();
},
hide: function(text, value, element) {
module.set.value(value, text);
module.hideAndClear();
}
},
get: {
id: function() {
return id;
},
defaultText: function() {
return $module.data(metadata.defaultText);
},
defaultValue: function() {
return $module.data(metadata.defaultValue);
},
placeholderText: function() {
return $module.data(metadata.placeholderText) || '';
},
text: function() {
return $text.text();
},
query: function() {
return $.trim($search.val());
},
searchWidth: function(value) {
value = (value !== undefined)
? value
: $search.val()
;
$sizer.text(value);
// prevent rounding issues
return Math.ceil( $sizer.width() + 1);
},
selectionCount: function() {
var
values = module.get.values(),
count
;
count = ( module.is.multiple() )
? $.isArray(values)
? values.length
: 0
: (module.get.value() !== '')
? 1
: 0
;
return count;
},
transition: function($subMenu) {
return (settings.transition == 'auto')
? module.is.upward($subMenu)
? 'slide up'
: 'slide down'
: settings.transition
;
},
userValues: function() {
var
values = module.get.values()
;
if(!values) {
return false;
}
values = $.isArray(values)
? values
: [values]
;
return $.grep(values, function(value) {
return (module.get.item(value) === false);
});
},
uniqueArray: function(array) {
return $.grep(array, function (value, index) {
return $.inArray(value, array) === index;
});
},
caretPosition: function() {
var
input = $search.get(0),
range,
rangeLength
;
if('selectionStart' in input) {
return input.selectionStart;
}
else if (document.selection) {
input.focus();
range = document.selection.createRange();
rangeLength = range.text.length;
range.moveStart('character', -input.value.length);
return range.text.length - rangeLength;
}
},
value: function() {
var
value = ($input.length > 0)
? $input.val()
: $module.data(metadata.value),
isEmptyMultiselect = ($.isArray(value) && value.length === 1 && value[0] === '')
;
// prevents placeholder element from being selected when multiple
return (value === undefined || isEmptyMultiselect)
? ''
: value
;
},
values: function() {
var
value = module.get.value()
;
if(value === '') {
return '';
}
return ( !module.has.selectInput() && module.is.multiple() )
? (typeof value == 'string') // delimited string
? value.split(settings.delimiter)
: ''
: value
;
},
remoteValues: function() {
var
values = module.get.values(),
remoteValues = false
;
if(values) {
if(typeof values == 'string') {
values = [values];
}
$.each(values, function(index, value) {
var
name = module.read.remoteData(value)
;
module.verbose('Restoring value from session data', name, value);
if(name) {
if(!remoteValues) {
remoteValues = {};
}
remoteValues[value] = name;
}
});
}
return remoteValues;
},
choiceText: function($choice, preserveHTML) {
preserveHTML = (preserveHTML !== undefined)
? preserveHTML
: settings.preserveHTML
;
if($choice) {
if($choice.find(selector.menu).length > 0) {
module.verbose('Retrieving text of element with sub-menu');
$choice = $choice.clone();
$choice.find(selector.menu).remove();
$choice.find(selector.menuIcon).remove();
}
return ($choice.data(metadata.text) !== undefined)
? $choice.data(metadata.text)
: (preserveHTML)
? $.trim($choice.html())
: $.trim($choice.text())
;
}
},
choiceValue: function($choice, choiceText) {
choiceText = choiceText || module.get.choiceText($choice);
if(!$choice) {
return false;
}
return ($choice.data(metadata.value) !== undefined)
? String( $choice.data(metadata.value) )
: (typeof choiceText === 'string')
? $.trim(choiceText.toLowerCase())
: String(choiceText)
;
},
inputEvent: function() {
var
input = $search[0]
;
if(input) {
return (input.oninput !== undefined)
? 'input'
: (input.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
}
return false;
},
selectValues: function() {
var
select = {}
;
select.values = [];
$module
.find('option')
.each(function() {
var
$option = $(this),
name = $option.html(),
disabled = $option.attr('disabled'),
value = ( $option.attr('value') !== undefined )
? $option.attr('value')
: name
;
if(settings.placeholder === 'auto' && value === '') {
select.placeholder = name;
}
else {
select.values.push({
name : name,
value : value,
disabled : disabled
});
}
})
;
if(settings.placeholder && settings.placeholder !== 'auto') {
module.debug('Setting placeholder value to', settings.placeholder);
select.placeholder = settings.placeholder;
}
if(settings.sortSelect) {
select.values.sort(function(a, b) {
return (a.name > b.name)
? 1
: -1
;
});
module.debug('Retrieved and sorted values from select', select);
}
else {
module.debug('Retrieved values from select', select);
}
return select;
},
activeItem: function() {
return $item.filter('.' + className.active);
},
selectedItem: function() {
var
$selectedItem = $item.not(selector.unselectable).filter('.' + className.selected)
;
return ($selectedItem.length > 0)
? $selectedItem
: $item.eq(0)
;
},
itemWithAdditions: function(value) {
var
$items = module.get.item(value),
$userItems = module.create.userChoice(value),
hasUserItems = ($userItems && $userItems.length > 0)
;
if(hasUserItems) {
$items = ($items.length > 0)
? $items.add($userItems)
: $userItems
;
}
return $items;
},
item: function(value, strict) {
var
$selectedItem = false,
shouldSearch,
isMultiple
;
value = (value !== undefined)
? value
: ( module.get.values() !== undefined)
? module.get.values()
: module.get.text()
;
shouldSearch = (isMultiple)
? (value.length > 0)
: (value !== undefined && value !== null)
;
isMultiple = (module.is.multiple() && $.isArray(value));
strict = (value === '' || value === 0)
? true
: strict || false
;
if(shouldSearch) {
$item
.each(function() {
var
$choice = $(this),
optionText = module.get.choiceText($choice),
optionValue = module.get.choiceValue($choice, optionText)
;
// safe early exit
if(optionValue === null || optionValue === undefined) {
return;
}
if(isMultiple) {
if($.inArray( String(optionValue), value) !== -1 || $.inArray(optionText, value) !== -1) {
$selectedItem = ($selectedItem)
? $selectedItem.add($choice)
: $choice
;
}
}
else if(strict) {
module.verbose('Ambiguous dropdown value using strict type check', $choice, value);
if( optionValue === value || optionText === value) {
$selectedItem = $choice;
return true;
}
}
else {
if( String(optionValue) == String(value) || optionText == value) {
module.verbose('Found select item by value', optionValue, value);
$selectedItem = $choice;
return true;
}
}
})
;
}
return $selectedItem;
}
},
check: {
maxSelections: function(selectionCount) {
if(settings.maxSelections) {
selectionCount = (selectionCount !== undefined)
? selectionCount
: module.get.selectionCount()
;
if(selectionCount >= settings.maxSelections) {
module.debug('Maximum selection count reached');
if(settings.useLabels) {
$item.addClass(className.filtered);
module.add.message(message.maxSelections);
}
return true;
}
else {
module.verbose('No longer at maximum selection count');
module.remove.message();
module.remove.filteredItem();
if(module.is.searchSelection()) {
module.filterItems();
}
return false;
}
}
return true;
}
},
restore: {
defaults: function() {
module.clear();
module.restore.defaultText();
module.restore.defaultValue();
},
defaultText: function() {
var
defaultText = module.get.defaultText(),
placeholderText = module.get.placeholderText
;
if(defaultText === placeholderText) {
module.debug('Restoring default placeholder text', defaultText);
module.set.placeholderText(defaultText);
}
else {
module.debug('Restoring default text', defaultText);
module.set.text(defaultText);
}
},
placeholderText: function() {
module.set.placeholderText();
},
defaultValue: function() {
var
defaultValue = module.get.defaultValue()
;
if(defaultValue !== undefined) {
module.debug('Restoring default value', defaultValue);
if(defaultValue !== '') {
module.set.value(defaultValue);
module.set.selected();
}
else {
module.remove.activeItem();
module.remove.selectedItem();
}
}
},
labels: function() {
if(settings.allowAdditions) {
if(!settings.useLabels) {
module.error(error.labels);
settings.useLabels = true;
}
module.debug('Restoring selected values');
module.create.userLabels();
}
module.check.maxSelections();
},
selected: function() {
module.restore.values();
if(module.is.multiple()) {
module.debug('Restoring previously selected values and labels');
module.restore.labels();
}
else {
module.debug('Restoring previously selected values');
}
},
values: function() {
// prevents callbacks from occurring on initial load
module.set.initialLoad();
if(settings.apiSettings && settings.saveRemoteData && module.get.remoteValues()) {
module.restore.remoteValues();
}
else {
module.set.selected();
}
module.remove.initialLoad();
},
remoteValues: function() {
var
values = module.get.remoteValues()
;
module.debug('Recreating selected from session data', values);
if(values) {
if( module.is.single() ) {
$.each(values, function(value, name) {
module.set.text(name);
});
}
else {
$.each(values, function(value, name) {
module.add.label(value, name);
});
}
}
}
},
read: {
remoteData: function(value) {
var
name
;
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
name = sessionStorage.getItem(value);
return (name !== undefined)
? name
: false
;
}
},
save: {
defaults: function() {
module.save.defaultText();
module.save.placeholderText();
module.save.defaultValue();
},
defaultValue: function() {
var
value = module.get.value()
;
module.verbose('Saving default value as', value);
$module.data(metadata.defaultValue, value);
},
defaultText: function() {
var
text = module.get.text()
;
module.verbose('Saving default text as', text);
$module.data(metadata.defaultText, text);
},
placeholderText: function() {
var
text
;
if(settings.placeholder !== false && $text.hasClass(className.placeholder)) {
text = module.get.text();
module.verbose('Saving placeholder text as', text);
$module.data(metadata.placeholderText, text);
}
},
remoteData: function(name, value) {
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
module.verbose('Saving remote data to session storage', value, name);
sessionStorage.setItem(value, name);
}
},
clear: function() {
if(module.is.multiple() && settings.useLabels) {
module.remove.labels();
}
else {
module.remove.activeItem();
module.remove.selectedItem();
}
module.set.placeholderText();
module.clearValue();
},
clearValue: function() {
module.set.value('');
},
scrollPage: function(direction, $selectedItem) {
var
$currentItem = $selectedItem || module.get.selectedItem(),
$menu = $currentItem.closest(selector.menu),
menuHeight = $menu.outerHeight(),
currentScroll = $menu.scrollTop(),
itemHeight = $item.eq(0).outerHeight(),
itemsPerPage = Math.floor(menuHeight / itemHeight),
maxScroll = $menu.prop('scrollHeight'),
newScroll = (direction == 'up')
? currentScroll - (itemHeight * itemsPerPage)
: currentScroll + (itemHeight * itemsPerPage),
$selectableItem = $item.not(selector.unselectable),
isWithinRange,
$nextSelectedItem,
elementIndex
;
elementIndex = (direction == 'up')
? $selectableItem.index($currentItem) - itemsPerPage
: $selectableItem.index($currentItem) + itemsPerPage
;
isWithinRange = (direction == 'up')
? (elementIndex >= 0)
: (elementIndex < $selectableItem.length)
;
$nextSelectedItem = (isWithinRange)
? $selectableItem.eq(elementIndex)
: (direction == 'up')
? $selectableItem.first()
: $selectableItem.last()
;
if($nextSelectedItem.length > 0) {
module.debug('Scrolling page', direction, $nextSelectedItem);
$currentItem
.removeClass(className.selected)
;
$nextSelectedItem
.addClass(className.selected)
;
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextSelectedItem);
}
$menu
.scrollTop(newScroll)
;
}
},
set: {
filtered: function() {
var
isMultiple = module.is.multiple(),
isSearch = module.is.searchSelection(),
isSearchMultiple = (isMultiple && isSearch),
searchValue = (isSearch)
? module.get.query()
: '',
hasSearchValue = (typeof searchValue === 'string' && searchValue.length > 0),
searchWidth = module.get.searchWidth(),
valueIsSet = searchValue !== ''
;
if(isMultiple && hasSearchValue) {
module.verbose('Adjusting input width', searchWidth, settings.glyphWidth);
$search.css('width', searchWidth);
}
if(hasSearchValue || (isSearchMultiple && valueIsSet)) {
module.verbose('Hiding placeholder text');
$text.addClass(className.filtered);
}
else if(!isMultiple || (isSearchMultiple && !valueIsSet)) {
module.verbose('Showing placeholder text');
$text.removeClass(className.filtered);
}
},
empty: function() {
$module.addClass(className.empty);
},
loading: function() {
$module.addClass(className.loading);
},
placeholderText: function(text) {
text = text || module.get.placeholderText();
module.debug('Setting placeholder text', text);
module.set.text(text);
$text.addClass(className.placeholder);
},
tabbable: function() {
if( module.is.searchSelection() ) {
module.debug('Added tabindex to searchable dropdown');
$search
.val('')
.attr('tabindex', 0)
;
$menu
.attr('tabindex', -1)
;
}
else {
module.debug('Added tabindex to dropdown');
if( $module.attr('tabindex') === undefined) {
$module
.attr('tabindex', 0)
;
$menu
.attr('tabindex', -1)
;
}
}
},
initialLoad: function() {
module.verbose('Setting initial load');
initialLoad = true;
},
activeItem: function($item) {
if( settings.allowAdditions && $item.filter(selector.addition).length > 0 ) {
$item.addClass(className.filtered);
}
else {
$item.addClass(className.active);
}
},
partialSearch: function(text) {
var
length = module.get.query().length
;
$search.val( text.substr(0 , length));
},
scrollPosition: function($item, forceScroll) {
var
edgeTolerance = 5,
$menu,
hasActive,
offset,
itemHeight,
itemOffset,
menuOffset,
menuScroll,
menuHeight,
abovePage,
belowPage
;
$item = $item || module.get.selectedItem();
$menu = $item.closest(selector.menu);
hasActive = ($item && $item.length > 0);
forceScroll = (forceScroll !== undefined)
? forceScroll
: false
;
if($item && $menu.length > 0 && hasActive) {
itemOffset = $item.position().top;
$menu.addClass(className.loading);
menuScroll = $menu.scrollTop();
menuOffset = $menu.offset().top;
itemOffset = $item.offset().top;
offset = menuScroll - menuOffset + itemOffset;
if(!forceScroll) {
menuHeight = $menu.height();
belowPage = menuScroll + menuHeight < (offset + edgeTolerance);
abovePage = ((offset - edgeTolerance) < menuScroll);
}
module.debug('Scrolling to active item', offset);
if(forceScroll || abovePage || belowPage) {
$menu.scrollTop(offset);
}
$menu.removeClass(className.loading);
}
},
text: function(text) {
if(settings.action !== 'select') {
if(settings.action == 'combo') {
module.debug('Changing combo button text', text, $combo);
if(settings.preserveHTML) {
$combo.html(text);
}
else {
$combo.text(text);
}
}
else {
if(text !== module.get.placeholderText()) {
$text.removeClass(className.placeholder);
}
module.debug('Changing text', text, $text);
$text
.removeClass(className.filtered)
;
if(settings.preserveHTML) {
$text.html(text);
}
else {
$text.text(text);
}
}
}
},
selectedItem: function($item) {
var
value = module.get.choiceValue($item),
searchText = module.get.choiceText($item, false),
text = module.get.choiceText($item, true)
;
module.debug('Setting user selection to item', $item);
module.remove.activeItem();
module.set.partialSearch(searchText);
module.set.activeItem($item);
module.set.selected(value, $item);
module.set.text(text);
},
selectedLetter: function(letter) {
var
$selectedItem = $item.filter('.' + className.selected),
alreadySelectedLetter = $selectedItem.length > 0 && module.has.firstLetter($selectedItem, letter),
$nextValue = false,
$nextItem
;
// check next of same letter
if(alreadySelectedLetter) {
$nextItem = $selectedItem.nextAll($item).eq(0);
if( module.has.firstLetter($nextItem, letter) ) {
$nextValue = $nextItem;
}
}
// check all values
if(!$nextValue) {
$item
.each(function(){
if(module.has.firstLetter($(this), letter)) {
$nextValue = $(this);
return false;
}
})
;
}
// set next value
if($nextValue) {
module.verbose('Scrolling to next value with letter', letter);
module.set.scrollPosition($nextValue);
$selectedItem.removeClass(className.selected);
$nextValue.addClass(className.selected);
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextValue);
}
}
},
direction: function($menu) {
if(settings.direction == 'auto') {
if(module.is.onScreen($menu)) {
module.remove.upward($menu);
}
else {
module.set.upward($menu);
}
}
else if(settings.direction == 'upward') {
module.set.upward($menu);
}
},
upward: function($menu) {
var $element = $menu || $module;
$element.addClass(className.upward);
},
value: function(value, text, $selected) {
var
escapedValue = module.escape.value(value),
hasInput = ($input.length > 0),
isAddition = !module.has.value(value),
currentValue = module.get.values(),
stringValue = (value !== undefined)
? String(value)
: value,
newValue
;
if(hasInput) {
if(!settings.allowReselection && stringValue == currentValue) {
module.verbose('Skipping value update already same value', value, currentValue);
if(!module.is.initialLoad()) {
return;
}
}
if( module.is.single() && module.has.selectInput() && module.can.extendSelect() ) {
module.debug('Adding user option', value);
module.add.optionValue(value);
}
module.debug('Updating input value', escapedValue, currentValue);
internalChange = true;
$input
.val(escapedValue)
;
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.debug('Input native change event ignored on initial load');
}
else {
module.trigger.change();
}
internalChange = false;
}
else {
module.verbose('Storing value in metadata', escapedValue, $input);
if(escapedValue !== currentValue) {
$module.data(metadata.value, stringValue);
}
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('No callback on initial load', settings.onChange);
}
else {
settings.onChange.call(element, value, text, $selected);
}
},
active: function() {
$module
.addClass(className.active)
;
},
multiple: function() {
$module.addClass(className.multiple);
},
visible: function() {
$module.addClass(className.visible);
},
exactly: function(value, $selectedItem) {
module.debug('Setting selected to exact values');
module.clear();
module.set.selected(value, $selectedItem);
},
selected: function(value, $selectedItem) {
var
isMultiple = module.is.multiple(),
$userSelectedItem
;
$selectedItem = (settings.allowAdditions)
? $selectedItem || module.get.itemWithAdditions(value)
: $selectedItem || module.get.item(value)
;
if(!$selectedItem) {
return;
}
module.debug('Setting selected menu item to', $selectedItem);
if(module.is.multiple()) {
module.remove.searchWidth();
}
if(module.is.single()) {
module.remove.activeItem();
module.remove.selectedItem();
}
else if(settings.useLabels) {
module.remove.selectedItem();
}
// select each item
$selectedItem
.each(function() {
var
$selected = $(this),
selectedText = module.get.choiceText($selected),
selectedValue = module.get.choiceValue($selected, selectedText),
isFiltered = $selected.hasClass(className.filtered),
isActive = $selected.hasClass(className.active),
isUserValue = $selected.hasClass(className.addition),
shouldAnimate = (isMultiple && $selectedItem.length == 1)
;
if(isMultiple) {
if(!isActive || isUserValue) {
if(settings.apiSettings && settings.saveRemoteData) {
module.save.remoteData(selectedText, selectedValue);
}
if(settings.useLabels) {
module.add.value(selectedValue, selectedText, $selected);
module.add.label(selectedValue, selectedText, shouldAnimate);
module.set.activeItem($selected);
module.filterActive();
module.select.nextAvailable($selectedItem);
}
else {
module.add.value(selectedValue, selectedText, $selected);
module.set.text(module.add.variables(message.count));
module.set.activeItem($selected);
}
}
else if(!isFiltered) {
module.debug('Selected active value, removing label');
module.remove.selected(selectedValue);
}
}
else {
if(settings.apiSettings && settings.saveRemoteData) {
module.save.remoteData(selectedText, selectedValue);
}
module.set.text(selectedText);
module.set.value(selectedValue, selectedText, $selected);
$selected
.addClass(className.active)
.addClass(className.selected)
;
}
})
;
}
},
add: {
label: function(value, text, shouldAnimate) {
var
$next = module.is.searchSelection()
? $search
: $text,
escapedValue = module.escape.value(value),
$label
;
$label = $('<a />')
.addClass(className.label)
.attr('data-' + metadata.value, escapedValue)
.html(templates.label(escapedValue, text))
;
$label = settings.onLabelCreate.call($label, escapedValue, text);
if(module.has.label(value)) {
module.debug('Label already exists, skipping', escapedValue);
return;
}
if(settings.label.variation) {
$label.addClass(settings.label.variation);
}
if(shouldAnimate === true) {
module.debug('Animating in label', $label);
$label
.addClass(className.hidden)
.insertBefore($next)
.transition(settings.label.transition, settings.label.duration)
;
}
else {
module.debug('Adding selection label', $label);
$label
.insertBefore($next)
;
}
},
message: function(message) {
var
$message = $menu.children(selector.message),
html = settings.templates.message(module.add.variables(message))
;
if($message.length > 0) {
$message
.html(html)
;
}
else {
$message = $('<div/>')
.html(html)
.addClass(className.message)
.appendTo($menu)
;
}
},
optionValue: function(value) {
var
escapedValue = module.escape.value(value),
$option = $input.find('option[value="' + module.escape.string(escapedValue) + '"]'),
hasOption = ($option.length > 0)
;
if(hasOption) {
return;
}
// temporarily disconnect observer
module.disconnect.selectObserver();
if( module.is.single() ) {
module.verbose('Removing previous user addition');
$input.find('option.' + className.addition).remove();
}
$('<option/>')
.prop('value', escapedValue)
.addClass(className.addition)
.html(value)
.appendTo($input)
;
module.verbose('Adding user addition as an <option>', value);
module.observe.select();
},
userSuggestion: function(value) {
var
$addition = $menu.children(selector.addition),
$existingItem = module.get.item(value),
alreadyHasValue = $existingItem && $existingItem.not(selector.addition).length,
hasUserSuggestion = $addition.length > 0,
html
;
if(settings.useLabels && module.has.maxSelections()) {
return;
}
if(value === '' || alreadyHasValue) {
$addition.remove();
return;
}
if(hasUserSuggestion) {
$addition
.data(metadata.value, value)
.data(metadata.text, value)
.attr('data-' + metadata.value, value)
.attr('data-' + metadata.text, value)
.removeClass(className.filtered)
;
if(!settings.hideAdditions) {
html = settings.templates.addition( module.add.variables(message.addResult, value) );
$addition
.html(html)
;
}
module.verbose('Replacing user suggestion with new value', $addition);
}
else {
$addition = module.create.userChoice(value);
$addition
.prependTo($menu)
;
module.verbose('Adding item choice to menu corresponding with user choice addition', $addition);
}
if(!settings.hideAdditions || module.is.allFiltered()) {
$addition
.addClass(className.selected)
.siblings()
.removeClass(className.selected)
;
}
module.refreshItems();
},
variables: function(message, term) {
var
hasCount = (message.search('{count}') !== -1),
hasMaxCount = (message.search('{maxCount}') !== -1),
hasTerm = (message.search('{term}') !== -1),
values,
count,
query
;
module.verbose('Adding templated variables to message', message);
if(hasCount) {
count = module.get.selectionCount();
message = message.replace('{count}', count);
}
if(hasMaxCount) {
count = module.get.selectionCount();
message = message.replace('{maxCount}', settings.maxSelections);
}
if(hasTerm) {
query = term || module.get.query();
message = message.replace('{term}', query);
}
return message;
},
value: function(addedValue, addedText, $selectedItem) {
var
currentValue = module.get.values(),
newValue
;
if(addedValue === '') {
module.debug('Cannot select blank values from multiselect');
return;
}
// extend current array
if($.isArray(currentValue)) {
newValue = currentValue.concat([addedValue]);
newValue = module.get.uniqueArray(newValue);
}
else {
newValue = [addedValue];
}
// add values
if( module.has.selectInput() ) {
if(module.can.extendSelect()) {
module.debug('Adding value to select', addedValue, newValue, $input);
module.add.optionValue(addedValue);
}
}
else {
newValue = newValue.join(settings.delimiter);
module.debug('Setting hidden input to delimited value', newValue, $input);
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('Skipping onadd callback on initial load', settings.onAdd);
}
else {
settings.onAdd.call(element, addedValue, addedText, $selectedItem);
}
module.set.value(newValue, addedValue, addedText, $selectedItem);
module.check.maxSelections();
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
activeLabel: function() {
$module.find(selector.label).removeClass(className.active);
},
empty: function() {
$module.removeClass(className.empty);
},
loading: function() {
$module.removeClass(className.loading);
},
initialLoad: function() {
initialLoad = false;
},
upward: function($menu) {
var $element = $menu || $module;
$element.removeClass(className.upward);
},
visible: function() {
$module.removeClass(className.visible);
},
activeItem: function() {
$item.removeClass(className.active);
},
filteredItem: function() {
if(settings.useLabels && module.has.maxSelections() ) {
return;
}
if(settings.useLabels && module.is.multiple()) {
$item.not('.' + className.active).removeClass(className.filtered);
}
else {
$item.removeClass(className.filtered);
}
module.remove.empty();
},
optionValue: function(value) {
var
escapedValue = module.escape.value(value),
$option = $input.find('option[value="' + module.escape.string(escapedValue) + '"]'),
hasOption = ($option.length > 0)
;
if(!hasOption || !$option.hasClass(className.addition)) {
return;
}
// temporarily disconnect observer
if(selectObserver) {
selectObserver.disconnect();
module.verbose('Temporarily disconnecting mutation observer');
}
$option.remove();
module.verbose('Removing user addition as an <option>', escapedValue);
if(selectObserver) {
selectObserver.observe($input[0], {
childList : true,
subtree : true
});
}
},
message: function() {
$menu.children(selector.message).remove();
},
searchWidth: function() {
$search.css('width', '');
},
searchTerm: function() {
module.verbose('Cleared search term');
$search.val('');
module.set.filtered();
},
userAddition: function() {
$item.filter(selector.addition).remove();
},
selected: function(value, $selectedItem) {
$selectedItem = (settings.allowAdditions)
? $selectedItem || module.get.itemWithAdditions(value)
: $selectedItem || module.get.item(value)
;
if(!$selectedItem) {
return false;
}
$selectedItem
.each(function() {
var
$selected = $(this),
selectedText = module.get.choiceText($selected),
selectedValue = module.get.choiceValue($selected, selectedText)
;
if(module.is.multiple()) {
if(settings.useLabels) {
module.remove.value(selectedValue, selectedText, $selected);
module.remove.label(selectedValue);
}
else {
module.remove.value(selectedValue, selectedText, $selected);
if(module.get.selectionCount() === 0) {
module.set.placeholderText();
}
else {
module.set.text(module.add.variables(message.count));
}
}
}
else {
module.remove.value(selectedValue, selectedText, $selected);
}
$selected
.removeClass(className.filtered)
.removeClass(className.active)
;
if(settings.useLabels) {
$selected.removeClass(className.selected);
}
})
;
},
selectedItem: function() {
$item.removeClass(className.selected);
},
value: function(removedValue, removedText, $removedItem) {
var
values = module.get.values(),
newValue
;
if( module.has.selectInput() ) {
module.verbose('Input is <select> removing selected option', removedValue);
newValue = module.remove.arrayValue(removedValue, values);
module.remove.optionValue(removedValue);
}
else {
module.verbose('Removing from delimited values', removedValue);
newValue = module.remove.arrayValue(removedValue, values);
newValue = newValue.join(settings.delimiter);
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('No callback on initial load', settings.onRemove);
}
else {
settings.onRemove.call(element, removedValue, removedText, $removedItem);
}
module.set.value(newValue, removedText, $removedItem);
module.check.maxSelections();
},
arrayValue: function(removedValue, values) {
if( !$.isArray(values) ) {
values = [values];
}
values = $.grep(values, function(value){
return (removedValue != value);
});
module.verbose('Removed value from delimited string', removedValue, values);
return values;
},
label: function(value, shouldAnimate) {
var
$labels = $module.find(selector.label),
$removedLabel = $labels.filter('[data-' + metadata.value + '="' + module.escape.string(value) +'"]')
;
module.verbose('Removing label', $removedLabel);
$removedLabel.remove();
},
activeLabels: function($activeLabels) {
$activeLabels = $activeLabels || $module.find(selector.label).filter('.' + className.active);
module.verbose('Removing active label selections', $activeLabels);
module.remove.labels($activeLabels);
},
labels: function($labels) {
$labels = $labels || $module.find(selector.label);
module.verbose('Removing labels', $labels);
$labels
.each(function(){
var
$label = $(this),
value = $label.data(metadata.value),
stringValue = (value !== undefined)
? String(value)
: value,
isUserValue = module.is.userValue(stringValue)
;
if(settings.onLabelRemove.call($label, value) === false) {
module.debug('Label remove callback cancelled removal');
return;
}
module.remove.message();
if(isUserValue) {
module.remove.value(stringValue);
module.remove.label(stringValue);
}
else {
// selected will also remove label
module.remove.selected(stringValue);
}
})
;
},
tabbable: function() {
if( module.is.searchSelection() ) {
module.debug('Searchable dropdown initialized');
$search
.removeAttr('tabindex')
;
$menu
.removeAttr('tabindex')
;
}
else {
module.debug('Simple selection dropdown initialized');
$module
.removeAttr('tabindex')
;
$menu
.removeAttr('tabindex')
;
}
}
},
has: {
menuSearch: function() {
return (module.has.search() && $search.closest($menu).length > 0);
},
search: function() {
return ($search.length > 0);
},
sizer: function() {
return ($sizer.length > 0);
},
selectInput: function() {
return ( $input.is('select') );
},
minCharacters: function(searchTerm) {
if(settings.minCharacters) {
searchTerm = (searchTerm !== undefined)
? String(searchTerm)
: String(module.get.query())
;
return (searchTerm.length >= settings.minCharacters);
}
return true;
},
firstLetter: function($item, letter) {
var
text,
firstLetter
;
if(!$item || $item.length === 0 || typeof letter !== 'string') {
return false;
}
text = module.get.choiceText($item, false);
letter = letter.toLowerCase();
firstLetter = String(text).charAt(0).toLowerCase();
return (letter == firstLetter);
},
input: function() {
return ($input.length > 0);
},
items: function() {
return ($item.length > 0);
},
menu: function() {
return ($menu.length > 0);
},
message: function() {
return ($menu.children(selector.message).length !== 0);
},
label: function(value) {
var
escapedValue = module.escape.value(value),
$labels = $module.find(selector.label)
;
return ($labels.filter('[data-' + metadata.value + '="' + module.escape.string(escapedValue) +'"]').length > 0);
},
maxSelections: function() {
return (settings.maxSelections && module.get.selectionCount() >= settings.maxSelections);
},
allResultsFiltered: function() {
var
$normalResults = $item.not(selector.addition)
;
return ($normalResults.filter(selector.unselectable).length === $normalResults.length);
},
userSuggestion: function() {
return ($menu.children(selector.addition).length > 0);
},
query: function() {
return (module.get.query() !== '');
},
value: function(value) {
var
values = module.get.values(),
hasValue = $.isArray(values)
? values && ($.inArray(value, values) !== -1)
: (values == value)
;
return (hasValue)
? true
: false
;
}
},
is: {
active: function() {
return $module.hasClass(className.active);
},
bubbledLabelClick: function(event) {
return $(event.target).is('select, input') && $module.closest('label').length > 0;
},
bubbledIconClick: function(event) {
return $(event.target).closest($icon).length > 0;
},
alreadySetup: function() {
return ($module.is('select') && $module.parent(selector.dropdown).length > 0 && $module.prev().length === 0);
},
animating: function($subMenu) {
return ($subMenu)
? $subMenu.transition && $subMenu.transition('is animating')
: $menu.transition && $menu.transition('is animating')
;
},
disabled: function() {
return $module.hasClass(className.disabled);
},
focused: function() {
return (document.activeElement === $module[0]);
},
focusedOnSearch: function() {
return (document.activeElement === $search[0]);
},
allFiltered: function() {
return( (module.is.multiple() || module.has.search()) && !(settings.hideAdditions == false && module.has.userSuggestion()) && !module.has.message() && module.has.allResultsFiltered() );
},
hidden: function($subMenu) {
return !module.is.visible($subMenu);
},
initialLoad: function() {
return initialLoad;
},
onScreen: function($subMenu) {
var
$currentMenu = $subMenu || $menu,
canOpenDownward = true,
onScreen = {},
calculations
;
$currentMenu.addClass(className.loading);
calculations = {
context: {
scrollTop : $context.scrollTop(),
height : $context.outerHeight()
},
menu : {
offset: $currentMenu.offset(),
height: $currentMenu.outerHeight()
}
};
onScreen = {
above : (calculations.context.scrollTop) <= calculations.menu.offset.top - calculations.menu.height,
below : (calculations.context.scrollTop + calculations.context.height) >= calculations.menu.offset.top + calculations.menu.height
};
if(onScreen.below) {
module.verbose('Dropdown can fit in context downward', onScreen);
canOpenDownward = true;
}
else if(!onScreen.below && !onScreen.above) {
module.verbose('Dropdown cannot fit in either direction, favoring downward', onScreen);
canOpenDownward = true;
}
else {
module.verbose('Dropdown cannot fit below, opening upward', onScreen);
canOpenDownward = false;
}
$currentMenu.removeClass(className.loading);
return canOpenDownward;
},
inObject: function(needle, object) {
var
found = false
;
$.each(object, function(index, property) {
if(property == needle) {
found = true;
return true;
}
});
return found;
},
multiple: function() {
return $module.hasClass(className.multiple);
},
remote: function() {
return settings.apiSettings && module.can.useAPI();
},
single: function() {
return !module.is.multiple();
},
selectMutation: function(mutations) {
var
selectChanged = false
;
$.each(mutations, function(index, mutation) {
if(mutation.target && $(mutation.target).is('select')) {
selectChanged = true;
return true;
}
});
return selectChanged;
},
search: function() {
return $module.hasClass(className.search);
},
searchSelection: function() {
return ( module.has.search() && $search.parent(selector.dropdown).length === 1 );
},
selection: function() {
return $module.hasClass(className.selection);
},
userValue: function(value) {
return ($.inArray(value, module.get.userValues()) !== -1);
},
upward: function($menu) {
var $element = $menu || $module;
return $element.hasClass(className.upward);
},
visible: function($subMenu) {
return ($subMenu)
? $subMenu.hasClass(className.visible)
: $menu.hasClass(className.visible)
;
}
},
can: {
activate: function($item) {
if(settings.useLabels) {
return true;
}
if(!module.has.maxSelections()) {
return true;
}
if(module.has.maxSelections() && $item.hasClass(className.active)) {
return true;
}
return false;
},
click: function() {
return (hasTouch || settings.on == 'click');
},
extendSelect: function() {
return settings.allowAdditions || settings.apiSettings;
},
show: function() {
return !module.is.disabled() && (module.has.items() || module.has.message());
},
useAPI: function() {
return $.fn.api !== undefined;
}
},
animate: {
show: function(callback, $subMenu) {
var
$currentMenu = $subMenu || $menu,
start = ($subMenu)
? function() {}
: function() {
module.hideSubMenus();
module.hideOthers();
module.set.active();
},
transition
;
callback = $.isFunction(callback)
? callback
: function(){}
;
module.verbose('Doing menu show animation', $currentMenu);
module.set.direction($subMenu);
transition = module.get.transition($subMenu);
if( module.is.selection() ) {
module.set.scrollPosition(module.get.selectedItem(), true);
}
if( module.is.hidden($currentMenu) || module.is.animating($currentMenu) ) {
if(transition == 'none') {
start();
$currentMenu.transition('show');
callback.call(element);
}
else if($.fn.transition !== undefined && $module.transition('is supported')) {
$currentMenu
.transition({
animation : transition + ' in',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
queue : true,
onStart : start,
onComplete : function() {
callback.call(element);
}
})
;
}
else {
module.error(error.noTransition, transition);
}
}
},
hide: function(callback, $subMenu) {
var
$currentMenu = $subMenu || $menu,
duration = ($subMenu)
? (settings.duration * 0.9)
: settings.duration,
start = ($subMenu)
? function() {}
: function() {
if( module.can.click() ) {
module.unbind.intent();
}
module.remove.active();
},
transition = module.get.transition($subMenu)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.visible($currentMenu) || module.is.animating($currentMenu) ) {
module.verbose('Doing menu hide animation', $currentMenu);
if(transition == 'none') {
start();
$currentMenu.transition('hide');
callback.call(element);
}
else if($.fn.transition !== undefined && $module.transition('is supported')) {
$currentMenu
.transition({
animation : transition + ' out',
duration : settings.duration,
debug : settings.debug,
verbose : settings.verbose,
queue : true,
onStart : start,
onComplete : function() {
if(settings.direction == 'auto') {
module.remove.upward($subMenu);
}
callback.call(element);
}
})
;
}
else {
module.error(error.transition);
}
}
}
},
hideAndClear: function() {
module.remove.searchTerm();
if( module.has.maxSelections() ) {
return;
}
if(module.has.search()) {
module.hide(function() {
module.remove.filteredItem();
});
}
else {
module.hide();
}
},
delay: {
show: function() {
module.verbose('Delaying show event to ensure user intent');
clearTimeout(module.timer);
module.timer = setTimeout(module.show, settings.delay.show);
},
hide: function() {
module.verbose('Delaying hide event to ensure user intent');
clearTimeout(module.timer);
module.timer = setTimeout(module.hide, settings.delay.hide);
}
},
escape: {
value: function(value) {
var
multipleValues = $.isArray(value),
stringValue = (typeof value === 'string'),
isUnparsable = (!stringValue && !multipleValues),
hasQuotes = (stringValue && value.search(regExp.quote) !== -1),
values = []
;
if(isUnparsable || !hasQuotes) {
return value;
}
module.debug('Encoding quote values for use in select', value);
if(multipleValues) {
$.each(value, function(index, value){
values.push(value.replace(regExp.quote, '"'));
});
return values;
}
return value.replace(regExp.quote, '"');
},
string: function(text) {
text = String(text);
return text.replace(regExp.escape, '\\$&');
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
if($.isPlainObject(settings[name])) {
$.extend(true, settings[name], value);
}
else {
settings[name] = value;
}
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(!settings.silent && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(!settings.silent && settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
if(!settings.silent) {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
}
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: $allModules
;
};
$.fn.dropdown.settings = {
silent : false,
debug : false,
verbose : false,
performance : true,
on : 'click', // what event should show menu action on item selection
action : 'activate', // action on item selection (nothing, activate, select, combo, hide, function(){})
apiSettings : false,
selectOnKeydown : true, // Whether selection should occur automatically when keyboard shortcuts used
minCharacters : 0, // Minimum characters required to trigger API call
filterRemoteData : false, // Whether API results should be filtered after being returned for query term
saveRemoteData : true, // Whether remote name/value pairs should be stored in sessionStorage to allow remote data to be restored on page refresh
throttle : 200, // How long to wait after last user input to search remotely
context : window, // Context to use when determining if on screen
direction : 'auto', // Whether dropdown should always open in one direction
keepOnScreen : true, // Whether dropdown should check whether it is on screen before showing
match : 'both', // what to match against with search selection (both, text, or label)
fullTextSearch : false, // search anywhere in value (set to 'exact' to require exact matches)
placeholder : 'auto', // whether to convert blank <select> values to placeholder text
preserveHTML : true, // preserve html when selecting value
sortSelect : false, // sort selection on init
forceSelection : true, // force a choice on blur with search selection
allowAdditions : false, // whether multiple select should allow user added values
hideAdditions : true, // whether or not to hide special message prompting a user they can enter a value
maxSelections : false, // When set to a number limits the number of selections to this count
useLabels : true, // whether multiple select should filter currently active selections from choices
delimiter : ',', // when multiselect uses normal <input> the values will be delimited with this character
showOnFocus : true, // show menu on focus
allowReselection : false, // whether current value should trigger callbacks when reselected
allowTab : true, // add tabindex to element
allowCategorySelection : false, // allow elements with sub-menus to be selected
fireOnInit : false, // Whether callbacks should fire when initializing dropdown values
transition : 'auto', // auto transition will slide down or up based on direction
duration : 200, // duration of transition
glyphWidth : 1.037, // widest glyph width in em (W is 1.037 em) used to calculate multiselect input width
// label settings on multi-select
label: {
transition : 'scale',
duration : 200,
variation : false
},
// delay before event
delay : {
hide : 300,
show : 200,
search : 20,
touch : 50
},
/* Callbacks */
onChange : function(value, text, $selected){},
onAdd : function(value, text, $selected){},
onRemove : function(value, text, $selected){},
onLabelSelect : function($selectedLabels){},
onLabelCreate : function(value, text) { return $(this); },
onLabelRemove : function(value) { return true; },
onNoResults : function(searchTerm) { return true; },
onShow : function(){},
onHide : function(){},
/* Component */
name : 'Dropdown',
namespace : 'dropdown',
message: {
addResult : 'Add <b>{term}</b>',
count : '{count} selected',
maxSelections : 'Max {maxCount} selections',
noResults : 'No results found.',
serverError : 'There was an error contacting the server'
},
error : {
action : 'You called a dropdown action that was not defined',
alreadySetup : 'Once a select has been initialized behaviors must be called on the created ui dropdown',
labels : 'Allowing user additions currently requires the use of labels.',
missingMultiple : '<select> requires multiple property to be set to correctly preserve multiple values',
method : 'The method you called is not defined.',
noAPI : 'The API module is required to load resources remotely',
noStorage : 'Saving remote data requires session storage',
noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>'
},
regExp : {
escape : /[-[\]{}()*+?.,\\^$|#\s]/g,
quote : /"/g
},
metadata : {
defaultText : 'defaultText',
defaultValue : 'defaultValue',
placeholderText : 'placeholder',
text : 'text',
value : 'value'
},
// property names for remote query
fields: {
remoteValues : 'results', // grouping for api results
values : 'values', // grouping for all dropdown values
disabled : 'disabled', // whether value should be disabled
name : 'name', // displayed dropdown text
value : 'value', // actual dropdown value
text : 'text' // displayed text when selected
},
keys : {
backspace : 8,
delimiter : 188, // comma
deleteKey : 46,
enter : 13,
escape : 27,
pageUp : 33,
pageDown : 34,
leftArrow : 37,
upArrow : 38,
rightArrow : 39,
downArrow : 40
},
selector : {
addition : '.addition',
dropdown : '.ui.dropdown',
hidden : '.hidden',
icon : '> .dropdown.icon',
input : '> input[type="hidden"], > select',
item : '.item',
label : '> .label',
remove : '> .label > .delete.icon',
siblingLabel : '.label',
menu : '.menu',
message : '.message',
menuIcon : '.dropdown.icon',
search : 'input.search, .menu > .search > input, .menu input.search',
sizer : '> input.sizer',
text : '> .text:not(.icon)',
unselectable : '.disabled, .filtered'
},
className : {
active : 'active',
addition : 'addition',
animating : 'animating',
disabled : 'disabled',
empty : 'empty',
dropdown : 'ui dropdown',
filtered : 'filtered',
hidden : 'hidden transition',
item : 'item',
label : 'ui label',
loading : 'loading',
menu : 'menu',
message : 'message',
multiple : 'multiple',
placeholder : 'default',
sizer : 'sizer',
search : 'search',
selected : 'selected',
selection : 'selection',
upward : 'upward',
visible : 'visible'
}
};
/* Templates */
$.fn.dropdown.settings.templates = {
// generates dropdown from select values
dropdown: function(select) {
var
placeholder = select.placeholder || false,
values = select.values || {},
html = ''
;
html += '<i class="dropdown icon"></i>';
if(select.placeholder) {
html += '<div class="default text">' + placeholder + '</div>';
}
else {
html += '<div class="text"></div>';
}
html += '<div class="menu">';
$.each(select.values, function(index, option) {
html += (option.disabled)
? '<div class="disabled item" data-value="' + option.value + '">' + option.name + '</div>'
: '<div class="item" data-value="' + option.value + '">' + option.name + '</div>'
;
});
html += '</div>';
return html;
},
// generates just menu from select
menu: function(response, fields) {
var
values = response[fields.values] || {},
html = ''
;
$.each(values, function(index, option) {
var
maybeText = (option[fields.text])
? 'data-text="' + option[fields.text] + '"'
: '',
maybeDisabled = (option[fields.disabled])
? 'disabled '
: ''
;
html += '<div class="'+ maybeDisabled +'item" data-value="' + option[fields.value] + '"' + maybeText + '>'
html += option[fields.name];
html += '</div>';
});
return html;
},
// generates label for multiselect
label: function(value, text) {
return text + '<i class="delete icon"></i>';
},
// generates messages like "No results"
message: function(message) {
return message;
},
// generates user addition to selection menu
addition: function(choice) {
return choice;
}
};
})( jQuery, window, document );
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ProgressPlugin {
constructor(options) {
if(typeof options === "function") {
options = {
handler: options
};
}
options = options || {};
this.profile = options.profile;
this.handler = options.handler;
}
apply(compiler) {
const handler = this.handler || defaultHandler;
const profile = this.profile;
if(compiler.compilers) {
const states = new Array(compiler.compilers.length);
compiler.compilers.forEach(function(compiler, idx) {
compiler.apply(new ProgressPlugin(function(p, msg) {
states[idx] = Array.prototype.slice.apply(arguments);
handler.apply(null, [
states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length,
`[${idx}] ${msg}`
].concat(Array.prototype.slice.call(arguments, 2)));
}));
});
} else {
let lastModulesCount = 0;
let moduleCount = 500;
let doneModules = 0;
const activeModules = [];
const update = function update(module) {
handler(
0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6,
"building modules",
`${doneModules}/${moduleCount} modules`,
`${activeModules.length} active`,
activeModules[activeModules.length - 1]
);
};
const moduleDone = function moduleDone(module) {
doneModules++;
const ident = module.identifier();
if(ident) {
const idx = activeModules.indexOf(ident);
if(idx >= 0) activeModules.splice(idx, 1);
}
update();
};
compiler.plugin("compilation", function(compilation) {
if(compilation.compiler.isChild()) return;
lastModulesCount = moduleCount;
moduleCount = 0;
doneModules = 0;
handler(0, "compiling");
compilation.plugin("build-module", function(module) {
moduleCount++;
const ident = module.identifier();
if(ident) {
activeModules.push(ident);
}
update();
});
compilation.plugin("failed-module", moduleDone);
compilation.plugin("succeed-module", moduleDone);
const syncHooks = {
"seal": [0.71, "sealing"],
"optimize": [0.72, "optimizing"],
"optimize-modules-basic": [0.73, "basic module optimization"],
"optimize-modules": [0.74, "module optimization"],
"optimize-modules-advanced": [0.75, "advanced module optimization"],
"optimize-chunks-basic": [0.76, "basic chunk optimization"],
"optimize-chunks": [0.77, "chunk optimization"],
"optimize-chunks-advanced": [0.78, "advanced chunk optimization"],
// optimize-tree
"revive-modules": [0.80, "module reviving"],
"optimize-module-order": [0.81, "module order optimization"],
"optimize-module-ids": [0.82, "module id optimization"],
"revive-chunks": [0.83, "chunk reviving"],
"optimize-chunk-order": [0.84, "chunk order optimization"],
"optimize-chunk-ids": [0.85, "chunk id optimization"],
"before-hash": [0.86, "hashing"],
"before-module-assets": [0.87, "module assets processing"],
"before-chunk-assets": [0.88, "chunk assets processing"],
"additional-chunk-assets": [0.89, "additional chunk assets processing"],
"record": [0.90, "recording"]
};
Object.keys(syncHooks).forEach(name => {
let pass = 0;
const settings = syncHooks[name];
compilation.plugin(name, () => {
if(pass++ > 0)
handler(settings[0], settings[1], `pass ${pass}`);
else
handler(settings[0], settings[1]);
});
});
compilation.plugin("optimize-tree", (chunks, modules, callback) => {
handler(0.79, "module and chunk tree optimization");
callback();
});
compilation.plugin("additional-assets", callback => {
handler(0.91, "additional asset processing");
callback();
});
compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
handler(0.92, "chunk asset optimization");
callback();
});
compilation.plugin("optimize-assets", (assets, callback) => {
handler(0.94, "asset optimization");
callback();
});
});
compiler.plugin("emit", (compilation, callback) => {
handler(0.95, "emitting");
callback();
});
compiler.plugin("done", () => {
handler(1, "");
});
}
let lineCaretPosition = 0,
lastState, lastStateTime;
function defaultHandler(percentage, msg) {
let state = msg;
const details = Array.prototype.slice.call(arguments, 2);
if(percentage < 1) {
percentage = Math.floor(percentage * 100);
msg = `${percentage}% ${msg}`;
if(percentage < 100) {
msg = ` ${msg}`;
}
if(percentage < 10) {
msg = ` ${msg}`;
}
details.forEach(detail => {
if(!detail) return;
if(detail.length > 40) {
detail = `...${detail.substr(detail.length - 37)}`;
}
msg += ` ${detail}`;
});
}
if(profile) {
state = state.replace(/^\d+\/\d+\s+/, "");
if(percentage === 0) {
lastState = null;
lastStateTime = +new Date();
} else if(state !== lastState || percentage === 1) {
const now = +new Date();
if(lastState) {
const stateMsg = `${now - lastStateTime}ms ${lastState}`;
goToLineStart(stateMsg);
process.stderr.write(stateMsg + "\n");
lineCaretPosition = 0;
}
lastState = state;
lastStateTime = now;
}
}
goToLineStart(msg);
process.stderr.write(msg);
}
function goToLineStart(nextMessage) {
let str = "";
for(; lineCaretPosition > nextMessage.length; lineCaretPosition--) {
str += "\b \b";
}
for(var i = 0; i < lineCaretPosition; i++) {
str += "\b";
}
lineCaretPosition = nextMessage.length;
if(str) process.stderr.write(str);
}
}
}
module.exports = ProgressPlugin;
|
Clazz.declarePackage ("JSV.api");
Clazz.declareInterface (JSV.api, "JSVGraphics");
|
(function (main) {
'use strict';
/**
* Parse or format dates
* @class fecha
*/
var fecha = {},
token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,
dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
amPm = ['am', 'pm'],
twoDigits = /\d\d?/, threeDigits = /\d{3}/, fourDigits = /\d{4}/,
word = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,
noop = function () {},
dayNamesShort = [], monthNamesShort = [],
parseFlags = {
D: [twoDigits, function (d, v) {
d.day = v;
}],
M: [twoDigits, function (d, v) {
d.month = v - 1;
}],
YY: [twoDigits, function (d, v) {
var da = new Date(), cent = +('' + da.getFullYear()).substr(0, 2);
d.year = '' + (v > 68 ? cent - 1 : cent) + v;
}],
h: [twoDigits, function (d, v) {
d.hour = v;
}],
m: [twoDigits, function (d, v) {
d.minute = v;
}],
s: [twoDigits, function (d, v) {
d.second = v;
}],
YYYY: [fourDigits, function (d, v) {
d.year = v;
}],
S: [/\d/, function (d, v) {
d.millisecond = v * 100;
}],
SS: [/\d{2}/, function (d, v) {
d.millisecond = v * 10;
}],
SSS: [threeDigits, function (d, v) {
d.millisecond = v;
}],
d: [twoDigits, noop],
ddd: [word, noop],
MMM: [word, monthUpdate('monthNamesShort')],
MMMM: [word, monthUpdate('monthNames')],
a: [word, function (d, v) {
if (amPm.indexOf(v.toLowerCase())) {
d.isPm = true;
}
}],
ZZ: [/[\+\-]\d\d:?\d\d/, function (d, v) {
var parts = (v + '').match(/([\+\-]|\d\d)/gi), minutes;
if (parts) {
minutes = +(parts[1] * 60) + parseInt(parts[2], 10);
d.timezoneOffset = parts[0] === '+' ? minutes : -minutes;
}
}]
};
parseFlags.dd = parseFlags.d;
parseFlags.dddd = parseFlags.ddd;
parseFlags.Do = parseFlags.DD = parseFlags.D;
parseFlags.mm = parseFlags.m;
parseFlags.hh = parseFlags.H = parseFlags.HH = parseFlags.h;
parseFlags.MM = parseFlags.M;
parseFlags.ss = parseFlags.s;
parseFlags.A = parseFlags.a;
shorten(monthNames, monthNamesShort, 3);
shorten(dayNames, dayNamesShort, 3);
function monthUpdate(arrName) {
return function (d, v) {
var index = fecha.i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase());
if (~index) {
d.month = index;
}
}
}
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
function shorten(arr, newArr, sLen) {
for (var i = 0, len = arr.length; i < len; i++) {
newArr.push(arr[i].substr(0, sLen));
}
}
function DoFn(D) {
return D + [ 'th', 'st', 'nd', 'rd' ][ D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10 ];
}
fecha.i18n = {
dayNamesShort: dayNamesShort,
dayNames: dayNames,
monthNamesShort: monthNamesShort,
monthNames: monthNames,
amPm: amPm,
DoFn: DoFn
};
// Some common format strings
fecha.masks = {
'default': 'ddd MMM DD YYYY HH:mm:ss',
shortDate: 'M/D/YY',
mediumDate: 'MMM D, YYYY',
longDate: 'MMMM D, YYYY',
fullDate: 'dddd, MMMM D, YYYY',
shortTime: 'HH:mm',
mediumTime: 'HH:mm:ss',
longTime: 'HH:mm:ss.SSS'
};
/***
* Format a date
* @method format
* @param {Date|string} dateObj
* @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
*/
fecha.format = function (dateObj, mask) {
// Passing date through Date applies Date.parse, if necessary
if (typeof dateObj === 'string') {
dateObj = fecha.parse(dateObj);
} else if (!dateObj) {
dateObj = new Date();
}
if (isNaN(dateObj)) {
throw new SyntaxError('invalid date');
}
mask = fecha.masks[mask] || mask || fecha.masks['default'];
var D = dateObj.getDate(), d = dateObj.getDay(), M = dateObj.getMonth(), y = dateObj.getFullYear(), H = dateObj.getHours(), m = dateObj.getMinutes(), s = dateObj.getSeconds(), S = dateObj.getMilliseconds(), o = dateObj.getTimezoneOffset(), flags = {
D: D,
DD: pad(D),
Do: fecha.i18n.DoFn(D),
d: d,
dd: pad(d),
ddd: fecha.i18n.dayNamesShort[d],
dddd: fecha.i18n.dayNames[d],
M: M + 1,
MM: pad(M + 1),
MMM: fecha.i18n.monthNamesShort[M],
MMMM: fecha.i18n.monthNames[M],
YY: String(y).slice(2),
YYYY: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
m: m,
mm: pad(m),
s: s,
ss: pad(s),
S: Math.round(S / 100),
SS: pad(Math.round(S / 10), 2),
SSS: pad(S, 3),
a: H < 12 ? fecha.i18n.amPm[0] : fecha.i18n.amPm[1],
A: H < 12 ? fecha.i18n.amPm[0].toUpperCase() : fecha.i18n.amPm[1].toUpperCase(),
ZZ: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
/**
* Parse a date string into an object, changes - into /
* @method parse
* @param {string} dateStr Date string
* @param {string} format Date parse format
* @returns {Date}
*/
fecha.parse = function (dateStr, format) {
if (!format) {
return new Date(dateStr.replace(/\-/g, '/'));
} else {
format = fecha.masks[format] || format;
var isValid = true, dateInfo = {};
format.replace(token, function ($0) {
if (parseFlags[$0]) {
var info = parseFlags[$0];
var index = dateStr.search(info[0]);
if (!~index) {
isValid = false;
} else {
dateStr.replace(info[0], function (result) {
info[1](dateInfo, result);
dateStr = dateStr.substr(index + result.length);
return result;
});
}
}
return parseFlags[$0] ? '' : $0.slice(1, $0.length - 1);
});
}
if (!isValid) {
return false;
}
var today = new Date(), date;
if (dateInfo.isPm && dateInfo.hour) {
dateInfo.hour = +dateInfo.hour + 12
}
if (dateInfo.timezoneOffset) {
dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset;
date = new Date(Date.UTC(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1,
dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0));
} else {
date = new Date(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1,
dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0);
}
return date;
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = fecha;
} else if (typeof require !== 'undefined' && require.amd) {
define(function () {
return fecha;
});
} else {
main.fecha = fecha;
}
})(this);
|
define(
"dojo/cldr/nls/zh-hk/currency", //begin v1.x content
{
"HKD_displayName": "港幣",
"HKD_symbol": "HK$",
"CAD_displayName": "加幣",
"CNY_displayName": "人民幣",
"USD_symbol": "$",
"AUD_displayName": "澳幣",
"JPY_displayName": "日圓",
"GBP_displayName": "英鎊",
"EUR_displayName": "歐元"
}
//end v1.x content
); |
import { assert, deprecate } from 'ember-metal/debug';
import { get } from 'ember-metal/property_get';
import assign from 'ember-metal/assign';
import { isGlobal } from 'ember-metal/path_cache';
import { internal, render } from 'htmlbars-runtime';
import getValue from 'ember-htmlbars/hooks/get-value';
import { isStream } from 'ember-metal/streams/utils';
export default function buildComponentTemplate({ component, tagName, layout, isAngleBracket, isComponentElement, outerAttrs }, attrs, content) {
var blockToRender, meta;
if (component === undefined) {
component = null;
}
if (layout && layout.raw) {
let yieldTo = createContentBlocks(content.templates, content.scope, content.self, component);
blockToRender = createLayoutBlock(layout.raw, yieldTo, content.self, component, attrs);
meta = layout.raw.meta;
} else if (content.templates && content.templates.default) {
blockToRender = createContentBlock(content.templates.default, content.scope, content.self, component);
meta = content.templates.default.meta;
}
if (component && !component._isAngleBracket || isComponentElement) {
tagName = tagName || tagNameFor(component);
// If this is not a tagless component, we need to create the wrapping
// element. We use `manualElement` to create a template that represents
// the wrapping element and yields to the previous block.
if (tagName !== '') {
if (isComponentElement) { attrs = mergeAttrs(attrs, outerAttrs); }
var attributes = normalizeComponentAttributes(component, isAngleBracket, attrs);
var elementTemplate = internal.manualElement(tagName, attributes);
elementTemplate.meta = meta;
blockToRender = createElementBlock(elementTemplate, blockToRender, component);
} else {
validateTaglessComponent(component);
}
}
// tagName is one of:
// * `undefined` if no component is present
// * the falsy value "" if set explicitly on the component
// * an actual tagName set explicitly on the component
return { createdElement: !!tagName, block: blockToRender };
}
export function buildHTMLTemplate(tagName, _attrs, content) {
let attrs = {};
for (let prop in _attrs) {
let val = _attrs[prop];
if (typeof val === 'string') {
attrs[prop] = val;
} else {
attrs[prop] = ['value', val];
}
}
let childTemplate = content.templates.default;
let elementTemplate = internal.manualElement(tagName, attrs, childTemplate.isEmpty);
if (childTemplate.isEmpty) {
return blockFor(elementTemplate, { scope: content.scope });
} else {
let blockToRender = blockFor(content.templates.default, content);
return blockFor(elementTemplate, { yieldTo: blockToRender, scope: content.scope });
}
}
function mergeAttrs(innerAttrs, outerAttrs) {
let result = assign({}, innerAttrs, outerAttrs);
if (innerAttrs.class && outerAttrs.class) {
result.class = ['subexpr', '-join-classes', [['value', innerAttrs.class], ['value', outerAttrs.class]], []];
}
return result;
}
function blockFor(template, options) {
assert('BUG: Must pass a template to blockFor', !!template);
return internal.blockFor(render, template, options);
}
function createContentBlock(template, scope, self, component) {
assert('BUG: buildComponentTemplate can take a scope or a self, but not both', !(scope && self));
return blockFor(template, {
scope,
self,
options: { view: component }
});
}
function createContentBlocks(templates, scope, self, component) {
if (!templates) {
return;
}
var output = {};
for (var name in templates) {
if (templates.hasOwnProperty(name)) {
var template = templates[name];
if (template) {
output[name] = createContentBlock(templates[name], scope, self, component);
}
}
}
return output;
}
function createLayoutBlock(template, yieldTo, self, component, attrs) {
return blockFor(template, {
yieldTo,
// If we have an old-style Controller with a template it will be
// passed as our `self` argument, and it should be the context for
// the template. Otherwise, we must have a real Component and it
// should be its own template context.
self: self || component,
options: { view: component, attrs: attrs }
});
}
function createElementBlock(template, yieldTo, component) {
return blockFor(template, {
yieldTo: yieldTo,
self: component,
options: { view: component }
});
}
function tagNameFor(view) {
var tagName = view.tagName;
if (tagName !== null && typeof tagName === 'object' && tagName.isDescriptor) {
tagName = get(view, 'tagName');
deprecate(
'In the future using a computed property to define tagName will not be permitted. That value will be respected, but changing it will not update the element.',
!tagName,
{ id: 'ember-views.computed-tag-name', until: '2.0.0' }
);
}
if (tagName === null || tagName === undefined) {
tagName = view._defaultTagName || 'div';
}
return tagName;
}
// Takes a component and builds a normalized set of attribute
// bindings consumable by HTMLBars' `attribute` hook.
function normalizeComponentAttributes(component, isAngleBracket, attrs) {
var normalized = {};
var attributeBindings = component.attributeBindings;
var i, l;
if (attrs.id && getValue(attrs.id)) {
// Do not allow binding to the `id`
normalized.id = getValue(attrs.id);
component.elementId = normalized.id;
} else {
normalized.id = component.elementId;
}
if (attributeBindings) {
for (i = 0, l = attributeBindings.length; i < l; i++) {
var attr = attributeBindings[i];
var colonIndex = attr.indexOf(':');
var attrName, expression;
if (colonIndex !== -1) {
var attrProperty = attr.substring(0, colonIndex);
attrName = attr.substring(colonIndex + 1);
expression = ['get', 'view.' + attrProperty];
} else if (attrs[attr]) {
// TODO: For compatibility with 1.x, we probably need to `set`
// the component's attribute here if it is a CP, but we also
// probably want to suspend observers and allow the
// willUpdateAttrs logic to trigger observers at the correct time.
attrName = attr;
expression = ['value', attrs[attr]];
} else {
attrName = attr;
expression = ['get', 'view.' + attr];
}
assert('You cannot use class as an attributeBinding, use classNameBindings instead.', attrName !== 'class');
normalized[attrName] = expression;
}
}
if (isAngleBracket) {
for (var prop in attrs) {
let val = attrs[prop];
if (!val) { continue; }
if (typeof val === 'string' || val.isConcat) {
normalized[prop] = ['value', val];
}
}
}
if (attrs.tagName) {
component.tagName = attrs.tagName;
}
var normalizedClass = normalizeClass(component, attrs);
if (normalizedClass) {
normalized.class = normalizedClass;
}
if (get(component, 'isVisible') === false) {
var hiddenStyle = ['subexpr', '-html-safe', ['display: none;'], []];
var existingStyle = normalized.style;
if (existingStyle) {
normalized.style = ['subexpr', 'concat', [existingStyle, ' ', hiddenStyle], [ ]];
} else {
normalized.style = hiddenStyle;
}
}
return normalized;
}
function normalizeClass(component, attrs) {
var i, l;
var normalizedClass = [];
var classNames = get(component, 'classNames');
var classNameBindings = get(component, 'classNameBindings');
if (attrs.class) {
if (isStream(attrs.class)) {
normalizedClass.push(['subexpr', '-normalize-class', [['value', attrs.class.path], ['value', attrs.class]], []]);
} else {
normalizedClass.push(attrs.class);
}
}
if (attrs.classBinding) {
normalizeClasses(attrs.classBinding.split(' '), normalizedClass);
}
if (classNames) {
for (i = 0, l = classNames.length; i < l; i++) {
normalizedClass.push(classNames[i]);
}
}
if (classNameBindings) {
normalizeClasses(classNameBindings, normalizedClass);
}
if (normalizeClass.length) {
return ['subexpr', '-join-classes', normalizedClass, []];
}
}
function normalizeClasses(classes, output) {
var i, l;
for (i = 0, l = classes.length; i < l; i++) {
var className = classes[i];
assert('classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. [\'foo\', \':bar\']', className.indexOf(' ') === -1);
var [propName, activeClass, inactiveClass] = className.split(':');
// Legacy :class microsyntax for static class names
if (propName === '') {
output.push(activeClass);
continue;
}
// 2.0TODO: Remove deprecated global path
var prop = isGlobal(propName) ? propName : 'view.' + propName;
output.push(['subexpr', '-normalize-class', [
// params
['value', propName],
['get', prop]
], [
// hash
'activeClass', activeClass,
'inactiveClass', inactiveClass
]]);
}
}
function validateTaglessComponent(component) {
assert('You cannot use `classNameBindings` on a tag-less component: ' + component.toString(), function() {
var classNameBindings = component.classNameBindings;
return !classNameBindings || classNameBindings.length === 0;
});
}
|
/**
* ein validator
*
* @link http://formvalidation.io/validators/ein/
* @author https://twitter.com/nghuuphuoc
* @copyright (c) 2013 - 2015 Nguyen Huu Phuoc
* @license http://formvalidation.io/license/
*/
(function($) {
FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
'en_US': {
ein: {
'default': 'Please enter a valid EIN number'
}
}
});
FormValidation.Validator.ein = {
// The first two digits are called campus
// See http://en.wikipedia.org/wiki/Employer_Identification_Number
// http://www.irs.gov/Businesses/Small-Businesses-&-Self-Employed/How-EINs-are-Assigned-and-Valid-EIN-Prefixes
CAMPUS: {
ANDOVER: ['10', '12'],
ATLANTA: ['60', '67'],
AUSTIN: ['50', '53'],
BROOKHAVEN: ['01', '02', '03', '04', '05', '06', '11', '13', '14', '16', '21', '22', '23', '25', '34', '51', '52', '54', '55', '56', '57', '58', '59', '65'],
CINCINNATI: ['30', '32', '35', '36', '37', '38', '61'],
FRESNO: ['15', '24'],
KANSAS_CITY: ['40', '44'],
MEMPHIS: ['94', '95'],
OGDEN: ['80', '90'],
PHILADELPHIA: ['33', '39', '41', '42', '43', '46', '48', '62', '63', '64', '66', '68', '71', '72', '73', '74', '75', '76', '77', '81', '82', '83', '84', '85', '86', '87', '88', '91', '92', '93', '98', '99'],
INTERNET: ['20', '26', '27', '45', '46'],
SMALL_BUSINESS_ADMINISTRATION: ['31']
},
/**
* Validate EIN (Employer Identification Number) which is also known as
* Federal Employer Identification Number (FEIN) or Federal Tax Identification Number
*
* @param {FormValidation.Base} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following keys:
* - message: The invalid message
* @returns {Object|Boolean}
*/
validate: function(validator, $field, options) {
var value = validator.getFieldValue($field, 'ein');
if (value === '') {
return true;
}
if (!/^[0-9]{2}-?[0-9]{7}$/.test(value)) {
return false;
}
// Check the first two digits
var campus = value.substr(0, 2) + '';
for (var key in this.CAMPUS) {
if ($.inArray(campus, this.CAMPUS[key]) !== -1) {
return {
valid: true,
campus: key
};
}
}
return false;
}
};
}(jQuery));
|
'use strict';
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };
Object.defineProperty(exports, '__esModule', {
value: true
});
var _hexToRgb = require('./utils');
var _removeClass$getTopMargin$fadeIn$show$addClass = require('./handle-dom');
var _defaultParams = require('./default-params');
var _defaultParams2 = _interopRequireWildcard(_defaultParams);
/*
* Add modal + overlay to DOM
*/
var _injectedHTML = require('./injected-html');
var _injectedHTML2 = _interopRequireWildcard(_injectedHTML);
var modalClass = '.sweet-alert';
var overlayClass = '.sweet-overlay';
var sweetAlertInitialize = function sweetAlertInitialize() {
var sweetWrap = document.createElement('div');
sweetWrap.innerHTML = _injectedHTML2['default'];
// Append elements to body
while (sweetWrap.firstChild) {
document.body.appendChild(sweetWrap.firstChild);
}
};
/*
* Get DOM element of modal
*/
var getModal = (function (_getModal) {
function getModal() {
return _getModal.apply(this, arguments);
}
getModal.toString = function () {
return _getModal.toString();
};
return getModal;
})(function () {
var $modal = document.querySelector(modalClass);
if (!$modal) {
sweetAlertInitialize();
$modal = getModal();
}
return $modal;
});
/*
* Get DOM element of input (in modal)
*/
var getInput = function getInput() {
var $modal = getModal();
if ($modal) {
return $modal.querySelector('input');
}
};
/*
* Get DOM element of overlay
*/
var getOverlay = function getOverlay() {
return document.querySelector(overlayClass);
};
/*
* Add box-shadow style to button (depending on its chosen bg-color)
*/
var setFocusStyle = function setFocusStyle($button, bgColor) {
var rgbColor = _hexToRgb.hexToRgb(bgColor);
$button.style.boxShadow = '0 0 2px rgba(' + rgbColor + ', 0.8), inset 0 0 0 1px rgba(0, 0, 0, 0.05)';
};
/*
* Animation when opening modal
*/
var openModal = function openModal(callback) {
var $modal = getModal();
_removeClass$getTopMargin$fadeIn$show$addClass.fadeIn(getOverlay(), 10);
_removeClass$getTopMargin$fadeIn$show$addClass.show($modal);
_removeClass$getTopMargin$fadeIn$show$addClass.addClass($modal, 'showSweetAlert');
_removeClass$getTopMargin$fadeIn$show$addClass.removeClass($modal, 'hideSweetAlert');
window.previousActiveElement = document.activeElement;
var $okButton = $modal.querySelector('button.confirm');
$okButton.focus();
setTimeout(function () {
_removeClass$getTopMargin$fadeIn$show$addClass.addClass($modal, 'visible');
}, 500);
var timer = $modal.getAttribute('data-timer');
if (timer !== 'null' && timer !== '') {
var timerCallback = callback;
$modal.timeout = setTimeout(function () {
var doneFunctionExists = (timerCallback || null) && $modal.getAttribute('data-has-done-function') === 'true';
if (doneFunctionExists) {
timerCallback(null);
} else {
sweetAlert.close();
}
}, timer);
}
};
/*
* Reset the styling of the input
* (for example if errors have been shown)
*/
var resetInput = function resetInput() {
var $modal = getModal();
var $input = getInput();
_removeClass$getTopMargin$fadeIn$show$addClass.removeClass($modal, 'show-input');
$input.value = _defaultParams2['default'].inputValue;
$input.setAttribute('type', _defaultParams2['default'].inputType);
$input.setAttribute('placeholder', _defaultParams2['default'].inputPlaceholder);
resetInputError();
};
var resetInputError = function resetInputError(event) {
// If press enter => ignore
if (event && event.keyCode === 13) {
return false;
}
var $modal = getModal();
var $errorIcon = $modal.querySelector('.sa-input-error');
_removeClass$getTopMargin$fadeIn$show$addClass.removeClass($errorIcon, 'show');
var $errorContainer = $modal.querySelector('.sa-error-container');
_removeClass$getTopMargin$fadeIn$show$addClass.removeClass($errorContainer, 'show');
};
/*
* Set "margin-top"-property on modal based on its computed height
*/
var fixVerticalPosition = function fixVerticalPosition() {
var $modal = getModal();
$modal.style.marginTop = _removeClass$getTopMargin$fadeIn$show$addClass.getTopMargin(getModal());
};
exports.sweetAlertInitialize = sweetAlertInitialize;
exports.getModal = getModal;
exports.getOverlay = getOverlay;
exports.getInput = getInput;
exports.setFocusStyle = setFocusStyle;
exports.openModal = openModal;
exports.resetInput = resetInput;
exports.resetInputError = resetInputError;
exports.fixVerticalPosition = fixVerticalPosition; |
WYMeditor.STRINGS['de'] = {
Strong: 'Fett',
Emphasis: 'Kursiv',
Superscript: 'Text hochstellen',
Subscript: 'Text tiefstellen',
Ordered_List: 'Geordnete Liste einfügen',
Unordered_List: 'Ungeordnete Liste einfügen',
Indent: 'Einzug erhöhen',
Outdent: 'Einzug vermindern',
Undo: 'Befehle rückgängig machen',
Redo: 'Befehle wiederherstellen',
Link: 'Hyperlink einfügen',
Unlink: 'Hyperlink entfernen',
Image: 'Bild einfügen',
Table: 'Tabelle einfügen',
HTML: 'HTML anzeigen/verstecken',
Paragraph: 'Absatz',
Heading_1: 'Überschrift 1',
Heading_2: 'Überschrift 2',
Heading_3: 'Überschrift 3',
Heading_4: 'Überschrift 4',
Heading_5: 'Überschrift 5',
Heading_6: 'Überschrift 6',
Preformatted: 'Vorformatiert',
Blockquote: 'Zitat',
Table_Header: 'Tabellenüberschrift',
URL: 'URL',
Title: 'Titel',
Alternative_Text: 'Alternativer Text',
Caption: 'Tabellenüberschrift',
Summary: 'Summary',
Number_Of_Rows: 'Anzahl Zeilen',
Number_Of_Cols: 'Anzahl Spalten',
Submit: 'Absenden',
Cancel: 'Abbrechen',
Choose: 'Auswählen',
Preview: 'Vorschau',
Paste_From_Word: 'Aus Word einfügen',
Tools: 'Werkzeuge',
Containers: 'Inhaltstyp',
Classes: 'Klassen',
Status: 'Status',
Source_Code: 'Quellcode'
};
|
/*
This file is part of Ext JS 4
Copyright (c) 2011 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.
*/
/**
* @class Ext.grid.PagingScroller
* @extends Ext.grid.Scroller
*
* @private
*/
Ext.define('Ext.grid.PagingScroller', {
extend: 'Ext.grid.Scroller',
alias: 'widget.paginggridscroller',
//renderTpl: null,
//tpl: [
// '<tpl for="pages">',
// '<div class="' + Ext.baseCSSPrefix + 'stretcher" style="width: {width}px;height: {height}px;"></div>',
// '</tpl>'
//],
/**
* @cfg {Number} percentageFromEdge This is a number above 0 and less than 1 which specifies
* at what percentage to begin fetching the next page. For example if the pageSize is 100
* and the percentageFromEdge is the default of 0.35, the paging scroller will prefetch pages
* when scrolling up between records 0 and 34 and when scrolling down between records 65 and 99.
*/
percentageFromEdge: 0.35,
/**
* @cfg {Number} scrollToLoadBuffer This is the time in milliseconds to buffer load requests
* when scrolling the PagingScrollbar.
*/
scrollToLoadBuffer: 200,
activePrefetch: true,
chunkSize: 50,
snapIncrement: 25,
syncScroll: true,
initComponent: function() {
var me = this,
ds = me.store;
ds.on('guaranteedrange', this.onGuaranteedRange, this);
this.callParent(arguments);
},
onGuaranteedRange: function(range, start, end) {
var me = this,
ds = me.store,
rs;
// this should never happen
if (range.length && me.visibleStart < range[0].index) {
return;
}
ds.loadRecords(range);
if (!me.firstLoad) {
if (me.rendered) {
me.invalidate();
} else {
me.on('afterrender', this.invalidate, this, {single: true});
}
me.firstLoad = true;
} else {
// adjust to visible
me.syncTo();
}
},
syncTo: function() {
var me = this,
pnl = me.getPanel(),
store = pnl.store,
scrollerElDom = this.scrollEl.dom,
rowOffset = me.visibleStart - store.guaranteedStart,
scrollBy = rowOffset * me.rowHeight,
scrollHeight = scrollerElDom.scrollHeight,
clientHeight = scrollerElDom.clientHeight,
scrollTop = scrollerElDom.scrollTop,
useMaximum;
// BrowserBug: clientHeight reports 0 in IE9 StrictMode
// Instead we are using offsetHeight and hardcoding borders
if (Ext.isIE9 && Ext.isStrict) {
clientHeight = scrollerElDom.offsetHeight + 2;
}
// This should always be zero or greater than zero but staying
// safe and less than 0 we'll scroll to the bottom.
useMaximum = (scrollHeight - clientHeight - scrollTop <= 0);
this.setViewScrollTop(scrollBy, useMaximum);
},
getPageData : function(){
var panel = this.getPanel(),
store = panel.store,
totalCount = store.getTotalCount();
return {
total : totalCount,
currentPage : store.currentPage,
pageCount: Math.ceil(totalCount / store.pageSize),
fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
};
},
onElScroll: function(e, t) {
var me = this,
panel = me.getPanel(),
store = panel.store,
pageSize = store.pageSize,
guaranteedStart = store.guaranteedStart,
guaranteedEnd = store.guaranteedEnd,
totalCount = store.getTotalCount(),
numFromEdge = Math.ceil(me.percentageFromEdge * store.pageSize),
position = t.scrollTop,
visibleStart = Math.floor(position / me.rowHeight),
view = panel.down('tableview'),
viewEl = view.el,
visibleHeight = viewEl.getHeight(),
visibleAhead = Math.ceil(visibleHeight / me.rowHeight),
visibleEnd = visibleStart + visibleAhead,
prevPage = Math.floor(visibleStart / store.pageSize),
nextPage = Math.floor(visibleEnd / store.pageSize) + 2,
lastPage = Math.ceil(totalCount / store.pageSize),
//requestStart = visibleStart,
requestStart = Math.floor(visibleStart / me.snapIncrement) * me.snapIncrement,
requestEnd = requestStart + pageSize - 1,
activePrefetch = me.activePrefetch;
me.visibleStart = visibleStart;
me.visibleEnd = visibleEnd;
me.syncScroll = true;
if (totalCount >= pageSize) {
// end of request was past what the total is, grab from the end back a pageSize
if (requestEnd > totalCount - 1) {
this.cancelLoad();
if (store.rangeSatisfied(totalCount - pageSize, totalCount - 1)) {
me.syncScroll = true;
}
store.guaranteeRange(totalCount - pageSize, totalCount - 1);
// Out of range, need to reset the current data set
} else if (visibleStart < guaranteedStart || visibleEnd > guaranteedEnd) {
if (store.rangeSatisfied(requestStart, requestEnd)) {
this.cancelLoad();
store.guaranteeRange(requestStart, requestEnd);
} else {
store.mask();
me.attemptLoad(requestStart, requestEnd);
}
// dont sync the scroll view immediately, sync after the range has been guaranteed
me.syncScroll = false;
} else if (activePrefetch && visibleStart < (guaranteedStart + numFromEdge) && prevPage > 0) {
me.syncScroll = true;
store.prefetchPage(prevPage);
} else if (activePrefetch && visibleEnd > (guaranteedEnd - numFromEdge) && nextPage < lastPage) {
me.syncScroll = true;
store.prefetchPage(nextPage);
}
}
if (me.syncScroll) {
me.syncTo();
}
},
getSizeCalculation: function() {
// Use the direct ownerCt here rather than the scrollerOwner
// because we are calculating widths/heights.
var owner = this.ownerGrid,
view = owner.getView(),
store = this.store,
dock = this.dock,
elDom = this.el.dom,
width = 1,
height = 1;
if (!this.rowHeight) {
this.rowHeight = view.el.down(view.getItemSelector()).getHeight(false, true);
}
// If the Store is *locally* filtered, use the filtered count from getCount.
height = store[(!store.remoteFilter && store.isFiltered()) ? 'getCount' : 'getTotalCount']() * this.rowHeight;
if (isNaN(width)) {
width = 1;
}
if (isNaN(height)) {
height = 1;
}
return {
width: width,
height: height
};
},
attemptLoad: function(start, end) {
var me = this;
if (!me.loadTask) {
me.loadTask = Ext.create('Ext.util.DelayedTask', me.doAttemptLoad, me, []);
}
me.loadTask.delay(me.scrollToLoadBuffer, me.doAttemptLoad, me, [start, end]);
},
cancelLoad: function() {
if (this.loadTask) {
this.loadTask.cancel();
}
},
doAttemptLoad: function(start, end) {
var store = this.getPanel().store;
store.guaranteeRange(start, end);
},
setViewScrollTop: function(scrollTop, useMax) {
var owner = this.getPanel(),
items = owner.query('tableview'),
i = 0,
len = items.length,
center,
centerEl,
calcScrollTop,
maxScrollTop,
scrollerElDom = this.el.dom;
owner.virtualScrollTop = scrollTop;
center = items[1] || items[0];
centerEl = center.el.dom;
maxScrollTop = ((owner.store.pageSize * this.rowHeight) - centerEl.clientHeight);
calcScrollTop = (scrollTop % ((owner.store.pageSize * this.rowHeight) + 1));
if (useMax) {
calcScrollTop = maxScrollTop;
}
if (calcScrollTop > maxScrollTop) {
//Ext.Error.raise("Calculated scrollTop was larger than maxScrollTop");
return;
// calcScrollTop = maxScrollTop;
}
for (; i < len; i++) {
items[i].el.dom.scrollTop = calcScrollTop;
}
}
});
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, less, PathUtils */
/**
* ExtensionUtils defines utility methods for implementing extensions.
*/
define(function (require, exports, module) {
"use strict";
var FileSystem = require("filesystem/FileSystem"),
FileUtils = require("file/FileUtils");
/**
* Appends a <style> tag to the document's head.
*
* @param {!string} css CSS code to use as the tag's content
* @return {!HTMLStyleElement} The generated HTML node
**/
function addEmbeddedStyleSheet(css) {
return $("<style>").text(css).appendTo("head")[0];
}
/**
* Appends a <link> tag to the document's head.
*
* @param {!string} url URL to a style sheet
* @param {$.Deferred=} deferred Optionally check for load and error events
* @return {!HTMLLinkElement} The generated HTML node
**/
function addLinkedStyleSheet(url, deferred) {
var attributes = {
type: "text/css",
rel: "stylesheet",
href: url
};
var $link = $("<link/>").attr(attributes);
if (deferred) {
$link.on('load', deferred.resolve).on('error', deferred.reject);
}
$link.appendTo("head");
return $link[0];
}
/**
* getModuleUrl returns different urls for win platform
* so that's why we need a different check here
* @see #getModuleUrl
* @param {!string} pathOrUrl that should be checked if it's absolute
* @return {!boolean} returns true if pathOrUrl is absolute url on win platform
* or when it's absolute path on other platforms
*/
function isAbsolutePathOrUrl(pathOrUrl) {
return brackets.platform === "win" ? PathUtils.isAbsoluteUrl(pathOrUrl) : FileSystem.isAbsolutePath(pathOrUrl);
}
/**
* Parses LESS code and returns a promise that resolves with plain CSS code.
*
* Pass the {@link url} argument to resolve relative URLs contained in the code.
* Make sure URLs in the code are wrapped in quotes, like so:
* background-image: url("image.png");
*
* @param {!string} code LESS code to parse
* @param {?string} url URL to the file containing the code
* @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed
*/
function parseLessCode(code, url) {
var result = new $.Deferred(),
options;
if (url) {
var dir = url.slice(0, url.lastIndexOf("/") + 1),
file = url.slice(dir.length);
options = {
filename: file,
paths: [dir],
rootpath: dir
};
if (isAbsolutePathOrUrl(url)) {
options.currentFileInfo = {
currentDirectory: dir,
entryPath: dir,
filename: url,
rootFilename: url,
rootpath: dir
};
}
}
var parser = new less.Parser(options);
parser.parse(code, function onParse(err, tree) {
if (err) {
result.reject(err);
} else {
try {
result.resolve(tree.toCSS());
} catch (toCSSError) {
result.reject(toCSSError);
}
}
});
return result.promise();
}
/**
* Returns a path to an extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {?string} path Relative path from the extension folder to a file
* @return {!string} The path to the module's folder
**/
function getModulePath(module, path) {
var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1);
if (path) {
modulePath += path;
}
return modulePath;
}
/**
* Returns a URL to an extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {?string} path Relative path from the extension folder to a file
* @return {!string} The URL to the module's folder
**/
function getModuleUrl(module, path) {
var url = encodeURI(getModulePath(module, path));
// On Windows, $.get() fails if the url is a full pathname. To work around this,
// prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname,
// but *doesn't* work if it is prepended with "file://". Go figure.
// However, the prefix "file://localhost" does work.
if (brackets.platform === "win" && url.indexOf(":") !== -1) {
url = "file:///" + url;
}
return url;
}
/**
* Performs a GET request using a path relative to an extension module.
*
* The resulting URL can be retrieved in the resolve callback by accessing
*
* @param {!module} module Module provided by RequireJS
* @param {!string} path Relative path from the extension folder to a file
* @return {!$.Promise} A promise object that is resolved with the contents of the requested file
**/
function loadFile(module, path) {
var url = PathUtils.isAbsoluteUrl(path) ? path : getModuleUrl(module, path),
promise = $.get(url);
return promise;
}
/**
* Loads a style sheet (CSS or LESS) relative to the extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {!string} path Relative path from the extension folder to a CSS or LESS file
* @return {!$.Promise} A promise object that is resolved with an HTML node if the file can be loaded.
*/
function loadStyleSheet(module, path) {
var result = new $.Deferred();
loadFile(module, path)
.done(function (content) {
var url = this.url;
if (url.slice(-5) === ".less") {
parseLessCode(content, url)
.done(function (css) {
result.resolve(addEmbeddedStyleSheet(css));
})
.fail(result.reject);
} else {
var deferred = new $.Deferred(),
link = addLinkedStyleSheet(url, deferred);
deferred
.done(function () {
result.resolve(link);
})
.fail(result.reject);
}
})
.fail(result.reject);
// Summarize error info to console for easier debugging
result.fail(function (error, textStatus, httpError) {
if (error.readyState !== undefined) {
// If first arg is a jQXHR object, the real error info is in the next two args
console.error("[Extension] Unable to read stylesheet " + path + ":", textStatus, httpError);
} else {
console.error("[Extension] Unable to process stylesheet " + path, error);
}
});
return result.promise();
}
/**
* Loads the package.json file in the given extension folder.
*
* @param {string} folder The extension folder.
* @return {$.Promise} A promise object that is resolved with the parsed contents of the package.json file,
* or rejected if there is no package.json or the contents are not valid JSON.
*/
function loadPackageJson(folder) {
var file = FileSystem.getFileForPath(folder + "/package.json"),
result = new $.Deferred();
FileUtils.readAsText(file)
.done(function (text) {
try {
var json = JSON.parse(text);
result.resolve(json);
} catch (e) {
result.reject();
}
})
.fail(function () {
result.reject();
});
return result.promise();
}
exports.addEmbeddedStyleSheet = addEmbeddedStyleSheet;
exports.addLinkedStyleSheet = addLinkedStyleSheet;
exports.parseLessCode = parseLessCode;
exports.getModulePath = getModulePath;
exports.getModuleUrl = getModuleUrl;
exports.loadFile = loadFile;
exports.loadStyleSheet = loadStyleSheet;
exports.loadPackageJson = loadPackageJson;
});
|
/*!
* json-schema-faker library v0.4.1
* http://json-schema-faker.js.org
* @preserve
*
* Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin
* Released under the MIT license
*
* Date: 2017-02-17 19:35:15.530Z
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsf = f()}})(function(){var define,module,exports;return (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(require,module,exports){
"use strict";
var Registry = require("../class/Registry");
// instantiate
var registry = new Registry();
/**
* Custom format API
*
* @see https://github.com/json-schema-faker/json-schema-faker#custom-formats
* @param nameOrFormatMap
* @param callback
* @returns {any}
*/
function formatAPI(nameOrFormatMap, callback) {
if (typeof nameOrFormatMap === 'undefined') {
return registry.list();
}
else if (typeof nameOrFormatMap === 'string') {
if (typeof callback === 'function') {
registry.register(nameOrFormatMap, callback);
}
else {
return registry.get(nameOrFormatMap);
}
}
else {
registry.registerMany(nameOrFormatMap);
}
}
module.exports = formatAPI;
},{"../class/Registry":5}],2:[function(require,module,exports){
"use strict";
var OptionRegistry = require("../class/OptionRegistry");
// instantiate
var registry = new OptionRegistry();
/**
* Custom option API
*
* @param nameOrOptionMap
* @returns {any}
*/
function optionAPI(nameOrOptionMap) {
if (typeof nameOrOptionMap === 'string') {
return registry.get(nameOrOptionMap);
}
else {
return registry.registerMany(nameOrOptionMap);
}
}
module.exports = optionAPI;
},{"../class/OptionRegistry":4}],3:[function(require,module,exports){
"use strict";
var RandExp = require("randexp");
var option = require("../api/option");
// set maximum default, see #193
RandExp.prototype.max = 10;
/**
* Container is used to wrap external libraries (faker, chance, casual, randexp) that are used among the whole codebase. These
* libraries might be configured, customized, etc. and each internal JSF module needs to access those instances instead
* of pure npm module instances. This class supports consistent access to these instances.
*/
var Container = (function () {
function Container() {
// static requires - handle both initial dependency load (deps will be available
// among other modules) as well as they will be included by browserify AST
this.registry = {
faker: null,
chance: null,
casual: null,
// randexp is required for "pattern" values
randexp: RandExp
};
}
/**
* Override dependency given by name
* @param name
* @param callback
*/
Container.prototype.extend = function (name, callback) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency is not allowed.');
}
this.registry[name] = callback(this.registry[name]);
};
/**
* Returns dependency given by name
* @param name
* @returns {Dependency}
*/
Container.prototype.get = function (name) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency doesn\'t exist.');
}
else if (name === 'randexp') {
var RandExp_ = this.registry['randexp'];
// wrapped generator
return function (pattern) {
var re = new RandExp_(pattern);
// apply given setting
re.max = option('defaultRandExpMax');
return re.gen();
};
}
return this.registry[name];
};
/**
* Returns all dependencies
*
* @returns {Registry}
*/
Container.prototype.getAll = function () {
return {
faker: this.get('faker'),
chance: this.get('chance'),
randexp: this.get('randexp'),
casual: this.get('casual')
};
};
return Container;
}());
// TODO move instantiation somewhere else (out from class file)
// instantiate
var container = new Container();
module.exports = container;
},{"../api/option":2,"randexp":169}],4:[function(require,module,exports){
"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 Registry = require("./Registry");
/**
* This class defines a registry for custom formats used within JSF.
*/
var OptionRegistry = (function (_super) {
__extends(OptionRegistry, _super);
function OptionRegistry() {
var _this = _super.call(this) || this;
_this.data['failOnInvalidTypes'] = true;
_this.data['defaultInvalidTypeProduct'] = null;
_this.data['useDefaultValue'] = false;
_this.data['requiredOnly'] = false;
_this.data['maxItems'] = null;
_this.data['maxLength'] = null;
_this.data['defaultMinItems'] = 0;
_this.data['defaultRandExpMax'] = 10;
_this.data['alwaysFakeOptionals'] = false;
return _this;
}
return OptionRegistry;
}(Registry));
module.exports = OptionRegistry;
},{"./Registry":5}],5:[function(require,module,exports){
"use strict";
/**
* This class defines a registry for custom formats used within JSF.
*/
var Registry = (function () {
function Registry() {
// empty by default
this.data = {};
}
/**
* Registers custom format
*/
Registry.prototype.register = function (name, callback) {
this.data[name] = callback;
};
/**
* Register many formats at one shot
*/
Registry.prototype.registerMany = function (formats) {
for (var name in formats) {
this.data[name] = formats[name];
}
};
/**
* Returns element by registry key
*/
Registry.prototype.get = function (name) {
var format = this.data[name];
if (typeof format === 'undefined') {
throw new Error('unknown registry key ' + JSON.stringify(name));
}
return format;
};
/**
* Returns the whole registry content
*/
Registry.prototype.list = function () {
return this.data;
};
return Registry;
}());
module.exports = Registry;
},{}],6:[function(require,module,exports){
// TODO: tsify
"use strict";
function isArray(obj) {
return obj && Array.isArray(obj);
}
function isObject(obj) {
return obj && obj !== null && typeof obj === 'object';
}
function hasNothing(obj) {
if (isArray(obj)) {
return obj.length === 0;
}
if (isObject(obj)) {
return Object.keys(obj).length === 0;
}
return typeof obj === 'undefined' || obj === null;
}
function removeProps(obj, key, parent) {
var i, value, isFullyEmpty = true;
if (isArray(obj)) {
for (i = 0; i < obj.length; ++i) {
value = obj[i];
if (isObject(value)) {
removeProps(value, i, obj);
}
if (hasNothing(value)) {
obj.splice(i--, 1);
}
else {
isFullyEmpty = false;
}
}
}
else {
for (i in obj) {
value = obj[i];
if (isObject(value)) {
removeProps(value, i, obj);
}
if (hasNothing(value)) {
delete obj[i];
}
else {
isFullyEmpty = false;
}
}
}
if (typeof key !== 'undefined' && isFullyEmpty) {
delete parent[key];
removeProps(obj);
}
}
module.exports = function (obj) {
removeProps(obj);
return obj;
};
},{}],7:[function(require,module,exports){
"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 ParseError = (function (_super) {
__extends(ParseError, _super);
function ParseError(message, path) {
var _this = _super.call(this) || this;
_this.path = path;
Error.captureStackTrace(_this, _this.constructor);
_this.name = 'ParseError';
_this.message = message;
_this.path = path;
return _this;
}
return ParseError;
}(Error));
module.exports = ParseError;
},{}],8:[function(require,module,exports){
"use strict";
var inferredProperties = {
array: [
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems'
],
integer: [
'exclusiveMaximum',
'exclusiveMinimum',
'maximum',
'minimum',
'multipleOf'
],
object: [
'additionalProperties',
'dependencies',
'maxProperties',
'minProperties',
'patternProperties',
'properties',
'required'
],
string: [
'maxLength',
'minLength',
'pattern'
]
};
inferredProperties.number = inferredProperties.integer;
var subschemaProperties = [
'additionalItems',
'items',
'additionalProperties',
'dependencies',
'patternProperties',
'properties'
];
/**
* Iterates through all keys of `obj` and:
* - checks whether those keys match properties of a given inferred type
* - makes sure that `obj` is not a subschema; _Do not attempt to infer properties named as subschema containers. The
* reason for this is that any property name within those containers that matches one of the properties used for
* inferring missing type values causes the container itself to get processed which leads to invalid output. (Issue 62)_
*
* @returns {boolean}
*/
function matchesType(obj, lastElementInPath, inferredTypeProperties) {
return Object.keys(obj).filter(function (prop) {
var isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1, inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1;
if (inferredPropertyFound && !isSubschema) {
return true;
}
}).length > 0;
}
/**
* Checks whether given `obj` type might be inferred. The mechanism iterates through all inferred types definitions,
* tries to match allowed properties with properties of given `obj`. Returns type name, if inferred, or null.
*
* @returns {string|null}
*/
function inferType(obj, schemaPath) {
for (var typeName in inferredProperties) {
var lastElementInPath = schemaPath[schemaPath.length - 1];
if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) {
return typeName;
}
}
}
module.exports = inferType;
},{}],9:[function(require,module,exports){
/// <reference path="../index.d.ts" />
"use strict";
/**
* Returns random element of a collection
*
* @param collection
* @returns {T}
*/
function pick(collection) {
return collection[Math.floor(Math.random() * collection.length)];
}
/**
* Returns shuffled collection of elements
*
* @param collection
* @returns {T[]}
*/
function shuffle(collection) {
var tmp, key, copy = collection.slice(), length = collection.length;
for (; length > 0;) {
key = Math.floor(Math.random() * length);
// swap
tmp = copy[--length];
copy[length] = copy[key];
copy[key] = tmp;
}
return copy;
}
/**
* These values determine default range for random.number function
*
* @type {number}
*/
var MIN_NUMBER = -100, MAX_NUMBER = 100;
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
* @see http://stackoverflow.com/a/1527820/769384
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Generates random number according to parameters passed
*
* @param min
* @param max
* @param defMin
* @param defMax
* @param hasPrecision
* @returns {number}
*/
function number(min, max, defMin, defMax, hasPrecision) {
if (hasPrecision === void 0) { hasPrecision = false; }
defMin = typeof defMin === 'undefined' ? MIN_NUMBER : defMin;
defMax = typeof defMax === 'undefined' ? MAX_NUMBER : defMax;
min = typeof min === 'undefined' ? defMin : min;
max = typeof max === 'undefined' ? defMax : max;
if (max < min) {
max += min;
}
var result = getRandomInt(min, max);
if (!hasPrecision) {
return parseInt(result + '', 10);
}
return result;
}
module.exports = {
pick: pick,
shuffle: shuffle,
number: number
};
},{}],10:[function(require,module,exports){
"use strict";
var deref = require("deref");
var traverse = require("./traverse");
var random = require("./random");
var utils = require("./utils");
function isKey(prop) {
return prop === 'enum' || prop === 'default' || prop === 'required' || prop === 'definitions';
}
// TODO provide types
function run(schema, refs, ex) {
var $ = deref();
var _ = {};
try {
return traverse($(schema, refs, ex), [], function reduce(sub, maxReduceDepth) {
if (typeof maxReduceDepth === 'undefined') {
maxReduceDepth = random.number(1, 3);
}
if (!sub) {
return null;
}
if (typeof sub.$ref === 'string') {
var id = sub.$ref;
// match and increment seen references
if (!_[id]) {
_[id] = 0;
}
_[id] += 1;
// cleanup
delete sub.$ref;
if (_[id] > maxReduceDepth) {
delete sub.oneOf;
delete sub.anyOf;
delete sub.allOf;
return sub;
}
utils.merge(sub, $.util.findByRef(id, $.refs));
}
if (Array.isArray(sub.allOf)) {
var schemas = sub.allOf;
delete sub.allOf;
// this is the only case where all sub-schemas
// must be resolved before any merge
schemas.forEach(function (schema) {
utils.merge(sub, reduce(schema, maxReduceDepth + 1));
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
var mix = sub.oneOf || sub.anyOf;
delete sub.anyOf;
delete sub.oneOf;
utils.merge(sub, random.pick(mix));
}
for (var prop in sub) {
if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !isKey(prop)) {
sub[prop] = reduce(sub[prop], maxReduceDepth);
}
}
return sub;
});
}
catch (e) {
if (e.path) {
throw new Error(e.message + ' in ' + '/' + e.path.join('/'));
}
else {
throw e;
}
}
}
module.exports = run;
},{"./random":9,"./traverse":11,"./utils":12,"deref":31}],11:[function(require,module,exports){
"use strict";
var clean = require("./clean");
var random = require("./random");
var ParseError = require("./error");
var inferType = require("./infer");
var types = require("../types/index");
var option = require("../api/option");
function isExternal(schema) {
return schema.faker || schema.chance || schema.casual;
}
function reduceExternal(schema, path) {
if (schema['x-faker']) {
schema.faker = schema['x-faker'];
}
if (schema['x-chance']) {
schema.chance = schema['x-chance'];
}
if (schema['x-casual']) {
schema.casual = schema['x-casual'];
}
var count = (schema.faker !== undefined ? 1 : 0) +
(schema.chance !== undefined ? 1 : 0) +
(schema.casual !== undefined ? 1 : 0);
if (count > 1) {
throw new ParseError('ambiguous generator mixing faker, chance or casual: ' + JSON.stringify(schema), path);
}
return schema;
}
// TODO provide types
function traverse(schema, path, resolve) {
resolve(schema);
if (Array.isArray(schema["enum"])) {
return random.pick(schema["enum"]);
}
if (option('useDefaultValue') && 'default' in schema) {
return schema["default"];
}
// TODO remove the ugly overcome
var type = schema.type;
if (Array.isArray(type)) {
type = random.pick(type);
}
else if (typeof type === 'undefined') {
// Attempt to infer the type
type = inferType(schema, path) || type;
}
schema = reduceExternal(schema, path);
if (isExternal(schema)) {
type = 'external';
}
if (typeof type === 'string') {
if (!types[type]) {
if (option('failOnInvalidTypes')) {
throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type']));
}
else {
return option('defaultInvalidTypeProduct');
}
}
else {
try {
return types[type](schema, path, resolve, traverse);
}
catch (e) {
if (typeof e.path === 'undefined') {
throw new ParseError(e.message, path);
}
throw e;
}
}
}
var copy = {};
if (Array.isArray(schema)) {
copy = [];
}
for (var prop in schema) {
if (typeof schema[prop] === 'object' && prop !== 'definitions') {
copy[prop] = traverse(schema[prop], path.concat([prop]), resolve);
}
else {
copy[prop] = schema[prop];
}
}
return clean(copy);
}
module.exports = traverse;
},{"../api/option":2,"../types/index":24,"./clean":6,"./error":7,"./infer":8,"./random":9}],12:[function(require,module,exports){
"use strict";
function getSubAttribute(obj, dotSeparatedKey) {
var keyElements = dotSeparatedKey.split('.');
while (keyElements.length) {
var prop = keyElements.shift();
if (!obj[prop]) {
break;
}
obj = obj[prop];
}
return obj;
}
/**
* Returns true/false whether the object parameter has its own properties defined
*
* @param obj
* @param properties
* @returns {boolean}
*/
function hasProperties(obj) {
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments[_i];
}
return properties.filter(function (key) {
return typeof obj[key] !== 'undefined';
}).length > 0;
}
/**
* Returns typecasted value.
* External generators (faker, chance, casual) may return data in non-expected formats, such as string, when you might expect an
* integer. This function is used to force the typecast.
*
* @param value
* @param targetType
* @returns {any}
*/
function typecast(value, targetType) {
switch (targetType) {
case 'integer':
return parseInt(value, 10);
case 'number':
return parseFloat(value);
case 'string':
return '' + value;
case 'boolean':
return !!value;
default:
return value;
}
}
function clone(arr) {
var out = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
out[index] = Array.isArray(item) ? clone(item) : merge({}, item);
}
else {
out[index] = item;
}
});
return out;
}
// TODO refactor merge function
function merge(a, b) {
for (var key in b) {
if (typeof b[key] !== 'object' || b[key] === null) {
a[key] = b[key];
}
else if (Array.isArray(b[key])) {
a[key] = (a[key] || []).concat(clone(b[key]));
}
else if (typeof a[key] !== 'object' || a[key] === null || Array.isArray(a[key])) {
a[key] = merge({}, b[key]);
}
else {
a[key] = merge(a[key], b[key]);
}
}
return a;
}
module.exports = {
getSubAttribute: getSubAttribute,
hasProperties: hasProperties,
typecast: typecast,
clone: clone,
merge: merge
};
},{}],13:[function(require,module,exports){
"use strict";
/**
* Generates randomized boolean value.
*
* @returns {boolean}
*/
function booleanGenerator() {
return Math.random() > 0.5;
}
module.exports = booleanGenerator;
},{}],14:[function(require,module,exports){
"use strict";
var container = require("../class/Container");
var randexp = container.get('randexp');
/**
* Predefined core formats
* @type {[key: string]: string}
*/
var regexps = {
email: '[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}',
hostname: '[a-zA-Z]{1,33}\\.[a-z]{2,4}',
ipv6: '[a-f\\d]{4}(:[a-f\\d]{4}){7}',
uri: '[a-zA-Z][a-zA-Z0-9+-.]*'
};
/**
* Generates randomized string basing on a built-in regex format
*
* @param coreFormat
* @returns {string}
*/
function coreFormatGenerator(coreFormat) {
return randexp(regexps[coreFormat]).replace(/\{(\w+)\}/, function (match, key) {
return randexp(regexps[key]);
});
}
module.exports = coreFormatGenerator;
},{"../class/Container":3}],15:[function(require,module,exports){
"use strict";
var random = require("../core/random");
/**
* Generates randomized date time ISO format string.
*
* @returns {string}
*/
function dateTimeGenerator() {
return new Date(random.number(0, 100000000000000)).toISOString();
}
module.exports = dateTimeGenerator;
},{"../core/random":9}],16:[function(require,module,exports){
"use strict";
var random = require("../core/random");
/**
* Generates randomized ipv4 address.
*
* @returns {string}
*/
function ipv4Generator() {
return [0, 0, 0, 0].map(function () {
return random.number(0, 255);
}).join('.');
}
module.exports = ipv4Generator;
},{"../core/random":9}],17:[function(require,module,exports){
"use strict";
/**
* Generates null value.
*
* @returns {null}
*/
function nullGenerator() {
return null;
}
module.exports = nullGenerator;
},{}],18:[function(require,module,exports){
"use strict";
var words = require("../generators/words");
var random = require("../core/random");
/**
* Helper function used by thunkGenerator to produce some words for the final result.
*
* @returns {string}
*/
function produce() {
var length = random.number(1, 5);
return words(length).join(' ');
}
/**
* Generates randomized concatenated string based on words generator.
*
* @returns {string}
*/
function thunkGenerator(min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 140; }
var min = Math.max(0, min), max = random.number(min, max), result = produce();
// append until length is reached
while (result.length < min) {
result += produce();
}
// cut if needed
if (result.length > max) {
result = result.substr(0, max);
}
return result;
}
module.exports = thunkGenerator;
},{"../core/random":9,"../generators/words":19}],19:[function(require,module,exports){
"use strict";
var random = require("../core/random");
var LIPSUM_WORDS = ('Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore'
+ ' et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea'
+ ' commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla'
+ ' pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est'
+ ' laborum').split(' ');
/**
* Generates randomized array of single lorem ipsum words.
*
* @param length
* @returns {Array.<string>}
*/
function wordsGenerator(length) {
var words = random.shuffle(LIPSUM_WORDS);
return words.slice(0, length);
}
module.exports = wordsGenerator;
},{"../core/random":9}],20:[function(require,module,exports){
"use strict";
var container = require("./class/Container");
var format = require("./api/format");
var option = require("./api/option");
var run = require("./core/run");
var jsf = function (schema, refs) {
return run(schema, refs);
};
jsf.format = format;
jsf.option = option;
// returns itself for chaining
jsf.extend = function (name, cb) {
container.extend(name, cb);
return jsf;
};
jsf.version = '0.4.0';
module.exports = jsf;
},{"./api/format":1,"./api/option":2,"./class/Container":3,"./core/run":10}],21:[function(require,module,exports){
"use strict";
var random = require("../core/random");
var utils = require("../core/utils");
var ParseError = require("../core/error");
var option = require("../api/option");
// TODO provide types
function unique(path, items, value, sample, resolve, traverseCallback) {
var tmp = [], seen = [];
function walk(obj) {
var json = JSON.stringify(obj);
if (seen.indexOf(json) === -1) {
seen.push(json);
tmp.push(obj);
}
}
items.forEach(walk);
// TODO: find a better solution?
var limit = 100;
while (tmp.length !== items.length) {
walk(traverseCallback(value.items || sample, path, resolve));
if (!limit--) {
break;
}
}
return tmp;
}
// TODO provide types
var arrayType = function arrayType(value, path, resolve, traverseCallback) {
var items = [];
if (!(value.items || value.additionalItems)) {
if (utils.hasProperties(value, 'minItems', 'maxItems', 'uniqueItems')) {
throw new ParseError('missing items for ' + JSON.stringify(value), path);
}
return items;
}
// see http://stackoverflow.com/a/38355228/769384
// after type guards support subproperties (in TS 2.0) we can simplify below to (value.items instanceof Array)
// so that value.items.map becomes recognized for typescript compiler
var tmpItems = value.items;
if (tmpItems instanceof Array) {
return Array.prototype.concat.apply(items, tmpItems.map(function (item, key) {
var itemSubpath = path.concat(['items', key + '']);
return traverseCallback(item, itemSubpath, resolve);
}));
}
var minItems = value.minItems;
var maxItems = value.maxItems;
if (option('defaultMinItems') && minItems === undefined) {
// fix boundaries
minItems = !maxItems
? option('defaultMinItems')
: Math.min(option('defaultMinItems'), maxItems);
}
if (option('maxItems')) {
// Don't allow user to set max items above our maximum
if (maxItems && maxItems > option('maxItems')) {
maxItems = option('maxItems');
}
// Don't allow user to set min items above our maximum
if (minItems && minItems > option('maxItems')) {
minItems = maxItems;
}
}
var length = random.number(minItems, maxItems, 1, 5),
// TODO below looks bad. Should additionalItems be copied as-is?
sample = typeof value.additionalItems === 'object' ? value.additionalItems : {};
for (var current = items.length; current < length; current++) {
var itemSubpath = path.concat(['items', current + '']);
var element = traverseCallback(value.items || sample, itemSubpath, resolve);
items.push(element);
}
if (value.uniqueItems) {
return unique(path.concat(['items']), items, value, sample, resolve, traverseCallback);
}
return items;
};
module.exports = arrayType;
},{"../api/option":2,"../core/error":7,"../core/random":9,"../core/utils":12}],22:[function(require,module,exports){
"use strict";
var booleanGenerator = require("../generators/boolean");
var booleanType = booleanGenerator;
module.exports = booleanType;
},{"../generators/boolean":13}],23:[function(require,module,exports){
"use strict";
var utils = require("../core/utils");
var container = require("../class/Container");
var externalType = function externalType(value, path) {
var libraryName = value.faker ? 'faker' : (value.chance ? 'chance' : 'casual'), libraryModule = container.get(libraryName), key = value.faker || value.chance || value.casual, path = key, args = [];
if (typeof path === 'object') {
path = Object.keys(path)[0];
if (Array.isArray(key[path])) {
args = key[path];
}
else {
args.push(key[path]);
}
}
var genFunction = utils.getSubAttribute(libraryModule, path);
try {
// see #116, #117 - faker.js 3.1.0 introduced local dependencies between generators
// making jsf break after upgrading from 3.0.1
var contextObject = libraryModule;
if (libraryName === 'faker') {
var parts = path.split('.');
while (parts.length > 1) {
contextObject = libraryModule[parts.shift()];
}
genFunction = contextObject[parts[0]];
}
}
catch (e) {
throw new Error('cannot resolve ' + libraryName + '-generator for ' + JSON.stringify(key));
}
if (typeof genFunction !== 'function') {
if (libraryName === 'casual') {
return utils.typecast(genFunction, value.type);
}
throw new Error('unknown ' + libraryName + '-generator for ' + JSON.stringify(key));
}
var result = genFunction.apply(contextObject, args);
return utils.typecast(result, value.type);
};
module.exports = externalType;
},{"../class/Container":3,"../core/utils":12}],24:[function(require,module,exports){
"use strict";
var _boolean = require("./boolean");
var _null = require("./null");
var _array = require("./array");
var _integer = require("./integer");
var _number = require("./number");
var _object = require("./object");
var _string = require("./string");
var _external = require("./external");
var typeMap = {
boolean: _boolean,
"null": _null,
array: _array,
integer: _integer,
number: _number,
object: _object,
string: _string,
external: _external
};
module.exports = typeMap;
},{"./array":21,"./boolean":22,"./external":23,"./integer":25,"./null":26,"./number":27,"./object":28,"./string":29}],25:[function(require,module,exports){
"use strict";
var number = require("./number");
// The `integer` type is just a wrapper for the `number` type. The `number` type
// returns floating point numbers, and `integer` type truncates the fraction
// part, leaving the result as an integer.
var integerType = function integerType(value) {
var generated = number(value);
// whether the generated number is positive or negative, need to use either
// floor (positive) or ceil (negative) function to get rid of the fraction
return generated > 0 ? Math.floor(generated) : Math.ceil(generated);
};
module.exports = integerType;
},{"./number":27}],26:[function(require,module,exports){
"use strict";
var nullGenerator = require("../generators/null");
var nullType = nullGenerator;
module.exports = nullType;
},{"../generators/null":17}],27:[function(require,module,exports){
"use strict";
var random = require("../core/random");
var MIN_INTEGER = -100000000, MAX_INTEGER = 100000000;
var numberType = function numberType(value) {
var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum, multipleOf = value.multipleOf;
if (multipleOf) {
max = Math.floor(max / multipleOf) * multipleOf;
min = Math.ceil(min / multipleOf) * multipleOf;
}
if (value.exclusiveMinimum && value.minimum && min === value.minimum) {
min += multipleOf || 1;
}
if (value.exclusiveMaximum && value.maximum && max === value.maximum) {
max -= multipleOf || 1;
}
if (min > max) {
return NaN;
}
if (multipleOf) {
return Math.floor(random.number(min, max) / multipleOf) * multipleOf;
}
return random.number(min, max, undefined, undefined, true);
};
module.exports = numberType;
},{"../core/random":9}],28:[function(require,module,exports){
"use strict";
var container = require("../class/Container");
var random = require("../core/random");
var words = require("../generators/words");
var utils = require("../core/utils");
var option = require("../api/option");
var ParseError = require("../core/error");
var randexp = container.get('randexp');
// fallback generator
var anyType = { type: ['string', 'number', 'integer', 'boolean'] };
// TODO provide types
var objectType = function objectType(value, path, resolve, traverseCallback) {
var props = {};
var properties = value.properties || {};
var patternProperties = value.patternProperties || {};
var requiredProperties = (value.required || []).slice();
var allowsAdditional = value.additionalProperties === false ? false : true;
var propertyKeys = Object.keys(properties);
var patternPropertyKeys = Object.keys(patternProperties);
var additionalProperties = allowsAdditional
? (value.additionalProperties === true ? {} : value.additionalProperties)
: null;
if (!allowsAdditional &&
propertyKeys.length === 0 &&
patternPropertyKeys.length === 0 &&
utils.hasProperties(value, 'minProperties', 'maxProperties', 'dependencies', 'required')) {
throw new ParseError('missing properties for:\n' + JSON.stringify(value, null, ' '), path);
}
if (option('requiredOnly') === true) {
requiredProperties.forEach(function (key) {
if (properties[key]) {
props[key] = properties[key];
}
});
return traverseCallback(props, path.concat(['properties']), resolve);
}
var min = Math.max(value.minProperties || 0, requiredProperties.length);
var max = Math.max(value.maxProperties || random.number(min, min + 5));
random.shuffle(patternPropertyKeys.concat(propertyKeys)).forEach(function (_key) {
if (requiredProperties.indexOf(_key) === -1) {
requiredProperties.push(_key);
}
});
// properties are read from right-to-left
var _props = option('alwaysFakeOptionals') ? requiredProperties
: requiredProperties.slice(0, random.number(min, max));
_props.forEach(function (key) {
// first ones are the required properies
if (properties[key]) {
props[key] = properties[key];
}
else {
var found;
// then try patternProperties
patternPropertyKeys.forEach(function (_key) {
if (key.match(new RegExp(_key))) {
found = true;
props[randexp(key)] = patternProperties[_key];
}
});
if (!found) {
// try patternProperties again,
var subschema = patternProperties[key] || additionalProperties;
if (subschema) {
// otherwise we can use additionalProperties?
props[patternProperties[key] ? randexp(key) : key] = subschema;
}
}
}
});
var current = Object.keys(props).length;
while (true) {
if (!(patternPropertyKeys.length || allowsAdditional)) {
break;
}
if (current >= min) {
break;
}
if (allowsAdditional) {
var word = words(1) + randexp('[a-f\\d]{1,3}');
if (!props[word]) {
props[word] = additionalProperties || anyType;
current += 1;
}
}
patternPropertyKeys.forEach(function (_key) {
var word = randexp(_key);
if (!props[word]) {
props[word] = patternProperties[_key];
current += 1;
}
});
}
if (!allowsAdditional && current < min) {
throw new ParseError('properties constraints were too strong to successfully generate a valid object for:\n' +
JSON.stringify(value, null, ' '), path);
}
return traverseCallback(props, path.concat(['properties']), resolve);
};
module.exports = objectType;
},{"../api/option":2,"../class/Container":3,"../core/error":7,"../core/random":9,"../core/utils":12,"../generators/words":19}],29:[function(require,module,exports){
"use strict";
var thunk = require("../generators/thunk");
var ipv4 = require("../generators/ipv4");
var dateTime = require("../generators/dateTime");
var coreFormat = require("../generators/coreFormat");
var format = require("../api/format");
var option = require("../api/option");
var container = require("../class/Container");
var randexp = container.get('randexp');
function generateFormat(value) {
switch (value.format) {
case 'date-time':
return dateTime();
case 'ipv4':
return ipv4();
case 'regex':
// TODO: discuss
return '.+?';
case 'email':
case 'hostname':
case 'ipv6':
case 'uri':
return coreFormat(value.format);
default:
var callback = format(value.format);
return callback(container.getAll(), value);
}
}
var stringType = function stringType(value) {
var output;
var minLength = value.minLength;
var maxLength = value.maxLength;
if (option('maxLength')) {
// Don't allow user to set max length above our maximum
if (maxLength && maxLength > option('maxLength')) {
maxLength = option('maxLength');
}
// Don't allow user to set min length above our maximum
if (minLength && minLength > option('maxLength')) {
minLength = option('maxLength');
}
}
if (value.format) {
output = generateFormat(value);
}
else if (value.pattern) {
output = randexp(value.pattern);
}
else {
output = thunk(minLength, maxLength);
}
while (output.length < minLength) {
output += Math.random() > 0.7 ? thunk() : randexp('.+');
}
if (output.length > maxLength) {
output = output.substr(0, maxLength);
}
return output;
};
module.exports = stringType;
},{"../api/format":1,"../api/option":2,"../class/Container":3,"../generators/coreFormat":14,"../generators/dateTime":15,"../generators/ipv4":16,"../generators/thunk":18}],30:[function(require,module,exports){
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Viacheslav Lotsmanov
*
* 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.
*/
'use strict';
function isSpecificValue(val) {
return (
val instanceof Buffer
|| val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
function cloneSpecificValue(val) {
if (val instanceof Buffer) {
var x = new Buffer(val.length);
val.copy(x);
return x;
} else if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('Unexpected situation');
}
}
/**
* Recursive cloning array.
*/
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
/**
* Extening object that entered in first argument.
*
* Returns extended object or false if have no target object or incorrect type.
*
* If you wish to clone source object (without modify it), just use empty new
* object as first argument, like this:
* deepExtend({}, yourObj_1, [yourObj_N]);
*/
var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
// convert arguments to array and cut off target object
var args = Array.prototype.slice.call(arguments, 1);
var val, src, clone;
args.forEach(function (obj) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
}
},{}],31:[function(require,module,exports){
'use strict';
var $ = require('./util/helpers');
$.findByRef = require('./util/find-reference');
$.resolveSchema = require('./util/resolve-schema');
$.normalizeSchema = require('./util/normalize-schema');
var instance = module.exports = function() {
function $ref(fakeroot, schema, refs, ex) {
if (typeof fakeroot === 'object') {
ex = refs;
refs = schema;
schema = fakeroot;
fakeroot = undefined;
}
if (typeof schema !== 'object') {
throw new Error('schema must be an object');
}
if (typeof refs === 'object' && refs !== null) {
var aux = refs;
refs = [];
for (var k in aux) {
aux[k].id = aux[k].id || k;
refs.push(aux[k]);
}
}
if (typeof refs !== 'undefined' && !Array.isArray(refs)) {
ex = !!refs;
refs = [];
}
function push(ref) {
if (typeof ref.id === 'string') {
var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, '');
if (id.indexOf('#') > -1) {
var parts = id.split('#');
if (parts[1].charAt() === '/') {
id = parts[0];
} else {
id = parts[1] || parts[0];
}
}
if (!$ref.refs[id]) {
$ref.refs[id] = ref;
}
}
}
(refs || []).concat([schema]).forEach(function(ref) {
schema = $.normalizeSchema(fakeroot, ref, push);
push(schema);
});
return $.resolveSchema(schema, $ref.refs, ex);
}
$ref.refs = {};
$ref.util = $;
return $ref;
};
instance.util = $;
},{"./util/find-reference":33,"./util/helpers":34,"./util/normalize-schema":35,"./util/resolve-schema":36}],32:[function(require,module,exports){
'use strict';
var clone = module.exports = function(obj, seen) {
seen = seen || [];
if (seen.indexOf(obj) > -1) {
throw new Error('unable dereference circular structures');
}
if (!obj || typeof obj !== 'object') {
return obj;
}
seen = seen.concat([obj]);
var target = Array.isArray(obj) ? [] : {};
function copy(key, value) {
target[key] = clone(value, seen);
}
if (Array.isArray(target)) {
obj.forEach(function(value, key) {
copy(key, value);
});
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
Object.keys(obj).forEach(function(key) {
copy(key, obj[key]);
});
}
return target;
};
},{}],33:[function(require,module,exports){
'use strict';
var $ = require('./helpers');
function get(obj, path) {
var hash = path.split('#')[1];
var parts = hash.split('/').slice(1);
while (parts.length) {
var key = decodeURIComponent(parts.shift()).replace(/~1/g, '/').replace(/~0/g, '~');
if (typeof obj[key] === 'undefined') {
throw new Error('JSON pointer not found: ' + path);
}
obj = obj[key];
}
return obj;
}
var find = module.exports = function(id, refs) {
var target = refs[id] || refs[id.split('#')[1]] || refs[$.getDocumentURI(id)];
if (target) {
target = id.indexOf('#/') > -1 ? get(target, id) : target;
} else {
for (var key in refs) {
if ($.resolveURL(refs[key].id, id) === refs[key].id) {
target = refs[key];
break;
}
}
}
if (!target) {
throw new Error('Reference not found: ' + id);
}
while (target.$ref) {
target = find(target.$ref, refs);
}
return target;
};
},{"./helpers":34}],34:[function(require,module,exports){
'use strict';
// https://gist.github.com/pjt33/efb2f1134bab986113fd
function URLUtils(url, baseURL) {
// remove leading ./
url = url.replace(/^\.\//, '');
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@]*)(?::([^:@]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
if (!m) {
throw new RangeError();
}
var href = m[0] || '';
var protocol = m[1] || '';
var username = m[2] || '';
var password = m[3] || '';
var host = m[4] || '';
var hostname = m[5] || '';
var port = m[6] || '';
var pathname = m[7] || '';
var search = m[8] || '';
var hash = m[9] || '';
if (baseURL !== undefined) {
var base = new URLUtils(baseURL);
var flag = protocol === '' && host === '' && username === '';
if (flag && pathname === '' && search === '') {
search = base.search;
}
if (flag && pathname.charAt(0) !== '/') {
pathname = (pathname !== '' ? (base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + pathname) : base.pathname);
}
// dot segments removal
var output = [];
pathname.replace(/\/?[^\/]+/g, function(p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
pathname = output.join('') || '/';
if (flag) {
port = base.port;
hostname = base.hostname;
host = base.host;
password = base.password;
username = base.username;
}
if (protocol === '') {
protocol = base.protocol;
}
href = protocol + (host !== '' ? '//' : '') + (username !== '' ? username + (password !== '' ? ':' + password : '') + '@' : '') + host + pathname + search + hash;
}
this.href = href;
this.origin = protocol + (host !== '' ? '//' + host : '');
this.protocol = protocol;
this.username = username;
this.password = password;
this.host = host;
this.hostname = hostname;
this.port = port;
this.pathname = pathname;
this.search = search;
this.hash = hash;
}
function isURL(path) {
if (typeof path === 'string' && /^\w+:\/\//.test(path)) {
return true;
}
}
function parseURI(href, base) {
return new URLUtils(href, base);
}
function resolveURL(base, href) {
base = base || 'http://json-schema.org/schema#';
href = parseURI(href, base);
base = parseURI(base);
if (base.hash && !href.hash) {
return href.href + base.hash;
}
return href.href;
}
function getDocumentURI(uri) {
return typeof uri === 'string' && uri.split('#')[0];
}
function isKeyword(prop) {
return prop === 'enum' || prop === 'default' || prop === 'required';
}
module.exports = {
isURL: isURL,
parseURI: parseURI,
isKeyword: isKeyword,
resolveURL: resolveURL,
getDocumentURI: getDocumentURI
};
},{}],35:[function(require,module,exports){
'use strict';
var $ = require('./helpers');
var cloneObj = require('./clone-obj');
var SCHEMA_URI = [
'http://json-schema.org/schema#',
'http://json-schema.org/draft-04/schema#'
];
function expand(obj, parent, callback) {
if (obj) {
var id = typeof obj.id === 'string' ? obj.id : '#';
if (!$.isURL(id)) {
id = $.resolveURL(parent === id ? null : parent, id);
}
if (typeof obj.$ref === 'string' && !$.isURL(obj.$ref)) {
obj.$ref = $.resolveURL(id, obj.$ref);
}
if (typeof obj.id === 'string') {
obj.id = parent = id;
}
}
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object' && value !== null && !$.isKeyword(key)) {
expand(value, parent, callback);
}
}
if (typeof callback === 'function') {
callback(obj);
}
}
module.exports = function(fakeroot, schema, push) {
if (typeof fakeroot === 'object') {
push = schema;
schema = fakeroot;
fakeroot = null;
}
var base = fakeroot || '',
copy = cloneObj(schema);
if (copy.$schema && SCHEMA_URI.indexOf(copy.$schema) === -1) {
throw new Error('Unsupported schema version (v4 only)');
}
base = $.resolveURL(copy.$schema || SCHEMA_URI[0], base);
expand(copy, $.resolveURL(copy.id || '#', base), push);
copy.id = copy.id || base;
return copy;
};
},{"./clone-obj":32,"./helpers":34}],36:[function(require,module,exports){
'use strict';
var $ = require('./helpers');
var find = require('./find-reference');
var deepExtend = require('deep-extend');
function copy(obj, refs, parent, resolve) {
var target = Array.isArray(obj) ? [] : {};
if (typeof obj.$ref === 'string') {
var base = $.getDocumentURI(obj.$ref);
if (parent !== base || (resolve && obj.$ref.indexOf('#/') > -1)) {
var fixed = find(obj.$ref, refs);
deepExtend(obj, fixed);
delete obj.$ref;
delete obj.id;
}
}
for (var prop in obj) {
if (typeof obj[prop] === 'object' && obj[prop] !== null && !$.isKeyword(prop)) {
target[prop] = copy(obj[prop], refs, parent, resolve);
} else {
target[prop] = obj[prop];
}
}
return target;
}
module.exports = function(obj, refs, resolve) {
var fixedId = $.resolveURL(obj.$schema, obj.id),
parent = $.getDocumentURI(fixedId);
return copy(obj, refs, parent, resolve);
};
},{"./find-reference":33,"./helpers":34,"deep-extend":30}],37:[function(require,module,exports){
//protected helper class
function _SubRange(low, high) {
this.low = low;
this.high = high;
this.length = 1 + high - low;
}
_SubRange.prototype.overlaps = function (range) {
return !(this.high < range.low || this.low > range.high);
};
_SubRange.prototype.touches = function (range) {
return !(this.high + 1 < range.low || this.low - 1 > range.high);
};
//returns inclusive combination of _SubRanges as a _SubRange
_SubRange.prototype.add = function (range) {
return this.touches(range) && new _SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high));
};
//returns subtraction of _SubRanges as an array of _SubRanges (there's a case where subtraction divides it in 2)
_SubRange.prototype.subtract = function (range) {
if (!this.overlaps(range)) return false;
if (range.low <= this.low && range.high >= this.high) return [];
if (range.low > this.low && range.high < this.high) return [new _SubRange(this.low, range.low - 1), new _SubRange(range.high + 1, this.high)];
if (range.low <= this.low) return [new _SubRange(range.high + 1, this.high)];
return [new _SubRange(this.low, range.low - 1)];
};
_SubRange.prototype.toString = function () {
if (this.low == this.high) return this.low.toString();
return this.low + '-' + this.high;
};
_SubRange.prototype.clone = function () {
return new _SubRange(this.low, this.high);
};
function DiscontinuousRange(a, b) {
if (this instanceof DiscontinuousRange) {
this.ranges = [];
this.length = 0;
if (a !== undefined) this.add(a, b);
} else {
return new DiscontinuousRange(a, b);
}
}
function _update_length(self) {
self.length = self.ranges.reduce(function (previous, range) {return previous + range.length}, 0);
}
DiscontinuousRange.prototype.add = function (a, b) {
var self = this;
function _add(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.touches(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.touches(self.ranges[i])) {
subrange = subrange.add(self.ranges[i]);
i++;
}
new_ranges.push(subrange);
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_add);
} else {
if (a instanceof _SubRange) {
_add(a);
} else {
if (b === undefined) b = a;
_add(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.subtract = function (a, b) {
var self = this;
function _subtract(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.overlaps(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.overlaps(self.ranges[i])) {
new_ranges = new_ranges.concat(self.ranges[i].subtract(subrange));
i++;
}
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_subtract);
} else {
if (a instanceof _SubRange) {
_subtract(a);
} else {
if (b === undefined) b = a;
_subtract(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.index = function (index) {
var i = 0;
while (i < this.ranges.length && this.ranges[i].length <= index) {
index -= this.ranges[i].length;
i++;
}
if (i >= this.ranges.length) return null;
return this.ranges[i].low + index;
};
DiscontinuousRange.prototype.toString = function () {
return '[ ' + this.ranges.join(', ') + ' ]'
};
DiscontinuousRange.prototype.clone = function () {
return new DiscontinuousRange(this);
};
module.exports = DiscontinuousRange;
},{}],38:[function(require,module,exports){
function Address (faker) {
var f = faker.fake,
Helpers = faker.helpers;
this.zipCode = function(format) {
// if zip format is not specified, use the zip format defined for the locale
if (typeof format === 'undefined') {
var localeFormat = faker.definitions.address.postcode;
if (typeof localeFormat === 'string') {
format = localeFormat;
} else {
format = faker.random.arrayElement(localeFormat);
}
}
return Helpers.replaceSymbols(format);
}
this.city = function (format) {
var formats = [
'{{address.cityPrefix}} {{name.firstName}} {{address.citySuffix}}',
'{{address.cityPrefix}} {{name.firstName}}',
'{{name.firstName}} {{address.citySuffix}}',
'{{name.lastName}} {{address.citySuffix}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
this.cityPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.city_prefix);
}
this.citySuffix = function () {
return faker.random.arrayElement(faker.definitions.address.city_suffix);
}
this.streetName = function () {
var result;
var suffix = faker.address.streetSuffix();
if (suffix !== "") {
suffix = " " + suffix
}
switch (faker.random.number(1)) {
case 0:
result = faker.name.lastName() + suffix;
break;
case 1:
result = faker.name.firstName() + suffix;
break;
}
return result;
}
//
// TODO: change all these methods that accept a boolean to instead accept an options hash.
//
this.streetAddress = function (useFullAddress) {
if (useFullAddress === undefined) { useFullAddress = false; }
var address = "";
switch (faker.random.number(2)) {
case 0:
address = Helpers.replaceSymbolWithNumber("#####") + " " + faker.address.streetName();
break;
case 1:
address = Helpers.replaceSymbolWithNumber("####") + " " + faker.address.streetName();
break;
case 2:
address = Helpers.replaceSymbolWithNumber("###") + " " + faker.address.streetName();
break;
}
return useFullAddress ? (address + " " + faker.address.secondaryAddress()) : address;
}
this.streetSuffix = function () {
return faker.random.arrayElement(faker.definitions.address.street_suffix);
}
this.streetPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.street_prefix);
}
this.secondaryAddress = function () {
return Helpers.replaceSymbolWithNumber(faker.random.arrayElement(
[
'Apt. ###',
'Suite ###'
]
));
}
this.county = function () {
return faker.random.arrayElement(faker.definitions.address.county);
}
this.country = function () {
return faker.random.arrayElement(faker.definitions.address.country);
}
this.countryCode = function () {
return faker.random.arrayElement(faker.definitions.address.country_code);
}
this.state = function (useAbbr) {
return faker.random.arrayElement(faker.definitions.address.state);
}
this.stateAbbr = function () {
return faker.random.arrayElement(faker.definitions.address.state_abbr);
}
this.latitude = function () {
return (faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4);
}
this.longitude = function () {
return (faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4);
}
return this;
}
module.exports = Address;
},{}],39:[function(require,module,exports){
var Commerce = function (faker) {
var self = this;
self.color = function() {
return faker.random.arrayElement(faker.definitions.commerce.color);
};
self.department = function(max, fixedAmount) {
return faker.random.arrayElement(faker.definitions.commerce.department);
/*
max = max || 3;
var num = Math.floor((Math.random() * max) + 1);
if (fixedAmount) {
num = max;
}
var categories = faker.commerce.categories(num);
if(num > 1) {
return faker.commerce.mergeCategories(categories);
}
return categories[0];
*/
};
self.productName = function() {
return faker.commerce.productAdjective() + " " +
faker.commerce.productMaterial() + " " +
faker.commerce.product();
};
self.price = function(min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
if(min < 0 || max < 0) {
return symbol + 0.00;
}
return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
};
/*
self.categories = function(num) {
var categories = [];
do {
var category = faker.random.arrayElement(faker.definitions.commerce.department);
if(categories.indexOf(category) === -1) {
categories.push(category);
}
} while(categories.length < num);
return categories;
};
*/
/*
self.mergeCategories = function(categories) {
var separator = faker.definitions.separator || " &";
// TODO: find undefined here
categories = categories || faker.definitions.commerce.categories;
var commaSeparated = categories.slice(0, -1).join(', ');
return [commaSeparated, categories[categories.length - 1]].join(separator + " ");
};
*/
self.productAdjective = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective);
};
self.productMaterial = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.material);
};
self.product = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.product);
}
return self;
};
module['exports'] = Commerce;
},{}],40:[function(require,module,exports){
var Company = function (faker) {
var self = this;
var f = faker.fake;
this.suffixes = function () {
// Don't want the source array exposed to modification, so return a copy
return faker.definitions.company.suffix.slice(0);
}
this.companyName = function (format) {
var formats = [
'{{name.lastName}} {{company.companySuffix}}',
'{{name.lastName}} - {{name.lastName}}',
'{{name.lastName}}, {{name.lastName}} and {{name.lastName}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
this.companySuffix = function () {
return faker.random.arrayElement(faker.company.suffixes());
}
this.catchPhrase = function () {
return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}')
}
this.bs = function () {
return f('{{company.bsAdjective}} {{company.bsBuzz}} {{company.bsNoun}}');
}
this.catchPhraseAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.adjective);
}
this.catchPhraseDescriptor = function () {
return faker.random.arrayElement(faker.definitions.company.descriptor);
}
this.catchPhraseNoun = function () {
return faker.random.arrayElement(faker.definitions.company.noun);
}
this.bsAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.bs_adjective);
}
this.bsBuzz = function () {
return faker.random.arrayElement(faker.definitions.company.bs_verb);
}
this.bsNoun = function () {
return faker.random.arrayElement(faker.definitions.company.bs_noun);
}
}
module['exports'] = Company;
},{}],41:[function(require,module,exports){
var _Date = function (faker) {
var self = this;
self.past = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var past = date.getTime();
past -= faker.random.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);
return date;
};
self.future = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var future = date.getTime();
future += faker.random.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);
return date;
};
self.between = function (from, to) {
var fromMilli = Date.parse(from);
var dateOffset = faker.random.number(Date.parse(to) - fromMilli);
var newDate = new Date(fromMilli + dateOffset);
return newDate;
};
self.recent = function (days) {
var date = new Date();
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};
var future = date.getTime();
future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);
return date;
};
self.month = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.month[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.month[type];
return faker.random.arrayElement(source);
};
self.weekday = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.weekday[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.weekday[type];
return faker.random.arrayElement(source);
};
return self;
};
module['exports'] = _Date;
},{}],42:[function(require,module,exports){
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
this.fake = function fake (str) {
// setup default response as empty string
var res = '';
// if incoming str parameter is not provided, return error message
if (typeof str !== 'string' || str.length === 0) {
res = 'string parameter is required!';
return res;
}
// find first matching {{ and }}
var start = str.search('{{');
var end = str.search('}}');
// if no {{ and }} is found, we are done
if (start === -1 && end === -1) {
return str;
}
// console.log('attempting to parse', str);
// extract method name from between the {{ }} that we found
// for example: {{name.firstName}}
var method = str.substr(start + 2, end - start - 2);
method = method.replace('}}', '');
method = method.replace('{{', '');
// console.log('method', method)
// split the method into module and function
var parts = method.split('.');
if (typeof faker[parts[0]] === "undefined") {
throw new Error('Invalid module: ' + parts[0]);
}
if (typeof faker[parts[0]][parts[1]] === "undefined") {
throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
}
// assign the function from the module.function namespace
var fn = faker[parts[0]][parts[1]];
// replace the found tag with the returned fake value
res = str.replace('{{' + method + '}}', fn());
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;
},{}],43:[function(require,module,exports){
var Finance = function (faker) {
var Helpers = faker.helpers,
self = this;
self.account = function (length) {
length = length || 8;
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
length = null;
return Helpers.replaceSymbolWithNumber(template);
}
self.accountName = function () {
return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' ');
}
self.mask = function (length, parens, elipsis) {
//set defaults
length = (length == 0 || !length || typeof length == 'undefined') ? 4 : length;
parens = (parens === null) ? true : parens;
elipsis = (elipsis === null) ? true : elipsis;
//create a template for length
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
//prefix with elipsis
template = (elipsis) ? ['...', template].join('') : template;
template = (parens) ? ['(', template, ')'].join('') : template;
//generate random numbers
template = Helpers.replaceSymbolWithNumber(template);
return template;
}
//min and max take in minimum and maximum amounts, dec is the decimal place you want rounded to, symbol is $, €, £, etc
//NOTE: this returns a string representation of the value, if you want a number use parseFloat and no symbol
self.amount = function (min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
}
self.transactionType = function () {
return Helpers.randomize(faker.definitions.finance.transaction_type);
}
self.currencyCode = function () {
return faker.random.objectElement(faker.definitions.finance.currency)['code'];
}
self.currencyName = function () {
return faker.random.objectElement(faker.definitions.finance.currency, 'key');
}
self.currencySymbol = function () {
var symbol;
while (!symbol) {
symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol'];
}
return symbol;
}
}
module['exports'] = Finance;
},{}],44:[function(require,module,exports){
var Hacker = function (faker) {
var self = this;
self.abbreviation = function () {
return faker.random.arrayElement(faker.definitions.hacker.abbreviation);
};
self.adjective = function () {
return faker.random.arrayElement(faker.definitions.hacker.adjective);
};
self.noun = function () {
return faker.random.arrayElement(faker.definitions.hacker.noun);
};
self.verb = function () {
return faker.random.arrayElement(faker.definitions.hacker.verb);
};
self.ingverb = function () {
return faker.random.arrayElement(faker.definitions.hacker.ingverb);
};
self.phrase = function () {
var data = {
abbreviation: self.abbreviation(),
adjective: self.adjective(),
ingverb: self.ingverb(),
noun: self.noun(),
verb: self.verb()
};
var phrase = faker.random.arrayElement([ "If we {{verb}} the {{noun}}, we can get to the {{abbreviation}} {{noun}} through the {{adjective}} {{abbreviation}} {{noun}}!",
"We need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Try to {{verb}} the {{abbreviation}} {{noun}}, maybe it will {{verb}} the {{adjective}} {{noun}}!",
"You can't {{verb}} the {{noun}} without {{ingverb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Use the {{adjective}} {{abbreviation}} {{noun}}, then you can {{verb}} the {{adjective}} {{noun}}!",
"The {{abbreviation}} {{noun}} is down, {{verb}} the {{adjective}} {{noun}} so we can {{verb}} the {{abbreviation}} {{noun}}!",
"{{ingverb}} the {{noun}} won't do anything, we need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"I'll {{verb}} the {{adjective}} {{abbreviation}} {{noun}}, that should {{noun}} the {{abbreviation}} {{noun}}!"
]);
return faker.helpers.mustache(phrase, data);
};
return self;
};
module['exports'] = Hacker;
},{}],45:[function(require,module,exports){
var Helpers = function (faker) {
var self = this;
// backword-compatibility
self.randomize = function (array) {
array = array || ["a", "b", "c"];
return faker.random.arrayElement(array);
};
// slugifies string
self.slugify = function (string) {
string = string || "";
return string.replace(/ /g, '-').replace(/[^\w\.\-]+/g, '');
};
// parses string for a symbol and replace it with a random number from 1-10
self.replaceSymbolWithNumber = function (string, symbol) {
string = string || "";
// default symbol is '#'
if (symbol === undefined) {
symbol = '#';
}
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == symbol) {
str += faker.random.number(9);
} else {
str += string.charAt(i);
}
}
return str;
};
// parses string for symbols (numbers or letters) and replaces them appropriately
self.replaceSymbols = function (string) {
string = string || "";
var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "#") {
str += faker.random.number(9);
} else if (string.charAt(i) == "?") {
str += alpha[Math.floor(Math.random() * alpha.length)];
} else {
str += string.charAt(i);
}
}
return str;
};
// takes an array and returns it randomized
self.shuffle = function (o) {
o = o || ["a", "b", "c"];
for (var j, x, i = o.length-1; i; j = faker.random.number(i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
self.mustache = function (str, data) {
if (typeof str === 'undefined') {
return '';
}
for(var p in data) {
var re = new RegExp('{{' + p + '}}', 'g')
str = str.replace(re, data[p]);
}
return str;
};
self.createCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"streetA": faker.address.streetName(),
"streetB": faker.address.streetAddress(),
"streetC": faker.address.streetAddress(true),
"streetD": faker.address.secondaryAddress(),
"city": faker.address.city(),
"state": faker.address.state(),
"country": faker.address.country(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
},
"posts": [
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
}
],
"accountHistory": [faker.helpers.createTransaction(), faker.helpers.createTransaction(), faker.helpers.createTransaction()]
};
};
self.contextualCard = function () {
var name = faker.name.firstName(),
userName = faker.internet.userName(name);
return {
"name": name,
"username": userName,
"avatar": faker.internet.avatar(),
"email": faker.internet.email(userName),
"dob": faker.date.past(50, new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)")),
"phone": faker.phone.phoneNumber(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
self.userCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
self.createTransaction = function(){
return {
"amount" : faker.finance.amount(),
"date" : new Date(2012, 1, 2), //TODO: add a ranged date method
"business": faker.company.companyName(),
"name": [faker.finance.accountName(), faker.finance.mask()].join(' '),
"type" : self.randomize(faker.definitions.finance.transaction_type),
"account" : faker.finance.account()
};
};
return self;
};
/*
String.prototype.capitalize = function () { //v1.0
return this.replace(/\w+/g, function (a) {
return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
});
};
*/
module['exports'] = Helpers;
},{}],46:[function(require,module,exports){
var Image = function (faker) {
var self = this;
self.image = function () {
var categories = ["abstract", "animals", "business", "cats", "city", "food", "nightlife", "fashion", "people", "nature", "sports", "technics", "transport"];
return self[faker.random.arrayElement(categories)]();
};
self.avatar = function () {
return faker.internet.avatar();
};
self.imageUrl = function (width, height, category) {
var width = width || 640;
var height = height || 480;
var url ='http://lorempixel.com/' + width + '/' + height;
if (typeof category !== 'undefined') {
url += '/' + category;
}
return url;
};
self.abstract = function (width, height) {
return faker.image.imageUrl(width, height, 'abstract');
};
self.animals = function (width, height) {
return faker.image.imageUrl(width, height, 'animals');
};
self.business = function (width, height) {
return faker.image.imageUrl(width, height, 'business');
};
self.cats = function (width, height) {
return faker.image.imageUrl(width, height, 'cats');
};
self.city = function (width, height) {
return faker.image.imageUrl(width, height, 'city');
};
self.food = function (width, height) {
return faker.image.imageUrl(width, height, 'food');
};
self.nightlife = function (width, height) {
return faker.image.imageUrl(width, height, 'nightlife');
};
self.fashion = function (width, height) {
return faker.image.imageUrl(width, height, 'fashion');
};
self.people = function (width, height) {
return faker.image.imageUrl(width, height, 'people');
};
self.nature = function (width, height) {
return faker.image.imageUrl(width, height, 'nature');
};
self.sports = function (width, height) {
return faker.image.imageUrl(width, height, 'sports');
};
self.technics = function (width, height) {
return faker.image.imageUrl(width, height, 'technics');
};
self.transport = function (width, height) {
return faker.image.imageUrl(width, height, 'transport');
}
}
module["exports"] = Image;
},{}],47:[function(require,module,exports){
/*
this index.js file is used for including the faker library as a CommonJS module, instead of a bundle
you can include the faker library into your existing node.js application by requiring the entire /faker directory
var faker = require(./faker);
var randomName = faker.name.findName();
you can also simply include the "faker.js" file which is the auto-generated bundled version of the faker library
var faker = require(./customAppPath/faker);
var randomName = faker.name.findName();
if you plan on modifying the faker library you should be performing your changes in the /lib/ directory
*/
function Faker (opts) {
var self = this;
opts = opts || {};
// assign options
var locales = self.locales || opts.locales || {};
var locale = self.locale || opts.locale || "en";
var localeFallback = self.localeFallback || opts.localeFallback || "en";
self.locales = locales;
self.locale = locale;
self.localeFallback = localeFallback;
self.definitions = {};
var Fake = require('./fake');
self.fake = new Fake(self).fake;
var Random = require('./random');
self.random = new Random(self);
// self.random = require('./random');
var Helpers = require('./helpers');
self.helpers = new Helpers(self);
var Name = require('./name');
self.name = new Name(self);
// self.name = require('./name');
var Address = require('./address');
self.address = new Address(self);
var Company = require('./company');
self.company = new Company(self);
var Finance = require('./finance');
self.finance = new Finance(self);
var Image = require('./image');
self.image = new Image(self);
var Lorem = require('./lorem');
self.lorem = new Lorem(self);
var Hacker = require('./hacker');
self.hacker = new Hacker(self);
var Internet = require('./internet');
self.internet = new Internet(self);
var Phone = require('./phone_number');
self.phone = new Phone(self);
var _Date = require('./date');
self.date = new _Date(self);
var Commerce = require('./commerce');
self.commerce = new Commerce(self);
// TODO: fix self.commerce = require('./commerce');
var _definitions = {
"name": ["first_name", "last_name", "prefix", "suffix", "title", "male_first_name", "female_first_name", "male_middle_name", "female_middle_name", "male_last_name", "female_last_name"],
"address": ["city_prefix", "city_suffix", "street_suffix", "county", "country", "country_code", "state", "state_abbr", "street_prefix", "postcode"],
"company": ["adjective", "noun", "descriptor", "bs_adjective", "bs_noun", "bs_verb", "suffix"],
"lorem": ["words"],
"hacker": ["abbreviation", "adjective", "noun", "verb", "ingverb"],
"phone_number": ["formats"],
"finance": ["account_type", "transaction_type", "currency"],
"internet": ["avatar_uri", "domain_suffix", "free_email", "password"],
"commerce": ["color", "department", "product_name", "price", "categories"],
"date": ["month", "weekday"],
"title": "",
"separator": ""
};
// Create a Getter for all definitions.foo.bar propetries
Object.keys(_definitions).forEach(function(d){
if (typeof self.definitions[d] === "undefined") {
self.definitions[d] = {};
}
if (typeof _definitions[d] === "string") {
self.definitions[d] = _definitions[d];
return;
}
_definitions[d].forEach(function(p){
Object.defineProperty(self.definitions[d], p, {
get: function () {
if (typeof self.locales[self.locale][d] === "undefined" || typeof self.locales[self.locale][d][p] === "undefined") {
// certain localization sets contain less data then others.
// in the case of a missing defintion, use the default localeFallback to substitute the missing set data
// throw new Error('unknown property ' + d + p)
return self.locales[localeFallback][d][p];
} else {
// return localized data
return self.locales[self.locale][d][p];
}
}
});
});
});
};
Faker.prototype.seed = function(value) {
var Random = require('./random');
this.seedValue = value;
this.random = new Random(this, this.seedValue);
}
module['exports'] = Faker;
},{"./address":38,"./commerce":39,"./company":40,"./date":41,"./fake":42,"./finance":43,"./hacker":44,"./helpers":45,"./image":46,"./internet":48,"./lorem":161,"./name":162,"./phone_number":163,"./random":164}],48:[function(require,module,exports){
var password_generator = require('../vendor/password-generator.js'),
random_ua = require('../vendor/user-agent');
var Internet = function (faker) {
var self = this;
self.avatar = function () {
return faker.random.arrayElement(faker.definitions.internet.avatar_uri);
};
self.email = function (firstName, lastName, provider) {
provider = provider || faker.random.arrayElement(faker.definitions.internet.free_email);
return faker.helpers.slugify(faker.internet.userName(firstName, lastName)) + "@" + provider;
};
self.userName = function (firstName, lastName) {
var result;
firstName = firstName || faker.name.firstName();
lastName = lastName || faker.name.lastName();
switch (faker.random.number(2)) {
case 0:
result = firstName + faker.random.number(99);
break;
case 1:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName;
break;
case 2:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName + faker.random.number(99);
break;
}
result = result.toString().replace(/'/g, "");
result = result.replace(/ /g, "");
return result;
};
self.protocol = function () {
var protocols = ['http','https'];
return faker.random.arrayElement(protocols);
};
self.url = function () {
return faker.internet.protocol() + '://' + faker.internet.domainName();
};
self.domainName = function () {
return faker.internet.domainWord() + "." + faker.internet.domainSuffix();
};
self.domainSuffix = function () {
return faker.random.arrayElement(faker.definitions.internet.domain_suffix);
};
self.domainWord = function () {
return faker.name.firstName().replace(/([\\~#&*{}/:<>?|\"])/ig, '').toLowerCase();
};
self.ip = function () {
var randNum = function () {
return (faker.random.number(255)).toFixed(0);
};
var result = [];
for (var i = 0; i < 4; i++) {
result[i] = randNum();
}
return result.join(".");
};
self.userAgent = function () {
return random_ua.generate();
};
self.color = function (baseRed255, baseGreen255, baseBlue255) {
baseRed255 = baseRed255 || 0;
baseGreen255 = baseGreen255 || 0;
baseBlue255 = baseBlue255 || 0;
// based on awesome response : http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette
var red = Math.floor((faker.random.number(256) + baseRed255) / 2);
var green = Math.floor((faker.random.number(256) + baseGreen255) / 2);
var blue = Math.floor((faker.random.number(256) + baseBlue255) / 2);
var redStr = red.toString(16);
var greenStr = green.toString(16);
var blueStr = blue.toString(16);
return '#' +
(redStr.length === 1 ? '0' : '') + redStr +
(greenStr.length === 1 ? '0' : '') + greenStr +
(blueStr.length === 1 ? '0': '') + blueStr;
};
self.mac = function(){
var i, mac = "";
for (i=0; i < 12; i++) {
mac+= parseInt(Math.random()*16).toString(16);
if (i%2==1 && i != 11) {
mac+=":";
}
}
return mac;
};
self.password = function (len, memorable, pattern, prefix) {
len = len || 15;
if (typeof memorable === "undefined") {
memorable = false;
}
return password_generator(len, memorable, pattern, prefix);
}
};
module["exports"] = Internet;
},{"../vendor/password-generator.js":167,"../vendor/user-agent":168}],49:[function(require,module,exports){
module["exports"] = [
"#####",
"####",
"###"
];
},{}],50:[function(require,module,exports){
module["exports"] = [
"#{city_prefix} #{Name.first_name}#{city_suffix}",
"#{city_prefix} #{Name.first_name}",
"#{Name.first_name}#{city_suffix}",
"#{Name.last_name}#{city_suffix}"
];
},{}],51:[function(require,module,exports){
module["exports"] = [
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port"
];
},{}],52:[function(require,module,exports){
module["exports"] = [
"town",
"ton",
"land",
"ville",
"berg",
"burgh",
"borough",
"bury",
"view",
"port",
"mouth",
"stad",
"furt",
"chester",
"mouth",
"fort",
"haven",
"side",
"shire"
];
},{}],53:[function(require,module,exports){
module["exports"] = [
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica (the territory South of 60 deg S)",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island (Bouvetoya)",
"Brazil",
"British Indian Ocean Territory (Chagos Archipelago)",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Cayman Islands",
"Central African Republic",
"Chad",
"Chile",
"China",
"Christmas Island",
"Cocos (Keeling) Islands",
"Colombia",
"Comoros",
"Congo",
"Congo",
"Cook Islands",
"Costa Rica",
"Cote d'Ivoire",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Faroe Islands",
"Falkland Islands (Malvinas)",
"Fiji",
"Finland",
"France",
"French Guiana",
"French Polynesia",
"French Southern Territories",
"Gabon",
"Gambia",
"Georgia",
"Germany",
"Ghana",
"Gibraltar",
"Greece",
"Greenland",
"Grenada",
"Guadeloupe",
"Guam",
"Guatemala",
"Guernsey",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Heard Island and McDonald Islands",
"Holy See (Vatican City State)",
"Honduras",
"Hong Kong",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Isle of Man",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jersey",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Democratic People's Republic of Korea",
"Republic of Korea",
"Kuwait",
"Kyrgyz Republic",
"Lao People's Democratic Republic",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libyan Arab Jamahiriya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macao",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Martinique",
"Mauritania",
"Mauritius",
"Mayotte",
"Mexico",
"Micronesia",
"Moldova",
"Monaco",
"Mongolia",
"Montenegro",
"Montserrat",
"Morocco",
"Mozambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Netherlands Antilles",
"Netherlands",
"New Caledonia",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Niue",
"Norfolk Island",
"Northern Mariana Islands",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Palestinian Territory",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
"Philippines",
"Pitcairn Islands",
"Poland",
"Portugal",
"Puerto Rico",
"Qatar",
"Reunion",
"Romania",
"Russian Federation",
"Rwanda",
"Saint Barthelemy",
"Saint Helena",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Martin",
"Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia (Slovak Republic)",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"South Georgia and the South Sandwich Islands",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Svalbard & Jan Mayen Islands",
"Swaziland",
"Sweden",
"Switzerland",
"Syrian Arab Republic",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Timor-Leste",
"Togo",
"Tokelau",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Turks and Caicos Islands",
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States of America",
"United States Minor Outlying Islands",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Venezuela",
"Vietnam",
"Virgin Islands, British",
"Virgin Islands, U.S.",
"Wallis and Futuna",
"Western Sahara",
"Yemen",
"Zambia",
"Zimbabwe"
];
},{}],54:[function(require,module,exports){
module["exports"] = [
"AD",
"AE",
"AF",
"AG",
"AI",
"AL",
"AM",
"AO",
"AQ",
"AR",
"AS",
"AT",
"AU",
"AW",
"AX",
"AZ",
"BA",
"BB",
"BD",
"BE",
"BF",
"BG",
"BH",
"BI",
"BJ",
"BL",
"BM",
"BN",
"BO",
"BQ",
"BQ",
"BR",
"BS",
"BT",
"BV",
"BW",
"BY",
"BZ",
"CA",
"CC",
"CD",
"CF",
"CG",
"CH",
"CI",
"CK",
"CL",
"CM",
"CN",
"CO",
"CR",
"CU",
"CV",
"CW",
"CX",
"CY",
"CZ",
"DE",
"DJ",
"DK",
"DM",
"DO",
"DZ",
"EC",
"EE",
"EG",
"EH",
"ER",
"ES",
"ET",
"FI",
"FJ",
"FK",
"FM",
"FO",
"FR",
"GA",
"GB",
"GD",
"GE",
"GF",
"GG",
"GH",
"GI",
"GL",
"GM",
"GN",
"GP",
"GQ",
"GR",
"GS",
"GT",
"GU",
"GW",
"GY",
"HK",
"HM",
"HN",
"HR",
"HT",
"HU",
"ID",
"IE",
"IL",
"IM",
"IN",
"IO",
"IQ",
"IR",
"IS",
"IT",
"JE",
"JM",
"JO",
"JP",
"KE",
"KG",
"KH",
"KI",
"KM",
"KN",
"KP",
"KR",
"KW",
"KY",
"KZ",
"LA",
"LB",
"LC",
"LI",
"LK",
"LR",
"LS",
"LT",
"LU",
"LV",
"LY",
"MA",
"MC",
"MD",
"ME",
"MF",
"MG",
"MH",
"MK",
"ML",
"MM",
"MN",
"MO",
"MP",
"MQ",
"MR",
"MS",
"MT",
"MU",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NC",
"NE",
"NF",
"NG",
"NI",
"NL",
"NO",
"NP",
"NR",
"NU",
"NZ",
"OM",
"PA",
"PE",
"PF",
"PG",
"PH",
"PK",
"PL",
"PM",
"PN",
"PR",
"PS",
"PT",
"PW",
"PY",
"QA",
"RE",
"RO",
"RS",
"RU",
"RW",
"SA",
"SB",
"SC",
"SD",
"SE",
"SG",
"SH",
"SI",
"SJ",
"SK",
"SL",
"SM",
"SN",
"SO",
"SR",
"SS",
"ST",
"SV",
"SX",
"SY",
"SZ",
"TC",
"TD",
"TF",
"TG",
"TH",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TR",
"TT",
"TV",
"TW",
"TZ",
"UA",
"UG",
"UM",
"US",
"UY",
"UZ",
"VA",
"VC",
"VE",
"VG",
"VI",
"VN",
"VU",
"WF",
"WS",
"YE",
"YT",
"ZA",
"ZM",
"ZW"
];
},{}],55:[function(require,module,exports){
module["exports"] = [
"Avon",
"Bedfordshire",
"Berkshire",
"Borders",
"Buckinghamshire",
"Cambridgeshire"
];
},{}],56:[function(require,module,exports){
module["exports"] = [
"United States of America"
];
},{}],57:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.city_prefix = require("./city_prefix");
address.city_suffix = require("./city_suffix");
address.county = require("./county");
address.country = require("./country");
address.country_code = require("./country_code");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.postcode_by_state = require("./postcode_by_state");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.time_zone = require("./time_zone");
address.city = require("./city");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");
},{"./building_number":49,"./city":50,"./city_prefix":51,"./city_suffix":52,"./country":53,"./country_code":54,"./county":55,"./default_country":56,"./postcode":58,"./postcode_by_state":59,"./secondary_address":60,"./state":61,"./state_abbr":62,"./street_address":63,"./street_name":64,"./street_suffix":65,"./time_zone":66}],58:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-####"
];
},{}],59:[function(require,module,exports){
arguments[4][58][0].apply(exports,arguments)
},{"dup":58}],60:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"Suite ###"
];
},{}],61:[function(require,module,exports){
module["exports"] = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming"
];
},{}],62:[function(require,module,exports){
module["exports"] = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY"
];
},{}],63:[function(require,module,exports){
module["exports"] = [
"#{building_number} #{street_name}"
];
},{}],64:[function(require,module,exports){
module["exports"] = [
"#{Name.first_name} #{street_suffix}",
"#{Name.last_name} #{street_suffix}"
];
},{}],65:[function(require,module,exports){
module["exports"] = [
"Alley",
"Avenue",
"Branch",
"Bridge",
"Brook",
"Brooks",
"Burg",
"Burgs",
"Bypass",
"Camp",
"Canyon",
"Cape",
"Causeway",
"Center",
"Centers",
"Circle",
"Circles",
"Cliff",
"Cliffs",
"Club",
"Common",
"Corner",
"Corners",
"Course",
"Court",
"Courts",
"Cove",
"Coves",
"Creek",
"Crescent",
"Crest",
"Crossing",
"Crossroad",
"Curve",
"Dale",
"Dam",
"Divide",
"Drive",
"Drive",
"Drives",
"Estate",
"Estates",
"Expressway",
"Extension",
"Extensions",
"Fall",
"Falls",
"Ferry",
"Field",
"Fields",
"Flat",
"Flats",
"Ford",
"Fords",
"Forest",
"Forge",
"Forges",
"Fork",
"Forks",
"Fort",
"Freeway",
"Garden",
"Gardens",
"Gateway",
"Glen",
"Glens",
"Green",
"Greens",
"Grove",
"Groves",
"Harbor",
"Harbors",
"Haven",
"Heights",
"Highway",
"Hill",
"Hills",
"Hollow",
"Inlet",
"Inlet",
"Island",
"Island",
"Islands",
"Islands",
"Isle",
"Isle",
"Junction",
"Junctions",
"Key",
"Keys",
"Knoll",
"Knolls",
"Lake",
"Lakes",
"Land",
"Landing",
"Lane",
"Light",
"Lights",
"Loaf",
"Lock",
"Locks",
"Locks",
"Lodge",
"Lodge",
"Loop",
"Mall",
"Manor",
"Manors",
"Meadow",
"Meadows",
"Mews",
"Mill",
"Mills",
"Mission",
"Mission",
"Motorway",
"Mount",
"Mountain",
"Mountain",
"Mountains",
"Mountains",
"Neck",
"Orchard",
"Oval",
"Overpass",
"Park",
"Parks",
"Parkway",
"Parkways",
"Pass",
"Passage",
"Path",
"Pike",
"Pine",
"Pines",
"Place",
"Plain",
"Plains",
"Plains",
"Plaza",
"Plaza",
"Point",
"Points",
"Port",
"Port",
"Ports",
"Ports",
"Prairie",
"Prairie",
"Radial",
"Ramp",
"Ranch",
"Rapid",
"Rapids",
"Rest",
"Ridge",
"Ridges",
"River",
"Road",
"Road",
"Roads",
"Roads",
"Route",
"Row",
"Rue",
"Run",
"Shoal",
"Shoals",
"Shore",
"Shores",
"Skyway",
"Spring",
"Springs",
"Springs",
"Spur",
"Spurs",
"Square",
"Square",
"Squares",
"Squares",
"Station",
"Station",
"Stravenue",
"Stravenue",
"Stream",
"Stream",
"Street",
"Street",
"Streets",
"Summit",
"Summit",
"Terrace",
"Throughway",
"Trace",
"Track",
"Trafficway",
"Trail",
"Trail",
"Tunnel",
"Tunnel",
"Turnpike",
"Turnpike",
"Underpass",
"Union",
"Unions",
"Valley",
"Valleys",
"Via",
"Viaduct",
"View",
"Views",
"Village",
"Village",
"Villages",
"Ville",
"Vista",
"Vista",
"Walk",
"Walks",
"Wall",
"Way",
"Ways",
"Well",
"Wells"
];
},{}],66:[function(require,module,exports){
module["exports"] = [
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Honolulu",
"America/Juneau",
"America/Los_Angeles",
"America/Tijuana",
"America/Denver",
"America/Phoenix",
"America/Chihuahua",
"America/Mazatlan",
"America/Chicago",
"America/Regina",
"America/Mexico_City",
"America/Mexico_City",
"America/Monterrey",
"America/Guatemala",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Bogota",
"America/Lima",
"America/Lima",
"America/Halifax",
"America/Caracas",
"America/La_Paz",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"America/Guyana",
"America/Godthab",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"Europe/Dublin",
"Europe/London",
"Europe/Lisbon",
"Europe/London",
"Africa/Casablanca",
"Africa/Monrovia",
"Etc/UTC",
"Europe/Belgrade",
"Europe/Bratislava",
"Europe/Budapest",
"Europe/Ljubljana",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Skopje",
"Europe/Warsaw",
"Europe/Zagreb",
"Europe/Brussels",
"Europe/Copenhagen",
"Europe/Madrid",
"Europe/Paris",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Berlin",
"Europe/Rome",
"Europe/Stockholm",
"Europe/Vienna",
"Africa/Algiers",
"Europe/Bucharest",
"Africa/Cairo",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Riga",
"Europe/Sofia",
"Europe/Tallinn",
"Europe/Vilnius",
"Europe/Athens",
"Europe/Istanbul",
"Europe/Minsk",
"Asia/Jerusalem",
"Africa/Harare",
"Africa/Johannesburg",
"Europe/Moscow",
"Europe/Moscow",
"Europe/Moscow",
"Asia/Kuwait",
"Asia/Riyadh",
"Africa/Nairobi",
"Asia/Baghdad",
"Asia/Tehran",
"Asia/Muscat",
"Asia/Muscat",
"Asia/Baku",
"Asia/Tbilisi",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Karachi",
"Asia/Tashkent",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kathmandu",
"Asia/Dhaka",
"Asia/Dhaka",
"Asia/Colombo",
"Asia/Almaty",
"Asia/Novosibirsk",
"Asia/Rangoon",
"Asia/Bangkok",
"Asia/Bangkok",
"Asia/Jakarta",
"Asia/Krasnoyarsk",
"Asia/Shanghai",
"Asia/Chongqing",
"Asia/Hong_Kong",
"Asia/Urumqi",
"Asia/Kuala_Lumpur",
"Asia/Singapore",
"Asia/Taipei",
"Australia/Perth",
"Asia/Irkutsk",
"Asia/Ulaanbaatar",
"Asia/Seoul",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Yakutsk",
"Australia/Darwin",
"Australia/Adelaide",
"Australia/Melbourne",
"Australia/Melbourne",
"Australia/Sydney",
"Australia/Brisbane",
"Australia/Hobart",
"Asia/Vladivostok",
"Pacific/Guam",
"Pacific/Port_Moresby",
"Asia/Magadan",
"Asia/Magadan",
"Pacific/Noumea",
"Pacific/Fiji",
"Asia/Kamchatka",
"Pacific/Majuro",
"Pacific/Auckland",
"Pacific/Auckland",
"Pacific/Tongatapu",
"Pacific/Fakaofo",
"Pacific/Apia"
];
},{}],67:[function(require,module,exports){
module["exports"] = [
"#{Name.name}",
"#{Company.name}"
];
},{}],68:[function(require,module,exports){
var app = {};
module['exports'] = app;
app.name = require("./name");
app.version = require("./version");
app.author = require("./author");
},{"./author":67,"./name":69,"./version":70}],69:[function(require,module,exports){
module["exports"] = [
"Redhold",
"Treeflex",
"Trippledex",
"Kanlam",
"Bigtax",
"Daltfresh",
"Toughjoyfax",
"Mat Lam Tam",
"Otcom",
"Tres-Zap",
"Y-Solowarm",
"Tresom",
"Voltsillam",
"Biodex",
"Greenlam",
"Viva",
"Matsoft",
"Temp",
"Zoolab",
"Subin",
"Rank",
"Job",
"Stringtough",
"Tin",
"It",
"Home Ing",
"Zamit",
"Sonsing",
"Konklab",
"Alpha",
"Latlux",
"Voyatouch",
"Alphazap",
"Holdlamis",
"Zaam-Dox",
"Sub-Ex",
"Quo Lux",
"Bamity",
"Ventosanzap",
"Lotstring",
"Hatity",
"Tempsoft",
"Overhold",
"Fixflex",
"Konklux",
"Zontrax",
"Tampflex",
"Span",
"Namfix",
"Transcof",
"Stim",
"Fix San",
"Sonair",
"Stronghold",
"Fintone",
"Y-find",
"Opela",
"Lotlux",
"Ronstring",
"Zathin",
"Duobam",
"Keylex"
];
},{}],70:[function(require,module,exports){
module["exports"] = [
"0.#.#",
"0.##",
"#.##",
"#.#",
"#.#.#"
];
},{}],71:[function(require,module,exports){
module["exports"] = [
"2011-10-12",
"2012-11-12",
"2015-11-11",
"2013-9-12"
];
},{}],72:[function(require,module,exports){
module["exports"] = [
"1234-2121-1221-1211",
"1212-1221-1121-1234",
"1211-1221-1234-2201",
"1228-1221-1221-1431"
];
},{}],73:[function(require,module,exports){
module["exports"] = [
"visa",
"mastercard",
"americanexpress",
"discover"
];
},{}],74:[function(require,module,exports){
var business = {};
module['exports'] = business;
business.credit_card_numbers = require("./credit_card_numbers");
business.credit_card_expiry_dates = require("./credit_card_expiry_dates");
business.credit_card_types = require("./credit_card_types");
},{"./credit_card_expiry_dates":71,"./credit_card_numbers":72,"./credit_card_types":73}],75:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####"
];
},{}],76:[function(require,module,exports){
var cell_phone = {};
module['exports'] = cell_phone;
cell_phone.formats = require("./formats");
},{"./formats":75}],77:[function(require,module,exports){
module["exports"] = [
"red",
"green",
"blue",
"yellow",
"purple",
"mint green",
"teal",
"white",
"black",
"orange",
"pink",
"grey",
"maroon",
"violet",
"turquoise",
"tan",
"sky blue",
"salmon",
"plum",
"orchid",
"olive",
"magenta",
"lime",
"ivory",
"indigo",
"gold",
"fuchsia",
"cyan",
"azure",
"lavender",
"silver"
];
},{}],78:[function(require,module,exports){
module["exports"] = [
"Books",
"Movies",
"Music",
"Games",
"Electronics",
"Computers",
"Home",
"Garden",
"Tools",
"Grocery",
"Health",
"Beauty",
"Toys",
"Kids",
"Baby",
"Clothing",
"Shoes",
"Jewelery",
"Sports",
"Outdoors",
"Automotive",
"Industrial"
];
},{}],79:[function(require,module,exports){
var commerce = {};
module['exports'] = commerce;
commerce.color = require("./color");
commerce.department = require("./department");
commerce.product_name = require("./product_name");
},{"./color":77,"./department":78,"./product_name":80}],80:[function(require,module,exports){
module["exports"] = {
"adjective": [
"Small",
"Ergonomic",
"Rustic",
"Intelligent",
"Gorgeous",
"Incredible",
"Fantastic",
"Practical",
"Sleek",
"Awesome",
"Generic",
"Handcrafted",
"Handmade",
"Licensed",
"Refined",
"Unbranded",
"Tasty"
],
"material": [
"Steel",
"Wooden",
"Concrete",
"Plastic",
"Cotton",
"Granite",
"Rubber",
"Metal",
"Soft",
"Fresh",
"Frozen"
],
"product": [
"Chair",
"Car",
"Computer",
"Keyboard",
"Mouse",
"Bike",
"Ball",
"Gloves",
"Pants",
"Shirt",
"Table",
"Shoes",
"Hat",
"Towels",
"Soap",
"Tuna",
"Chicken",
"Fish",
"Cheese",
"Bacon",
"Pizza",
"Salad",
"Sausages",
"Chips"
]
};
},{}],81:[function(require,module,exports){
module["exports"] = [
"Adaptive",
"Advanced",
"Ameliorated",
"Assimilated",
"Automated",
"Balanced",
"Business-focused",
"Centralized",
"Cloned",
"Compatible",
"Configurable",
"Cross-group",
"Cross-platform",
"Customer-focused",
"Customizable",
"Decentralized",
"De-engineered",
"Devolved",
"Digitized",
"Distributed",
"Diverse",
"Down-sized",
"Enhanced",
"Enterprise-wide",
"Ergonomic",
"Exclusive",
"Expanded",
"Extended",
"Face to face",
"Focused",
"Front-line",
"Fully-configurable",
"Function-based",
"Fundamental",
"Future-proofed",
"Grass-roots",
"Horizontal",
"Implemented",
"Innovative",
"Integrated",
"Intuitive",
"Inverse",
"Managed",
"Mandatory",
"Monitored",
"Multi-channelled",
"Multi-lateral",
"Multi-layered",
"Multi-tiered",
"Networked",
"Object-based",
"Open-architected",
"Open-source",
"Operative",
"Optimized",
"Optional",
"Organic",
"Organized",
"Persevering",
"Persistent",
"Phased",
"Polarised",
"Pre-emptive",
"Proactive",
"Profit-focused",
"Profound",
"Programmable",
"Progressive",
"Public-key",
"Quality-focused",
"Reactive",
"Realigned",
"Re-contextualized",
"Re-engineered",
"Reduced",
"Reverse-engineered",
"Right-sized",
"Robust",
"Seamless",
"Secured",
"Self-enabling",
"Sharable",
"Stand-alone",
"Streamlined",
"Switchable",
"Synchronised",
"Synergistic",
"Synergized",
"Team-oriented",
"Total",
"Triple-buffered",
"Universal",
"Up-sized",
"Upgradable",
"User-centric",
"User-friendly",
"Versatile",
"Virtual",
"Visionary",
"Vision-oriented"
];
},{}],82:[function(require,module,exports){
module["exports"] = [
"clicks-and-mortar",
"value-added",
"vertical",
"proactive",
"robust",
"revolutionary",
"scalable",
"leading-edge",
"innovative",
"intuitive",
"strategic",
"e-business",
"mission-critical",
"sticky",
"one-to-one",
"24/7",
"end-to-end",
"global",
"B2B",
"B2C",
"granular",
"frictionless",
"virtual",
"viral",
"dynamic",
"24/365",
"best-of-breed",
"killer",
"magnetic",
"bleeding-edge",
"web-enabled",
"interactive",
"dot-com",
"sexy",
"back-end",
"real-time",
"efficient",
"front-end",
"distributed",
"seamless",
"extensible",
"turn-key",
"world-class",
"open-source",
"cross-platform",
"cross-media",
"synergistic",
"bricks-and-clicks",
"out-of-the-box",
"enterprise",
"integrated",
"impactful",
"wireless",
"transparent",
"next-generation",
"cutting-edge",
"user-centric",
"visionary",
"customized",
"ubiquitous",
"plug-and-play",
"collaborative",
"compelling",
"holistic",
"rich"
];
},{}],83:[function(require,module,exports){
module["exports"] = [
"synergies",
"web-readiness",
"paradigms",
"markets",
"partnerships",
"infrastructures",
"platforms",
"initiatives",
"channels",
"eyeballs",
"communities",
"ROI",
"solutions",
"e-tailers",
"e-services",
"action-items",
"portals",
"niches",
"technologies",
"content",
"vortals",
"supply-chains",
"convergence",
"relationships",
"architectures",
"interfaces",
"e-markets",
"e-commerce",
"systems",
"bandwidth",
"infomediaries",
"models",
"mindshare",
"deliverables",
"users",
"schemas",
"networks",
"applications",
"metrics",
"e-business",
"functionalities",
"experiences",
"web services",
"methodologies"
];
},{}],84:[function(require,module,exports){
module["exports"] = [
"implement",
"utilize",
"integrate",
"streamline",
"optimize",
"evolve",
"transform",
"embrace",
"enable",
"orchestrate",
"leverage",
"reinvent",
"aggregate",
"architect",
"enhance",
"incentivize",
"morph",
"empower",
"envisioneer",
"monetize",
"harness",
"facilitate",
"seize",
"disintermediate",
"synergize",
"strategize",
"deploy",
"brand",
"grow",
"target",
"syndicate",
"synthesize",
"deliver",
"mesh",
"incubate",
"engage",
"maximize",
"benchmark",
"expedite",
"reintermediate",
"whiteboard",
"visualize",
"repurpose",
"innovate",
"scale",
"unleash",
"drive",
"extend",
"engineer",
"revolutionize",
"generate",
"exploit",
"transition",
"e-enable",
"iterate",
"cultivate",
"matrix",
"productize",
"redefine",
"recontextualize"
];
},{}],85:[function(require,module,exports){
module["exports"] = [
"24 hour",
"24/7",
"3rd generation",
"4th generation",
"5th generation",
"6th generation",
"actuating",
"analyzing",
"asymmetric",
"asynchronous",
"attitude-oriented",
"background",
"bandwidth-monitored",
"bi-directional",
"bifurcated",
"bottom-line",
"clear-thinking",
"client-driven",
"client-server",
"coherent",
"cohesive",
"composite",
"context-sensitive",
"contextually-based",
"content-based",
"dedicated",
"demand-driven",
"didactic",
"directional",
"discrete",
"disintermediate",
"dynamic",
"eco-centric",
"empowering",
"encompassing",
"even-keeled",
"executive",
"explicit",
"exuding",
"fault-tolerant",
"foreground",
"fresh-thinking",
"full-range",
"global",
"grid-enabled",
"heuristic",
"high-level",
"holistic",
"homogeneous",
"human-resource",
"hybrid",
"impactful",
"incremental",
"intangible",
"interactive",
"intermediate",
"leading edge",
"local",
"logistical",
"maximized",
"methodical",
"mission-critical",
"mobile",
"modular",
"motivating",
"multimedia",
"multi-state",
"multi-tasking",
"national",
"needs-based",
"neutral",
"next generation",
"non-volatile",
"object-oriented",
"optimal",
"optimizing",
"radical",
"real-time",
"reciprocal",
"regional",
"responsive",
"scalable",
"secondary",
"solution-oriented",
"stable",
"static",
"systematic",
"systemic",
"system-worthy",
"tangible",
"tertiary",
"transitional",
"uniform",
"upward-trending",
"user-facing",
"value-added",
"web-enabled",
"well-modulated",
"zero administration",
"zero defect",
"zero tolerance"
];
},{}],86:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
company.adjective = require("./adjective");
company.descriptor = require("./descriptor");
company.noun = require("./noun");
company.bs_verb = require("./bs_verb");
company.bs_adjective = require("./bs_adjective");
company.bs_noun = require("./bs_noun");
company.name = require("./name");
},{"./adjective":81,"./bs_adjective":82,"./bs_noun":83,"./bs_verb":84,"./descriptor":85,"./name":87,"./noun":88,"./suffix":89}],87:[function(require,module,exports){
module["exports"] = [
"#{Name.last_name} #{suffix}",
"#{Name.last_name}-#{Name.last_name}",
"#{Name.last_name}, #{Name.last_name} and #{Name.last_name}"
];
},{}],88:[function(require,module,exports){
module["exports"] = [
"ability",
"access",
"adapter",
"algorithm",
"alliance",
"analyzer",
"application",
"approach",
"architecture",
"archive",
"artificial intelligence",
"array",
"attitude",
"benchmark",
"budgetary management",
"capability",
"capacity",
"challenge",
"circuit",
"collaboration",
"complexity",
"concept",
"conglomeration",
"contingency",
"core",
"customer loyalty",
"database",
"data-warehouse",
"definition",
"emulation",
"encoding",
"encryption",
"extranet",
"firmware",
"flexibility",
"focus group",
"forecast",
"frame",
"framework",
"function",
"functionalities",
"Graphic Interface",
"groupware",
"Graphical User Interface",
"hardware",
"help-desk",
"hierarchy",
"hub",
"implementation",
"info-mediaries",
"infrastructure",
"initiative",
"installation",
"instruction set",
"interface",
"internet solution",
"intranet",
"knowledge user",
"knowledge base",
"local area network",
"leverage",
"matrices",
"matrix",
"methodology",
"middleware",
"migration",
"model",
"moderator",
"monitoring",
"moratorium",
"neural-net",
"open architecture",
"open system",
"orchestration",
"paradigm",
"parallelism",
"policy",
"portal",
"pricing structure",
"process improvement",
"product",
"productivity",
"project",
"projection",
"protocol",
"secured line",
"service-desk",
"software",
"solution",
"standardization",
"strategy",
"structure",
"success",
"superstructure",
"support",
"synergy",
"system engine",
"task-force",
"throughput",
"time-frame",
"toolset",
"utilisation",
"website",
"workforce"
];
},{}],89:[function(require,module,exports){
module["exports"] = [
"Inc",
"and Sons",
"LLC",
"Group"
];
},{}],90:[function(require,module,exports){
module["exports"] = [
"/34##-######-####L/",
"/37##-######-####L/"
];
},{}],91:[function(require,module,exports){
module["exports"] = [
"/30[0-5]#-######-###L/",
"/368#-######-###L/"
];
},{}],92:[function(require,module,exports){
module["exports"] = [
"/6011-####-####-###L/",
"/65##-####-####-###L/",
"/64[4-9]#-####-####-###L/",
"/6011-62##-####-####-###L/",
"/65##-62##-####-####-###L/",
"/64[4-9]#-62##-####-####-###L/"
];
},{}],93:[function(require,module,exports){
var credit_card = {};
module['exports'] = credit_card;
credit_card.visa = require("./visa");
credit_card.mastercard = require("./mastercard");
credit_card.discover = require("./discover");
credit_card.american_express = require("./american_express");
credit_card.diners_club = require("./diners_club");
credit_card.jcb = require("./jcb");
credit_card.switch = require("./switch");
credit_card.solo = require("./solo");
credit_card.maestro = require("./maestro");
credit_card.laser = require("./laser");
},{"./american_express":90,"./diners_club":91,"./discover":92,"./jcb":94,"./laser":95,"./maestro":96,"./mastercard":97,"./solo":98,"./switch":99,"./visa":100}],94:[function(require,module,exports){
module["exports"] = [
"/3528-####-####-###L/",
"/3529-####-####-###L/",
"/35[3-8]#-####-####-###L/"
];
},{}],95:[function(require,module,exports){
module["exports"] = [
"/6304###########L/",
"/6706###########L/",
"/6771###########L/",
"/6709###########L/",
"/6304#########{5,6}L/",
"/6706#########{5,6}L/",
"/6771#########{5,6}L/",
"/6709#########{5,6}L/"
];
},{}],96:[function(require,module,exports){
module["exports"] = [
"/50#{9,16}L/",
"/5[6-8]#{9,16}L/",
"/56##{9,16}L/"
];
},{}],97:[function(require,module,exports){
module["exports"] = [
"/5[1-5]##-####-####-###L/",
"/6771-89##-####-###L/"
];
},{}],98:[function(require,module,exports){
module["exports"] = [
"/6767-####-####-###L/",
"/6767-####-####-####-#L/",
"/6767-####-####-####-##L/"
];
},{}],99:[function(require,module,exports){
module["exports"] = [
"/6759-####-####-###L/",
"/6759-####-####-####-#L/",
"/6759-####-####-####-##L/"
];
},{}],100:[function(require,module,exports){
module["exports"] = [
"/4###########L/",
"/4###-####-####-###L/"
];
},{}],101:[function(require,module,exports){
var date = {};
module["exports"] = date;
date.month = require("./month");
date.weekday = require("./weekday");
},{"./month":102,"./weekday":103}],102:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1799
module["exports"] = {
wide: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
abbr: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
};
},{}],103:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1847
module["exports"] = {
wide: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
abbr: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
]
};
},{}],104:[function(require,module,exports){
module["exports"] = [
"Checking",
"Savings",
"Money Market",
"Investment",
"Home Loan",
"Credit Card",
"Auto Loan",
"Personal Loan"
];
},{}],105:[function(require,module,exports){
module["exports"] = {
"UAE Dirham": {
"code": "AED",
"symbol": ""
},
"Afghani": {
"code": "AFN",
"symbol": "؋"
},
"Lek": {
"code": "ALL",
"symbol": "Lek"
},
"Armenian Dram": {
"code": "AMD",
"symbol": ""
},
"Netherlands Antillian Guilder": {
"code": "ANG",
"symbol": "ƒ"
},
"Kwanza": {
"code": "AOA",
"symbol": ""
},
"Argentine Peso": {
"code": "ARS",
"symbol": "$"
},
"Australian Dollar": {
"code": "AUD",
"symbol": "$"
},
"Aruban Guilder": {
"code": "AWG",
"symbol": "ƒ"
},
"Azerbaijanian Manat": {
"code": "AZN",
"symbol": "ман"
},
"Convertible Marks": {
"code": "BAM",
"symbol": "KM"
},
"Barbados Dollar": {
"code": "BBD",
"symbol": "$"
},
"Taka": {
"code": "BDT",
"symbol": ""
},
"Bulgarian Lev": {
"code": "BGN",
"symbol": "лв"
},
"Bahraini Dinar": {
"code": "BHD",
"symbol": ""
},
"Burundi Franc": {
"code": "BIF",
"symbol": ""
},
"Bermudian Dollar (customarily known as Bermuda Dollar)": {
"code": "BMD",
"symbol": "$"
},
"Brunei Dollar": {
"code": "BND",
"symbol": "$"
},
"Boliviano Mvdol": {
"code": "BOB BOV",
"symbol": "$b"
},
"Brazilian Real": {
"code": "BRL",
"symbol": "R$"
},
"Bahamian Dollar": {
"code": "BSD",
"symbol": "$"
},
"Pula": {
"code": "BWP",
"symbol": "P"
},
"Belarussian Ruble": {
"code": "BYR",
"symbol": "p."
},
"Belize Dollar": {
"code": "BZD",
"symbol": "BZ$"
},
"Canadian Dollar": {
"code": "CAD",
"symbol": "$"
},
"Congolese Franc": {
"code": "CDF",
"symbol": ""
},
"Swiss Franc": {
"code": "CHF",
"symbol": "CHF"
},
"Chilean Peso Unidades de fomento": {
"code": "CLP CLF",
"symbol": "$"
},
"Yuan Renminbi": {
"code": "CNY",
"symbol": "¥"
},
"Colombian Peso Unidad de Valor Real": {
"code": "COP COU",
"symbol": "$"
},
"Costa Rican Colon": {
"code": "CRC",
"symbol": "₡"
},
"Cuban Peso Peso Convertible": {
"code": "CUP CUC",
"symbol": "₱"
},
"Cape Verde Escudo": {
"code": "CVE",
"symbol": ""
},
"Czech Koruna": {
"code": "CZK",
"symbol": "Kč"
},
"Djibouti Franc": {
"code": "DJF",
"symbol": ""
},
"Danish Krone": {
"code": "DKK",
"symbol": "kr"
},
"Dominican Peso": {
"code": "DOP",
"symbol": "RD$"
},
"Algerian Dinar": {
"code": "DZD",
"symbol": ""
},
"Kroon": {
"code": "EEK",
"symbol": ""
},
"Egyptian Pound": {
"code": "EGP",
"symbol": "£"
},
"Nakfa": {
"code": "ERN",
"symbol": ""
},
"Ethiopian Birr": {
"code": "ETB",
"symbol": ""
},
"Euro": {
"code": "EUR",
"symbol": "€"
},
"Fiji Dollar": {
"code": "FJD",
"symbol": "$"
},
"Falkland Islands Pound": {
"code": "FKP",
"symbol": "£"
},
"Pound Sterling": {
"code": "GBP",
"symbol": "£"
},
"Lari": {
"code": "GEL",
"symbol": ""
},
"Cedi": {
"code": "GHS",
"symbol": ""
},
"Gibraltar Pound": {
"code": "GIP",
"symbol": "£"
},
"Dalasi": {
"code": "GMD",
"symbol": ""
},
"Guinea Franc": {
"code": "GNF",
"symbol": ""
},
"Quetzal": {
"code": "GTQ",
"symbol": "Q"
},
"Guyana Dollar": {
"code": "GYD",
"symbol": "$"
},
"Hong Kong Dollar": {
"code": "HKD",
"symbol": "$"
},
"Lempira": {
"code": "HNL",
"symbol": "L"
},
"Croatian Kuna": {
"code": "HRK",
"symbol": "kn"
},
"Gourde US Dollar": {
"code": "HTG USD",
"symbol": ""
},
"Forint": {
"code": "HUF",
"symbol": "Ft"
},
"Rupiah": {
"code": "IDR",
"symbol": "Rp"
},
"New Israeli Sheqel": {
"code": "ILS",
"symbol": "₪"
},
"Indian Rupee": {
"code": "INR",
"symbol": ""
},
"Indian Rupee Ngultrum": {
"code": "INR BTN",
"symbol": ""
},
"Iraqi Dinar": {
"code": "IQD",
"symbol": ""
},
"Iranian Rial": {
"code": "IRR",
"symbol": "﷼"
},
"Iceland Krona": {
"code": "ISK",
"symbol": "kr"
},
"Jamaican Dollar": {
"code": "JMD",
"symbol": "J$"
},
"Jordanian Dinar": {
"code": "JOD",
"symbol": ""
},
"Yen": {
"code": "JPY",
"symbol": "¥"
},
"Kenyan Shilling": {
"code": "KES",
"symbol": ""
},
"Som": {
"code": "KGS",
"symbol": "лв"
},
"Riel": {
"code": "KHR",
"symbol": "៛"
},
"Comoro Franc": {
"code": "KMF",
"symbol": ""
},
"North Korean Won": {
"code": "KPW",
"symbol": "₩"
},
"Won": {
"code": "KRW",
"symbol": "₩"
},
"Kuwaiti Dinar": {
"code": "KWD",
"symbol": ""
},
"Cayman Islands Dollar": {
"code": "KYD",
"symbol": "$"
},
"Tenge": {
"code": "KZT",
"symbol": "лв"
},
"Kip": {
"code": "LAK",
"symbol": "₭"
},
"Lebanese Pound": {
"code": "LBP",
"symbol": "£"
},
"Sri Lanka Rupee": {
"code": "LKR",
"symbol": "₨"
},
"Liberian Dollar": {
"code": "LRD",
"symbol": "$"
},
"Lithuanian Litas": {
"code": "LTL",
"symbol": "Lt"
},
"Latvian Lats": {
"code": "LVL",
"symbol": "Ls"
},
"Libyan Dinar": {
"code": "LYD",
"symbol": ""
},
"Moroccan Dirham": {
"code": "MAD",
"symbol": ""
},
"Moldovan Leu": {
"code": "MDL",
"symbol": ""
},
"Malagasy Ariary": {
"code": "MGA",
"symbol": ""
},
"Denar": {
"code": "MKD",
"symbol": "ден"
},
"Kyat": {
"code": "MMK",
"symbol": ""
},
"Tugrik": {
"code": "MNT",
"symbol": "₮"
},
"Pataca": {
"code": "MOP",
"symbol": ""
},
"Ouguiya": {
"code": "MRO",
"symbol": ""
},
"Mauritius Rupee": {
"code": "MUR",
"symbol": "₨"
},
"Rufiyaa": {
"code": "MVR",
"symbol": ""
},
"Kwacha": {
"code": "MWK",
"symbol": ""
},
"Mexican Peso Mexican Unidad de Inversion (UDI)": {
"code": "MXN MXV",
"symbol": "$"
},
"Malaysian Ringgit": {
"code": "MYR",
"symbol": "RM"
},
"Metical": {
"code": "MZN",
"symbol": "MT"
},
"Naira": {
"code": "NGN",
"symbol": "₦"
},
"Cordoba Oro": {
"code": "NIO",
"symbol": "C$"
},
"Norwegian Krone": {
"code": "NOK",
"symbol": "kr"
},
"Nepalese Rupee": {
"code": "NPR",
"symbol": "₨"
},
"New Zealand Dollar": {
"code": "NZD",
"symbol": "$"
},
"Rial Omani": {
"code": "OMR",
"symbol": "﷼"
},
"Balboa US Dollar": {
"code": "PAB USD",
"symbol": "B/."
},
"Nuevo Sol": {
"code": "PEN",
"symbol": "S/."
},
"Kina": {
"code": "PGK",
"symbol": ""
},
"Philippine Peso": {
"code": "PHP",
"symbol": "Php"
},
"Pakistan Rupee": {
"code": "PKR",
"symbol": "₨"
},
"Zloty": {
"code": "PLN",
"symbol": "zł"
},
"Guarani": {
"code": "PYG",
"symbol": "Gs"
},
"Qatari Rial": {
"code": "QAR",
"symbol": "﷼"
},
"New Leu": {
"code": "RON",
"symbol": "lei"
},
"Serbian Dinar": {
"code": "RSD",
"symbol": "Дин."
},
"Russian Ruble": {
"code": "RUB",
"symbol": "руб"
},
"Rwanda Franc": {
"code": "RWF",
"symbol": ""
},
"Saudi Riyal": {
"code": "SAR",
"symbol": "﷼"
},
"Solomon Islands Dollar": {
"code": "SBD",
"symbol": "$"
},
"Seychelles Rupee": {
"code": "SCR",
"symbol": "₨"
},
"Sudanese Pound": {
"code": "SDG",
"symbol": ""
},
"Swedish Krona": {
"code": "SEK",
"symbol": "kr"
},
"Singapore Dollar": {
"code": "SGD",
"symbol": "$"
},
"Saint Helena Pound": {
"code": "SHP",
"symbol": "£"
},
"Leone": {
"code": "SLL",
"symbol": ""
},
"Somali Shilling": {
"code": "SOS",
"symbol": "S"
},
"Surinam Dollar": {
"code": "SRD",
"symbol": "$"
},
"Dobra": {
"code": "STD",
"symbol": ""
},
"El Salvador Colon US Dollar": {
"code": "SVC USD",
"symbol": "$"
},
"Syrian Pound": {
"code": "SYP",
"symbol": "£"
},
"Lilangeni": {
"code": "SZL",
"symbol": ""
},
"Baht": {
"code": "THB",
"symbol": "฿"
},
"Somoni": {
"code": "TJS",
"symbol": ""
},
"Manat": {
"code": "TMT",
"symbol": ""
},
"Tunisian Dinar": {
"code": "TND",
"symbol": ""
},
"Pa'anga": {
"code": "TOP",
"symbol": ""
},
"Turkish Lira": {
"code": "TRY",
"symbol": "TL"
},
"Trinidad and Tobago Dollar": {
"code": "TTD",
"symbol": "TT$"
},
"New Taiwan Dollar": {
"code": "TWD",
"symbol": "NT$"
},
"Tanzanian Shilling": {
"code": "TZS",
"symbol": ""
},
"Hryvnia": {
"code": "UAH",
"symbol": "₴"
},
"Uganda Shilling": {
"code": "UGX",
"symbol": ""
},
"US Dollar": {
"code": "USD",
"symbol": "$"
},
"Peso Uruguayo Uruguay Peso en Unidades Indexadas": {
"code": "UYU UYI",
"symbol": "$U"
},
"Uzbekistan Sum": {
"code": "UZS",
"symbol": "лв"
},
"Bolivar Fuerte": {
"code": "VEF",
"symbol": "Bs"
},
"Dong": {
"code": "VND",
"symbol": "₫"
},
"Vatu": {
"code": "VUV",
"symbol": ""
},
"Tala": {
"code": "WST",
"symbol": ""
},
"CFA Franc BEAC": {
"code": "XAF",
"symbol": ""
},
"Silver": {
"code": "XAG",
"symbol": ""
},
"Gold": {
"code": "XAU",
"symbol": ""
},
"Bond Markets Units European Composite Unit (EURCO)": {
"code": "XBA",
"symbol": ""
},
"European Monetary Unit (E.M.U.-6)": {
"code": "XBB",
"symbol": ""
},
"European Unit of Account 9(E.U.A.-9)": {
"code": "XBC",
"symbol": ""
},
"European Unit of Account 17(E.U.A.-17)": {
"code": "XBD",
"symbol": ""
},
"East Caribbean Dollar": {
"code": "XCD",
"symbol": "$"
},
"SDR": {
"code": "XDR",
"symbol": ""
},
"UIC-Franc": {
"code": "XFU",
"symbol": ""
},
"CFA Franc BCEAO": {
"code": "XOF",
"symbol": ""
},
"Palladium": {
"code": "XPD",
"symbol": ""
},
"CFP Franc": {
"code": "XPF",
"symbol": ""
},
"Platinum": {
"code": "XPT",
"symbol": ""
},
"Codes specifically reserved for testing purposes": {
"code": "XTS",
"symbol": ""
},
"Yemeni Rial": {
"code": "YER",
"symbol": "﷼"
},
"Rand": {
"code": "ZAR",
"symbol": "R"
},
"Rand Loti": {
"code": "ZAR LSL",
"symbol": ""
},
"Rand Namibia Dollar": {
"code": "ZAR NAD",
"symbol": ""
},
"Zambian Kwacha": {
"code": "ZMK",
"symbol": ""
},
"Zimbabwe Dollar": {
"code": "ZWL",
"symbol": ""
}
};
},{}],106:[function(require,module,exports){
var finance = {};
module['exports'] = finance;
finance.account_type = require("./account_type");
finance.transaction_type = require("./transaction_type");
finance.currency = require("./currency");
},{"./account_type":104,"./currency":105,"./transaction_type":107}],107:[function(require,module,exports){
module["exports"] = [
"deposit",
"withdrawal",
"payment",
"invoice"
];
},{}],108:[function(require,module,exports){
module["exports"] = [
"TCP",
"HTTP",
"SDD",
"RAM",
"GB",
"CSS",
"SSL",
"AGP",
"SQL",
"FTP",
"PCI",
"AI",
"ADP",
"RSS",
"XML",
"EXE",
"COM",
"HDD",
"THX",
"SMTP",
"SMS",
"USB",
"PNG",
"SAS",
"IB",
"SCSI",
"JSON",
"XSS",
"JBOD"
];
},{}],109:[function(require,module,exports){
module["exports"] = [
"auxiliary",
"primary",
"back-end",
"digital",
"open-source",
"virtual",
"cross-platform",
"redundant",
"online",
"haptic",
"multi-byte",
"bluetooth",
"wireless",
"1080p",
"neural",
"optical",
"solid state",
"mobile"
];
},{}],110:[function(require,module,exports){
var hacker = {};
module['exports'] = hacker;
hacker.abbreviation = require("./abbreviation");
hacker.adjective = require("./adjective");
hacker.noun = require("./noun");
hacker.verb = require("./verb");
hacker.ingverb = require("./ingverb");
},{"./abbreviation":108,"./adjective":109,"./ingverb":111,"./noun":112,"./verb":113}],111:[function(require,module,exports){
module["exports"] = [
"backing up",
"bypassing",
"hacking",
"overriding",
"compressing",
"copying",
"navigating",
"indexing",
"connecting",
"generating",
"quantifying",
"calculating",
"synthesizing",
"transmitting",
"programming",
"parsing"
];
},{}],112:[function(require,module,exports){
module["exports"] = [
"driver",
"protocol",
"bandwidth",
"panel",
"microchip",
"program",
"port",
"card",
"array",
"interface",
"system",
"sensor",
"firewall",
"hard drive",
"pixel",
"alarm",
"feed",
"monitor",
"application",
"transmitter",
"bus",
"circuit",
"capacitor",
"matrix"
];
},{}],113:[function(require,module,exports){
module["exports"] = [
"back up",
"bypass",
"hack",
"override",
"compress",
"copy",
"navigate",
"index",
"connect",
"generate",
"quantify",
"calculate",
"synthesize",
"input",
"transmit",
"program",
"reboot",
"parse"
];
},{}],114:[function(require,module,exports){
var en = {};
module['exports'] = en;
en.title = "English";
en.separator = " & ";
en.address = require("./address");
en.credit_card = require("./credit_card");
en.company = require("./company");
en.internet = require("./internet");
en.lorem = require("./lorem");
en.name = require("./name");
en.phone_number = require("./phone_number");
en.cell_phone = require("./cell_phone");
en.business = require("./business");
en.commerce = require("./commerce");
en.team = require("./team");
en.hacker = require("./hacker");
en.app = require("./app");
en.finance = require("./finance");
en.date = require("./date");
},{"./address":57,"./app":68,"./business":74,"./cell_phone":76,"./commerce":79,"./company":86,"./credit_card":93,"./date":101,"./finance":106,"./hacker":110,"./internet":118,"./lorem":119,"./name":123,"./phone_number":130,"./team":132}],115:[function(require,module,exports){
module["exports"] = [
"https://s3.amazonaws.com/uifaces/faces/twitter/jarjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahdif/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sprayaga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruzinav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Skyhartman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moscoz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurafire/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/91bilal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malykhinv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kushsolitary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowshade/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heyimjuani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/envex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/unterdreht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/collegeman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peejfancher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andyisonline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ultragex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fuck_you_two/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetalpbalkan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Stievius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerem/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osvaldas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelceballos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrykoblentz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weglov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandclay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetsulek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolasfolliot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayrobinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorerixon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michzen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markjenkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolai_larsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noxdzine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alagoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/idiot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadengle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutlu82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/simobenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vocino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guiiipontes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soyjavi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshaustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomaslau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VinThomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ManikRathee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/langate/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cemshid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leemunroe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_shahedk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BillSKenney/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/divya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshhemsley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sindresorhus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soffes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/9lessons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linux29/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Chakintosh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anaami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joreira/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shadeed9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottkclark/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jedbridges/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salleedesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marakasina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BrianPurkiss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelmartinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bublienko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devankoshal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ZacharyZorbas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timmillwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuasortino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/damenleeturks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomas_janousek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herrhaase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/RussellBishop/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brajeshwar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nachtmeister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bermonpainter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdullindenis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isacosta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suprb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yalozhkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chandlervdw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamgarth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_victa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/commadelimited/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roybarberuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/axel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ffbel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/syropian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ankitind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/traneblow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flashmurphy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ChrisFarina78/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baliomega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschamt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jm_denis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kennyadr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chatyrko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dingyi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mds/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terryxlife/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaroni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kinday/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eduardostuart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhilipsiva/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/GavicoInd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rohixx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakesimkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leeiio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjrus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uberschizo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefoundry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/claudioguglieri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ripplemdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/exentrich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jakemoore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joaoedumedeiros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/poormini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tereshenkov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keryilmaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haydn_woods/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/llun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sgaurav_baghel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jamiebrittain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/badlittleduck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pifagor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agromov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/erwanhesry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diesellaws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiaha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/koridhandy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewcohen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smaczny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gonzalorobaina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nandini_m/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sydlawrence/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdharrison/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgerken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lewisainslie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliecwaite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robbschiller/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flexrs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattdetails/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raquelwilson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrmartineau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/opnsrce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hgharrygo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximseshuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxalex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samihah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chanpory/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sharvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josemarques/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jefffis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krystalfister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lokesh_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedamianhdez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dpmachado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/funwatercat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timothycd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ivanfilipovbg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/picard102/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcobarbosa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krasnoukhov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/g3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ademilter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickdt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/operatino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bungiwan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugomano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/logorado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dc_user/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/horaciobella/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teeragit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqonicd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ilya_pestov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewarrow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssiskind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/HenryHoffman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdsaunders/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamsxu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousoffice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themadray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michigangraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kohette/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nickfratter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/runningskull/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madysondesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenton_clarke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyshen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bradenhamm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurtinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amanruzaini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyhaggard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Karimmove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronalfred/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wtrsld/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jitachi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/therealmarvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pmeissner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ooomz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chacky14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jesseddy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinmatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shanehudson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/IsaryAmairani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arthurholcombe1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andychipster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/boxmodel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ehsandiary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/LucasPerdidao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shalt0ni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swaplord/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaelifa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plbabin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guillemboti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arindam_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/renbyrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thiagovernetti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmillspaysbills/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikemai2awesome/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jervo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mekal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sta1ex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robergd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipecsl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrea211087/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/garand/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abovefunction/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pcridesagain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/randomlies/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BryanHorsey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heykenneth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dahparra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allthingssmitty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvernon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beweinreich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/increase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falvarad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souuf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/orkuncaylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AM_Kn2/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gearpixels/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bassamology/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vimarethomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kosmar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SULiik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrjamesnoble/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silvanmuhlemann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shaneIxD/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nacho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yigitpinarbasi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buzzusborne/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronkwhite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rmlewisuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giancarlon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nbirckel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_nny_m_cher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sdidonato/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atariboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abotap/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karalek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ludwiczakpawel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nemanjaivanovic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baluli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmadajmi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vovkasolovev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samgrover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derienzo777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonathansimmons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelsonjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/S0ufi4n3/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xtopherpaul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oaktreemedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nateschulte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/findingjenny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/namankreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyzotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/we_social/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leehambley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/solid_color/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abelcabans/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kkusaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jordyvdboom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosgavina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pechkinator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vc27/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdbannon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/croakx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerihenare/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gcmorley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duivvv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschadroste/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorDubugras/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wintopia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattbilotti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taylorling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/megdraws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meln1ks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahmoudmetwally/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Silveredge9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekebradley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/happypeter1983/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travis_arnold/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artem_kostenko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adobi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daykiine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alek_djuric/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scips/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelmendes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrhee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alsobrooks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mcflydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/santi_urso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allfordesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stayuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bertboerland/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marosholly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamnac/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cynthiasavard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muringa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hiemil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jackiesaik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zacsnider/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iduuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antjanus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aroon_sharma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dshster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thehacker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelbrooksjr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanmclaughlin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/clubb3rry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taybenlor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xripunov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/myastro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adityasutomo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/digitalmaverick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hjartstrorn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itolmach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vaughanmoffitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdots/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isnifer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeysafonov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scrapdnb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrismj83/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitorleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sokaniwaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zaki3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/illyzoren/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mocabyte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmanince/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/djsherman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidhemphill/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/waghner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/necodymiconer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/praveen_vijaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbrucci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cliffseal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travishines/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kuldarkalvik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Elt_n/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/phillapier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okseanjay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/id835559/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kudretkeskin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anjhero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duck4fuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scott_riley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noufalibrahim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/h1brd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borges_marcos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devinhalladay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ciaranr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefooo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikebeecham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tonymillion/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuaraichur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/irae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petrangr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmitriychuta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arashmanteghi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ainsleywagon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/svenlen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beshur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlyson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dutchnadia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teddyzetterlund/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samuelkraft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aoimedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/toddrew/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codepoet_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artvavs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benoitboucart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jomarmen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolmarlopez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/creartinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/homka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gaborenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinclediere/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximsorokin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plasticine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j2deme/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peachananr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kapaluccio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/de_ascanio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dawidwu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpatey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/popey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rehatkathuria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_purplebunny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/1markiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ajaxy_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dudestein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskarlevinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorstuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nehfy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vicivadeline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leandrovaranda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottgallant/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victor_haydin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawrb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryhanhassan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amayvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_brixen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karolkrakowiak_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herkulano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geran7/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cggaurav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_witko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lososina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/polarity/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattlat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonburke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/constantx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teylorfeliz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigelimeliah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rachelreveley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reabo101/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rahmeen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickyyean/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sebashton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpenico/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/francis_vega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oktayelipek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kikillo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbianz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrygerard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BroumiYoussef/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/0therplanet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilalsiddique1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ionuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grrr_nl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/liminha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rawdiggie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryandownie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sethlouey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pixage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arpitnj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/switmer777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josevnclch/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kanickairaj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/puzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tbakdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/besbujupi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supjoey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lowie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linkibol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balintorosz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imcoding/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agustincruiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gusoto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasschrijer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/superoutman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kalmerrautam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielizalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gojeanyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidbaldie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_vojto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laurengray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mymyboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nellleo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marciotoledo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ninjad3m0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/to_soham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muridrahhal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/levisan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grahamkennery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepetitogre/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antongenkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nessoila/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amandabuzard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/safrankov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cocolero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dss49/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matt3224/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluesix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/quailandquasar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AlbertoCococi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepinski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sementiy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhudobivnik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thibaut_re/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olgary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shojberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mtolokonnikov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bereto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naupintos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wegotvices/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xadhix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/macxim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rodnylobos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madcampos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebyvadim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartoszdawydzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supervova/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vonachoo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darylws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stevedesigner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mylesb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herbigt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/depaulawagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gizmeedevil1991/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_scottburgess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lisovsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidsasda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artd_sign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/YoungCutlass/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mgonto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorquinn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmond/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oksanafrewer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zauerkraut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkeithmason/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nitinhayaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lmjabreu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mandalareopens/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinkleft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ponchomendivil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juamperro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brunodesign1206/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caseycavanagh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/luxe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dotgridline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spedwig/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madewulf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattsapii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/helderleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisstumph/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayphen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nsamoylov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisvanderkooi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justme_timothyg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/otozk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prinzadi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gu5taf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cyril_gaillard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_kobelyatsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daniloc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nwdsha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/romanbulah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/skkirilov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dvdwinden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dannol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thekevinjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jwalter14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timgthomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buddhasource/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxpiper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thatonetommy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diansigitp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klimmka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gkaam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekcramer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyyo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xalionmalik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edhenderson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keyuri85/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roxanejammet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edkf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alessandroribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacksonlatka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebronjennan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kostaspt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karlkanall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moynihan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danpliego/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saulihirvi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wesleytrankin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fjaguero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bowbrick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mashaaaaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yassiryahya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dparrelli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fotomagin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/denisepires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqbalperkasa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martinansty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jarsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_oy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielrosser/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malgordon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlfairclough/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelabehsera/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierrestoffe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enjoythetau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/loganjlambert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpeezy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyginnivan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michalhron/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/msveet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lingeswaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolsvein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peter576/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reideiredale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joeymurdah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raphaelnikson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mvdheuvel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maxlinderman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/begreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/frankiefreesbie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robturlinckx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Talbi_ConSept/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/longlivemyword/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vanchesz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maiklam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rez___a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregsqueeb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/greenbes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_ragzor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anthonysukow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fluidbrush/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dactrtr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jehnglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bergmartin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugocornejo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_kkga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dzantievm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawalazar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sovesove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonsgotwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byryan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vytautas_a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizhgan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cicerobr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshelmersson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d33pthought/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davecraige/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nckjrvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexandermayes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jcubic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigrcoles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bagawarman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rob_thomas10/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cofla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maikelk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtgibbons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russell_baylis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhesslow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codysanfilippo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/webtanya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebybrenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dcalonaci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perfectflow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saarabpreet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kumarrajan12123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamsteffen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themikenagle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ceekaytweet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrybolt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/conspirator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dallasbpeters/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n3dmax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terpimost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirillz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byrnecore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j_drake_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hoangloi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tobysaxon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gofrasdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dimaposnyy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjisousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okandungel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/billyroshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskamaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/motionthinks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/knilob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashocka18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marrimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartjo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/omnizya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ernestsemerda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andreas_pr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edgarchris99/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasgeisen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gseguin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joannefournier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/demersdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adammarsbar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nasirwd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n_tassone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/javorszky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themrdave/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yecidsm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicollerich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/canapud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicoleglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/judzhin_miles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/designervzm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kianoshp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evandrix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alterchuca/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhrubo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ma_tiax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssbb_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dorphern/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mauriolg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bruno_mart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mactopus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_winslet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joemdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Shriiiiimp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacobbennett/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nfedoroff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamglimy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allagringaus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olaolusoga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buryaknick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wim1k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicklacke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a1chapone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/steynviljoen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/strikewan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryankirkman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewabogado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doooon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jagan123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariffsetiawan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elenadissi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mwarkentin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrymeier_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_garcia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmackerman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borantula/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/konus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spacewood_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryuchi311/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evanshajed/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tristanlegros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shoaib253/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aislinnkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okcoker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timpetricola/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunshinedgirl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nomidesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petebernardo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottiedude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/millinet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imsoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imammuht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benjamin_knight/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nepdud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joki4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lanceguyatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bboy1895/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amywebbb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rweve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haruintesettden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ricburton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelshd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/batsirai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/primozcigler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jffgrdnr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/8d3k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geneseleznev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/al_li/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souperphly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mslarkina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/2fockus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdavis565/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xiel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/turkutuuli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxward/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebinoclard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauravjassal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidmerrique/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mdsisto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewofficer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kojourin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnirmal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_shiznit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aluisio_azevedo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cloudstudio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvierich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexivanichkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fran_mchamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perretmagali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/betraydan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cadikkara/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matbeedotcom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyworboys/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bpartridge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelkoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silv3rgvn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alevizio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lawlbwoy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitor376/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/desastrozo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thimo_cz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jasonmarkjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lhausermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xravil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guischmitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vigobronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panghal0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelkooreman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/surgeonist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/christianoliff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caspergrl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkarna/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ipavelek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierre_nel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/y2graphic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sterlingrules/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elbuscainfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bennyjien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stushona/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/estebanuribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/embrcecreations/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danillos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charlesrpratt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmeffess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosblanco_eu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leonfedotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rangafangs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_frees/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgormtx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bryan_topham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpscribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mighty55/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carbontwelve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isaacfifth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamjdeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/barputro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/drewbyreese/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachacorazzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bistrianiosip/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magoo04/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pehamondello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yayteejay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_harris88/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/algunsanabria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zforrester/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ovall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosjgsousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geobikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ah_lice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/looneydoodle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerdgr8/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ddggccaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zackeeler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/normanbox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/el_fuertisimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ismail_biltagi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juangomezw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jnmnrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/patrickcoombe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanjohnson_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markolschesky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeffgolenski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kvasnic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lindseyzilla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauchomatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/afusinatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okansurreel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamawesomeface/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emileboudeling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arishi_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juanmamartinez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wikiziner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danthms/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mkginfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terrorpixel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousonaut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prheemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcolenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/foczzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martip07/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaodang17/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johncafazza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinlayfield/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/franciscoamk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdulhyeuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marklamb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edobene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresenfredrik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikaeljorhult/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisslowik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vinciarts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meelford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotnolten/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yehudab/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vijaykarthik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bfrohs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josep_martins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/attacks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tumski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/instalox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mangosango/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/paulfarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kazaky999/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kiwiupover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nvkznemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tom_even/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ratbus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodsman001/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshmedeski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thewillbeard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psaikali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joe_black/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleinadsays/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcusgorillius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hota_v/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jghyllebert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shinze/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/janpalounek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiespoken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/her_ruu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dansowter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipeapiress/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magugzbrand2d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/posterjob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nathalie_fs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobbytwoshoes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dreizle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremymouton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elisabethkjaer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/notbadart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mohanrohith/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jlsolerdeltoro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itskawsar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/slowspock/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zvchkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wiljanslofstra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craighenneberry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trubeatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juaumlol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samscouto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BenouarradeM/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gipsy_raf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/netonet_il/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arkokoley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itsajimithing/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smalonso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victordeanda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_dwite_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richardgarretts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregrwilkinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anatolinicolae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lu4sh1i/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanotirloni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ostirbu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darcystonge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naitanamoreno/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcomiskey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhiardana/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcomano_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidcazalis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falconerie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregkilian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bcrad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bolzanmarco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/low_res/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vlajki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petar_prog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonkspr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmalfikri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mfacchinello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atanism/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/harry_sistalam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/murrayswift/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobwassermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gavr1l0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madshensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_subtle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deviljho_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salimianoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joetruesdell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/twittypork/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/airskylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnezkumar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgajjar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cherif_b/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/louis_currie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deeenright/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cybind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eyronn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vickyshits/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sweetdelisa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cboller1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresdjasso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/melvindidit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andysolomon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaisselenator_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lvovenok/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giuliusa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/belyaev_rs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overcloacked/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kamal_chaneman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/incubo82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hellofeverrrr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhaligowski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunlandictwin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bu7921/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andytlaw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/finchjke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manigm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/umurgdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottfeltham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ganserene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutu_krish/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jodytaggart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ntfblog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tanveerrao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hfalucas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxleroydeval/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kucingbelang4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bargaorobalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colgruv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stalewine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefrost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumannzone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcolberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachingawas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjshaw14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ramanathan_pdy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johndezember/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshoenson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonmorreale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nutzumi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeyalmone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klefue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirangopal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumann_alex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matthewkay_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jay_wilburn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shesgared/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/apriendeau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnriordan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wake_gs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleksitappura/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emsgulam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xilantra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imomenui/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sircalebgrove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/newbrushes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hsinyo23/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m4rio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/katiemdaly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/s4f1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ecommerceil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marlinjayakody/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swooshycueb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sangdth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coderdiaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluefx_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eugeneeweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgclegg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n1ght_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dixchen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakehawksworth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trueblood_33/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hai_ninh_nguyen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marclgonzales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yesmeck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stephcoue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doronmalki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruehldesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anasnakawa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kijanmaharjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wearesavas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefvdham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tweetubhai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alecarpentier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fiterik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyryndya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d00maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/theonlyzeke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/missaaamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manekenthe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reetajayendra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyshimko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrgraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanozoffoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrebay007/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shvelo96/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pyronite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedjpetersen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtyukmaev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_williamguerra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/albertaugustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikashpathak18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinjohndayy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vj_demien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colirpixoil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/goddardlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laasli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jqiuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heycamtaylor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nastya_mane/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mastermindesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nyancecom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sandywoodruff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bighanddesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sbtransparent/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aviddayentonbay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richwild/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaysix_dizzy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tur8le/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/seyedhossein1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/privetwagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmandenn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dev_essentials/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmfsocial/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_yardenoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mateaodviteza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weavermedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mufaddal_mw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hafeeskhan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashernatali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sulaqo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eddiechen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josecarlospsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vm_f/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enricocicconi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danmartin70/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gmourier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/donjain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrxloka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_pedropinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eitarafa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oscarowusu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ralph_lam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panchajanyag/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodydotmx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jerrybai1907/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marshallchen_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xamorep/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aio___/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaabane_wail/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/txcx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akashsharma39/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falling_soul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sainraja/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mugukamil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johannesneu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markwienands/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karthipanraj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balakayuriy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alan_zhang_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/layerssss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaspernordkvist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mirfanqureshi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hanna_smi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VMilescu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aeon56/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sreejithexp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dicesales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhoot_amit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smenov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lonesomelemon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladimirdevic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelcipriano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haligaliharun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buleswapnil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/serefka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ifarafonow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikasvinfotech/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/urrutimeoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areandacom/128.jpg"
];
},{}],116:[function(require,module,exports){
module["exports"] = [
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],117:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com"
];
},{}],118:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.domain_suffix = require("./domain_suffix");
internet.avatar_uri = require("./avatar_uri");
},{"./avatar_uri":115,"./domain_suffix":116,"./free_email":117}],119:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
lorem.supplemental = require("./supplemental");
},{"./supplemental":120,"./words":121}],120:[function(require,module,exports){
module["exports"] = [
"abbas",
"abduco",
"abeo",
"abscido",
"absconditus",
"absens",
"absorbeo",
"absque",
"abstergo",
"absum",
"abundans",
"abutor",
"accedo",
"accendo",
"acceptus",
"accipio",
"accommodo",
"accusator",
"acer",
"acerbitas",
"acervus",
"acidus",
"acies",
"acquiro",
"acsi",
"adamo",
"adaugeo",
"addo",
"adduco",
"ademptio",
"adeo",
"adeptio",
"adfectus",
"adfero",
"adficio",
"adflicto",
"adhaero",
"adhuc",
"adicio",
"adimpleo",
"adinventitias",
"adipiscor",
"adiuvo",
"administratio",
"admiratio",
"admitto",
"admoneo",
"admoveo",
"adnuo",
"adopto",
"adsidue",
"adstringo",
"adsuesco",
"adsum",
"adulatio",
"adulescens",
"adultus",
"aduro",
"advenio",
"adversus",
"advoco",
"aedificium",
"aeger",
"aegre",
"aegrotatio",
"aegrus",
"aeneus",
"aequitas",
"aequus",
"aer",
"aestas",
"aestivus",
"aestus",
"aetas",
"aeternus",
"ager",
"aggero",
"aggredior",
"agnitio",
"agnosco",
"ago",
"ait",
"aiunt",
"alienus",
"alii",
"alioqui",
"aliqua",
"alius",
"allatus",
"alo",
"alter",
"altus",
"alveus",
"amaritudo",
"ambitus",
"ambulo",
"amicitia",
"amiculum",
"amissio",
"amita",
"amitto",
"amo",
"amor",
"amoveo",
"amplexus",
"amplitudo",
"amplus",
"ancilla",
"angelus",
"angulus",
"angustus",
"animadverto",
"animi",
"animus",
"annus",
"anser",
"ante",
"antea",
"antepono",
"antiquus",
"aperio",
"aperte",
"apostolus",
"apparatus",
"appello",
"appono",
"appositus",
"approbo",
"apto",
"aptus",
"apud",
"aqua",
"ara",
"aranea",
"arbitro",
"arbor",
"arbustum",
"arca",
"arceo",
"arcesso",
"arcus",
"argentum",
"argumentum",
"arguo",
"arma",
"armarium",
"armo",
"aro",
"ars",
"articulus",
"artificiose",
"arto",
"arx",
"ascisco",
"ascit",
"asper",
"aspicio",
"asporto",
"assentator",
"astrum",
"atavus",
"ater",
"atqui",
"atrocitas",
"atrox",
"attero",
"attollo",
"attonbitus",
"auctor",
"auctus",
"audacia",
"audax",
"audentia",
"audeo",
"audio",
"auditor",
"aufero",
"aureus",
"auris",
"aurum",
"aut",
"autem",
"autus",
"auxilium",
"avaritia",
"avarus",
"aveho",
"averto",
"avoco",
"baiulus",
"balbus",
"barba",
"bardus",
"basium",
"beatus",
"bellicus",
"bellum",
"bene",
"beneficium",
"benevolentia",
"benigne",
"bestia",
"bibo",
"bis",
"blandior",
"bonus",
"bos",
"brevis",
"cado",
"caecus",
"caelestis",
"caelum",
"calamitas",
"calcar",
"calco",
"calculus",
"callide",
"campana",
"candidus",
"canis",
"canonicus",
"canto",
"capillus",
"capio",
"capitulus",
"capto",
"caput",
"carbo",
"carcer",
"careo",
"caries",
"cariosus",
"caritas",
"carmen",
"carpo",
"carus",
"casso",
"caste",
"casus",
"catena",
"caterva",
"cattus",
"cauda",
"causa",
"caute",
"caveo",
"cavus",
"cedo",
"celebrer",
"celer",
"celo",
"cena",
"cenaculum",
"ceno",
"censura",
"centum",
"cerno",
"cernuus",
"certe",
"certo",
"certus",
"cervus",
"cetera",
"charisma",
"chirographum",
"cibo",
"cibus",
"cicuta",
"cilicium",
"cimentarius",
"ciminatio",
"cinis",
"circumvenio",
"cito",
"civis",
"civitas",
"clam",
"clamo",
"claro",
"clarus",
"claudeo",
"claustrum",
"clementia",
"clibanus",
"coadunatio",
"coaegresco",
"coepi",
"coerceo",
"cogito",
"cognatus",
"cognomen",
"cogo",
"cohaero",
"cohibeo",
"cohors",
"colligo",
"colloco",
"collum",
"colo",
"color",
"coma",
"combibo",
"comburo",
"comedo",
"comes",
"cometes",
"comis",
"comitatus",
"commemoro",
"comminor",
"commodo",
"communis",
"comparo",
"compello",
"complectus",
"compono",
"comprehendo",
"comptus",
"conatus",
"concedo",
"concido",
"conculco",
"condico",
"conduco",
"confero",
"confido",
"conforto",
"confugo",
"congregatio",
"conicio",
"coniecto",
"conitor",
"coniuratio",
"conor",
"conqueror",
"conscendo",
"conservo",
"considero",
"conspergo",
"constans",
"consuasor",
"contabesco",
"contego",
"contigo",
"contra",
"conturbo",
"conventus",
"convoco",
"copia",
"copiose",
"cornu",
"corona",
"corpus",
"correptius",
"corrigo",
"corroboro",
"corrumpo",
"coruscus",
"cotidie",
"crapula",
"cras",
"crastinus",
"creator",
"creber",
"crebro",
"credo",
"creo",
"creptio",
"crepusculum",
"cresco",
"creta",
"cribro",
"crinis",
"cruciamentum",
"crudelis",
"cruentus",
"crur",
"crustulum",
"crux",
"cubicularis",
"cubitum",
"cubo",
"cui",
"cuius",
"culpa",
"culpo",
"cultellus",
"cultura",
"cum",
"cunabula",
"cunae",
"cunctatio",
"cupiditas",
"cupio",
"cuppedia",
"cupressus",
"cur",
"cura",
"curatio",
"curia",
"curiositas",
"curis",
"curo",
"curriculum",
"currus",
"cursim",
"curso",
"cursus",
"curto",
"curtus",
"curvo",
"curvus",
"custodia",
"damnatio",
"damno",
"dapifer",
"debeo",
"debilito",
"decens",
"decerno",
"decet",
"decimus",
"decipio",
"decor",
"decretum",
"decumbo",
"dedecor",
"dedico",
"deduco",
"defaeco",
"defendo",
"defero",
"defessus",
"defetiscor",
"deficio",
"defigo",
"defleo",
"defluo",
"defungo",
"degenero",
"degero",
"degusto",
"deinde",
"delectatio",
"delego",
"deleo",
"delibero",
"delicate",
"delinquo",
"deludo",
"demens",
"demergo",
"demitto",
"demo",
"demonstro",
"demoror",
"demulceo",
"demum",
"denego",
"denique",
"dens",
"denuncio",
"denuo",
"deorsum",
"depereo",
"depono",
"depopulo",
"deporto",
"depraedor",
"deprecator",
"deprimo",
"depromo",
"depulso",
"deputo",
"derelinquo",
"derideo",
"deripio",
"desidero",
"desino",
"desipio",
"desolo",
"desparatus",
"despecto",
"despirmatio",
"infit",
"inflammatio",
"paens",
"patior",
"patria",
"patrocinor",
"patruus",
"pauci",
"paulatim",
"pauper",
"pax",
"peccatus",
"pecco",
"pecto",
"pectus",
"pecunia",
"pecus",
"peior",
"pel",
"ocer",
"socius",
"sodalitas",
"sol",
"soleo",
"solio",
"solitudo",
"solium",
"sollers",
"sollicito",
"solum",
"solus",
"solutio",
"solvo",
"somniculosus",
"somnus",
"sonitus",
"sono",
"sophismata",
"sopor",
"sordeo",
"sortitus",
"spargo",
"speciosus",
"spectaculum",
"speculum",
"sperno",
"spero",
"spes",
"spiculum",
"spiritus",
"spoliatio",
"sponte",
"stabilis",
"statim",
"statua",
"stella",
"stillicidium",
"stipes",
"stips",
"sto",
"strenuus",
"strues",
"studio",
"stultus",
"suadeo",
"suasoria",
"sub",
"subito",
"subiungo",
"sublime",
"subnecto",
"subseco",
"substantia",
"subvenio",
"succedo",
"succurro",
"sufficio",
"suffoco",
"suffragium",
"suggero",
"sui",
"sulum",
"sum",
"summa",
"summisse",
"summopere",
"sumo",
"sumptus",
"supellex",
"super",
"suppellex",
"supplanto",
"suppono",
"supra",
"surculus",
"surgo",
"sursum",
"suscipio",
"suspendo",
"sustineo",
"suus",
"synagoga",
"tabella",
"tabernus",
"tabesco",
"tabgo",
"tabula",
"taceo",
"tactus",
"taedium",
"talio",
"talis",
"talus",
"tam",
"tamdiu",
"tamen",
"tametsi",
"tamisium",
"tamquam",
"tandem",
"tantillus",
"tantum",
"tardus",
"tego",
"temeritas",
"temperantia",
"templum",
"temptatio",
"tempus",
"tenax",
"tendo",
"teneo",
"tener",
"tenuis",
"tenus",
"tepesco",
"tepidus",
"ter",
"terebro",
"teres",
"terga",
"tergeo",
"tergiversatio",
"tergo",
"tergum",
"termes",
"terminatio",
"tero",
"terra",
"terreo",
"territo",
"terror",
"tersus",
"tertius",
"testimonium",
"texo",
"textilis",
"textor",
"textus",
"thalassinus",
"theatrum",
"theca",
"thema",
"theologus",
"thermae",
"thesaurus",
"thesis",
"thorax",
"thymbra",
"thymum",
"tibi",
"timidus",
"timor",
"titulus",
"tolero",
"tollo",
"tondeo",
"tonsor",
"torqueo",
"torrens",
"tot",
"totidem",
"toties",
"totus",
"tracto",
"trado",
"traho",
"trans",
"tredecim",
"tremo",
"trepide",
"tres",
"tribuo",
"tricesimus",
"triduana",
"triginta",
"tripudio",
"tristis",
"triumphus",
"trucido",
"truculenter",
"tubineus",
"tui",
"tum",
"tumultus",
"tunc",
"turba",
"turbo",
"turpe",
"turpis",
"tutamen",
"tutis",
"tyrannus",
"uberrime",
"ubi",
"ulciscor",
"ullus",
"ulterius",
"ultio",
"ultra",
"umbra",
"umerus",
"umquam",
"una",
"unde",
"undique",
"universe",
"unus",
"urbanus",
"urbs",
"uredo",
"usitas",
"usque",
"ustilo",
"ustulo",
"usus",
"uter",
"uterque",
"utilis",
"utique",
"utor",
"utpote",
"utrimque",
"utroque",
"utrum",
"uxor",
"vaco",
"vacuus",
"vado",
"vae",
"valde",
"valens",
"valeo",
"valetudo",
"validus",
"vallum",
"vapulus",
"varietas",
"varius",
"vehemens",
"vel",
"velociter",
"velum",
"velut",
"venia",
"venio",
"ventito",
"ventosus",
"ventus",
"venustas",
"ver",
"verbera",
"verbum",
"vere",
"verecundia",
"vereor",
"vergo",
"veritas",
"vero",
"versus",
"verto",
"verumtamen",
"verus",
"vesco",
"vesica",
"vesper",
"vespillo",
"vester",
"vestigium",
"vestrum",
"vetus",
"via",
"vicinus",
"vicissitudo",
"victoria",
"victus",
"videlicet",
"video",
"viduata",
"viduo",
"vigilo",
"vigor",
"vilicus",
"vilis",
"vilitas",
"villa",
"vinco",
"vinculum",
"vindico",
"vinitor",
"vinum",
"vir",
"virga",
"virgo",
"viridis",
"viriliter",
"virtus",
"vis",
"viscus",
"vita",
"vitiosus",
"vitium",
"vito",
"vivo",
"vix",
"vobis",
"vociferor",
"voco",
"volaticus",
"volo",
"volubilis",
"voluntarius",
"volup",
"volutabrum",
"volva",
"vomer",
"vomica",
"vomito",
"vorago",
"vorax",
"voro",
"vos",
"votum",
"voveo",
"vox",
"vulariter",
"vulgaris",
"vulgivagus",
"vulgo",
"vulgus",
"vulnero",
"vulnus",
"vulpes",
"vulticulus",
"vultuosus",
"xiphias"
];
},{}],121:[function(require,module,exports){
module["exports"] = [
"alias",
"consequatur",
"aut",
"perferendis",
"sit",
"voluptatem",
"accusantium",
"doloremque",
"aperiam",
"eaque",
"ipsa",
"quae",
"ab",
"illo",
"inventore",
"veritatis",
"et",
"quasi",
"architecto",
"beatae",
"vitae",
"dicta",
"sunt",
"explicabo",
"aspernatur",
"aut",
"odit",
"aut",
"fugit",
"sed",
"quia",
"consequuntur",
"magni",
"dolores",
"eos",
"qui",
"ratione",
"voluptatem",
"sequi",
"nesciunt",
"neque",
"dolorem",
"ipsum",
"quia",
"dolor",
"sit",
"amet",
"consectetur",
"adipisci",
"velit",
"sed",
"quia",
"non",
"numquam",
"eius",
"modi",
"tempora",
"incidunt",
"ut",
"labore",
"et",
"dolore",
"magnam",
"aliquam",
"quaerat",
"voluptatem",
"ut",
"enim",
"ad",
"minima",
"veniam",
"quis",
"nostrum",
"exercitationem",
"ullam",
"corporis",
"nemo",
"enim",
"ipsam",
"voluptatem",
"quia",
"voluptas",
"sit",
"suscipit",
"laboriosam",
"nisi",
"ut",
"aliquid",
"ex",
"ea",
"commodi",
"consequatur",
"quis",
"autem",
"vel",
"eum",
"iure",
"reprehenderit",
"qui",
"in",
"ea",
"voluptate",
"velit",
"esse",
"quam",
"nihil",
"molestiae",
"et",
"iusto",
"odio",
"dignissimos",
"ducimus",
"qui",
"blanditiis",
"praesentium",
"laudantium",
"totam",
"rem",
"voluptatum",
"deleniti",
"atque",
"corrupti",
"quos",
"dolores",
"et",
"quas",
"molestias",
"excepturi",
"sint",
"occaecati",
"cupiditate",
"non",
"provident",
"sed",
"ut",
"perspiciatis",
"unde",
"omnis",
"iste",
"natus",
"error",
"similique",
"sunt",
"in",
"culpa",
"qui",
"officia",
"deserunt",
"mollitia",
"animi",
"id",
"est",
"laborum",
"et",
"dolorum",
"fuga",
"et",
"harum",
"quidem",
"rerum",
"facilis",
"est",
"et",
"expedita",
"distinctio",
"nam",
"libero",
"tempore",
"cum",
"soluta",
"nobis",
"est",
"eligendi",
"optio",
"cumque",
"nihil",
"impedit",
"quo",
"porro",
"quisquam",
"est",
"qui",
"minus",
"id",
"quod",
"maxime",
"placeat",
"facere",
"possimus",
"omnis",
"voluptas",
"assumenda",
"est",
"omnis",
"dolor",
"repellendus",
"temporibus",
"autem",
"quibusdam",
"et",
"aut",
"consequatur",
"vel",
"illum",
"qui",
"dolorem",
"eum",
"fugiat",
"quo",
"voluptas",
"nulla",
"pariatur",
"at",
"vero",
"eos",
"et",
"accusamus",
"officiis",
"debitis",
"aut",
"rerum",
"necessitatibus",
"saepe",
"eveniet",
"ut",
"et",
"voluptates",
"repudiandae",
"sint",
"et",
"molestiae",
"non",
"recusandae",
"itaque",
"earum",
"rerum",
"hic",
"tenetur",
"a",
"sapiente",
"delectus",
"ut",
"aut",
"reiciendis",
"voluptatibus",
"maiores",
"doloribus",
"asperiores",
"repellat"
];
},{}],122:[function(require,module,exports){
module["exports"] = [
"Aaliyah",
"Aaron",
"Abagail",
"Abbey",
"Abbie",
"Abbigail",
"Abby",
"Abdiel",
"Abdul",
"Abdullah",
"Abe",
"Abel",
"Abelardo",
"Abigail",
"Abigale",
"Abigayle",
"Abner",
"Abraham",
"Ada",
"Adah",
"Adalberto",
"Adaline",
"Adam",
"Adan",
"Addie",
"Addison",
"Adela",
"Adelbert",
"Adele",
"Adelia",
"Adeline",
"Adell",
"Adella",
"Adelle",
"Aditya",
"Adolf",
"Adolfo",
"Adolph",
"Adolphus",
"Adonis",
"Adrain",
"Adrian",
"Adriana",
"Adrianna",
"Adriel",
"Adrien",
"Adrienne",
"Afton",
"Aglae",
"Agnes",
"Agustin",
"Agustina",
"Ahmad",
"Ahmed",
"Aida",
"Aidan",
"Aiden",
"Aileen",
"Aimee",
"Aisha",
"Aiyana",
"Akeem",
"Al",
"Alaina",
"Alan",
"Alana",
"Alanis",
"Alanna",
"Alayna",
"Alba",
"Albert",
"Alberta",
"Albertha",
"Alberto",
"Albin",
"Albina",
"Alda",
"Alden",
"Alec",
"Aleen",
"Alejandra",
"Alejandrin",
"Alek",
"Alena",
"Alene",
"Alessandra",
"Alessandro",
"Alessia",
"Aletha",
"Alex",
"Alexa",
"Alexander",
"Alexandra",
"Alexandre",
"Alexandrea",
"Alexandria",
"Alexandrine",
"Alexandro",
"Alexane",
"Alexanne",
"Alexie",
"Alexis",
"Alexys",
"Alexzander",
"Alf",
"Alfonso",
"Alfonzo",
"Alford",
"Alfred",
"Alfreda",
"Alfredo",
"Ali",
"Alia",
"Alice",
"Alicia",
"Alisa",
"Alisha",
"Alison",
"Alivia",
"Aliya",
"Aliyah",
"Aliza",
"Alize",
"Allan",
"Allen",
"Allene",
"Allie",
"Allison",
"Ally",
"Alphonso",
"Alta",
"Althea",
"Alva",
"Alvah",
"Alvena",
"Alvera",
"Alverta",
"Alvina",
"Alvis",
"Alyce",
"Alycia",
"Alysa",
"Alysha",
"Alyson",
"Alysson",
"Amalia",
"Amanda",
"Amani",
"Amara",
"Amari",
"Amaya",
"Amber",
"Ambrose",
"Amelia",
"Amelie",
"Amely",
"America",
"Americo",
"Amie",
"Amina",
"Amir",
"Amira",
"Amiya",
"Amos",
"Amparo",
"Amy",
"Amya",
"Ana",
"Anabel",
"Anabelle",
"Anahi",
"Anais",
"Anastacio",
"Anastasia",
"Anderson",
"Andre",
"Andreane",
"Andreanne",
"Andres",
"Andrew",
"Andy",
"Angel",
"Angela",
"Angelica",
"Angelina",
"Angeline",
"Angelita",
"Angelo",
"Angie",
"Angus",
"Anibal",
"Anika",
"Anissa",
"Anita",
"Aniya",
"Aniyah",
"Anjali",
"Anna",
"Annabel",
"Annabell",
"Annabelle",
"Annalise",
"Annamae",
"Annamarie",
"Anne",
"Annetta",
"Annette",
"Annie",
"Ansel",
"Ansley",
"Anthony",
"Antoinette",
"Antone",
"Antonetta",
"Antonette",
"Antonia",
"Antonietta",
"Antonina",
"Antonio",
"Antwan",
"Antwon",
"Anya",
"April",
"Ara",
"Araceli",
"Aracely",
"Arch",
"Archibald",
"Ardella",
"Arden",
"Ardith",
"Arely",
"Ari",
"Ariane",
"Arianna",
"Aric",
"Ariel",
"Arielle",
"Arjun",
"Arlene",
"Arlie",
"Arlo",
"Armand",
"Armando",
"Armani",
"Arnaldo",
"Arne",
"Arno",
"Arnold",
"Arnoldo",
"Arnulfo",
"Aron",
"Art",
"Arthur",
"Arturo",
"Arvel",
"Arvid",
"Arvilla",
"Aryanna",
"Asa",
"Asha",
"Ashlee",
"Ashleigh",
"Ashley",
"Ashly",
"Ashlynn",
"Ashton",
"Ashtyn",
"Asia",
"Assunta",
"Astrid",
"Athena",
"Aubree",
"Aubrey",
"Audie",
"Audra",
"Audreanne",
"Audrey",
"August",
"Augusta",
"Augustine",
"Augustus",
"Aurelia",
"Aurelie",
"Aurelio",
"Aurore",
"Austen",
"Austin",
"Austyn",
"Autumn",
"Ava",
"Avery",
"Avis",
"Axel",
"Ayana",
"Ayden",
"Ayla",
"Aylin",
"Baby",
"Bailee",
"Bailey",
"Barbara",
"Barney",
"Baron",
"Barrett",
"Barry",
"Bart",
"Bartholome",
"Barton",
"Baylee",
"Beatrice",
"Beau",
"Beaulah",
"Bell",
"Bella",
"Belle",
"Ben",
"Benedict",
"Benjamin",
"Bennett",
"Bennie",
"Benny",
"Benton",
"Berenice",
"Bernadette",
"Bernadine",
"Bernard",
"Bernardo",
"Berneice",
"Bernhard",
"Bernice",
"Bernie",
"Berniece",
"Bernita",
"Berry",
"Bert",
"Berta",
"Bertha",
"Bertram",
"Bertrand",
"Beryl",
"Bessie",
"Beth",
"Bethany",
"Bethel",
"Betsy",
"Bette",
"Bettie",
"Betty",
"Bettye",
"Beulah",
"Beverly",
"Bianka",
"Bill",
"Billie",
"Billy",
"Birdie",
"Blair",
"Blaise",
"Blake",
"Blanca",
"Blanche",
"Blaze",
"Bo",
"Bobbie",
"Bobby",
"Bonita",
"Bonnie",
"Boris",
"Boyd",
"Brad",
"Braden",
"Bradford",
"Bradley",
"Bradly",
"Brady",
"Braeden",
"Brain",
"Brandi",
"Brando",
"Brandon",
"Brandt",
"Brandy",
"Brandyn",
"Brannon",
"Branson",
"Brant",
"Braulio",
"Braxton",
"Brayan",
"Breana",
"Breanna",
"Breanne",
"Brenda",
"Brendan",
"Brenden",
"Brendon",
"Brenna",
"Brennan",
"Brennon",
"Brent",
"Bret",
"Brett",
"Bria",
"Brian",
"Briana",
"Brianne",
"Brice",
"Bridget",
"Bridgette",
"Bridie",
"Brielle",
"Brigitte",
"Brionna",
"Brisa",
"Britney",
"Brittany",
"Brock",
"Broderick",
"Brody",
"Brook",
"Brooke",
"Brooklyn",
"Brooks",
"Brown",
"Bruce",
"Bryana",
"Bryce",
"Brycen",
"Bryon",
"Buck",
"Bud",
"Buddy",
"Buford",
"Bulah",
"Burdette",
"Burley",
"Burnice",
"Buster",
"Cade",
"Caden",
"Caesar",
"Caitlyn",
"Cale",
"Caleb",
"Caleigh",
"Cali",
"Calista",
"Callie",
"Camden",
"Cameron",
"Camila",
"Camilla",
"Camille",
"Camren",
"Camron",
"Camryn",
"Camylle",
"Candace",
"Candelario",
"Candice",
"Candida",
"Candido",
"Cara",
"Carey",
"Carissa",
"Carlee",
"Carleton",
"Carley",
"Carli",
"Carlie",
"Carlo",
"Carlos",
"Carlotta",
"Carmel",
"Carmela",
"Carmella",
"Carmelo",
"Carmen",
"Carmine",
"Carol",
"Carolanne",
"Carole",
"Carolina",
"Caroline",
"Carolyn",
"Carolyne",
"Carrie",
"Carroll",
"Carson",
"Carter",
"Cary",
"Casandra",
"Casey",
"Casimer",
"Casimir",
"Casper",
"Cassandra",
"Cassandre",
"Cassidy",
"Cassie",
"Catalina",
"Caterina",
"Catharine",
"Catherine",
"Cathrine",
"Cathryn",
"Cathy",
"Cayla",
"Ceasar",
"Cecelia",
"Cecil",
"Cecile",
"Cecilia",
"Cedrick",
"Celestine",
"Celestino",
"Celia",
"Celine",
"Cesar",
"Chad",
"Chadd",
"Chadrick",
"Chaim",
"Chance",
"Chandler",
"Chanel",
"Chanelle",
"Charity",
"Charlene",
"Charles",
"Charley",
"Charlie",
"Charlotte",
"Chase",
"Chasity",
"Chauncey",
"Chaya",
"Chaz",
"Chelsea",
"Chelsey",
"Chelsie",
"Chesley",
"Chester",
"Chet",
"Cheyanne",
"Cheyenne",
"Chloe",
"Chris",
"Christ",
"Christa",
"Christelle",
"Christian",
"Christiana",
"Christina",
"Christine",
"Christop",
"Christophe",
"Christopher",
"Christy",
"Chyna",
"Ciara",
"Cicero",
"Cielo",
"Cierra",
"Cindy",
"Citlalli",
"Clair",
"Claire",
"Clara",
"Clarabelle",
"Clare",
"Clarissa",
"Clark",
"Claud",
"Claude",
"Claudia",
"Claudie",
"Claudine",
"Clay",
"Clemens",
"Clement",
"Clementina",
"Clementine",
"Clemmie",
"Cleo",
"Cleora",
"Cleta",
"Cletus",
"Cleve",
"Cleveland",
"Clifford",
"Clifton",
"Clint",
"Clinton",
"Clotilde",
"Clovis",
"Cloyd",
"Clyde",
"Coby",
"Cody",
"Colby",
"Cole",
"Coleman",
"Colin",
"Colleen",
"Collin",
"Colt",
"Colten",
"Colton",
"Columbus",
"Concepcion",
"Conner",
"Connie",
"Connor",
"Conor",
"Conrad",
"Constance",
"Constantin",
"Consuelo",
"Cooper",
"Cora",
"Coralie",
"Corbin",
"Cordelia",
"Cordell",
"Cordia",
"Cordie",
"Corene",
"Corine",
"Cornelius",
"Cornell",
"Corrine",
"Cortez",
"Cortney",
"Cory",
"Coty",
"Courtney",
"Coy",
"Craig",
"Crawford",
"Creola",
"Cristal",
"Cristian",
"Cristina",
"Cristobal",
"Cristopher",
"Cruz",
"Crystal",
"Crystel",
"Cullen",
"Curt",
"Curtis",
"Cydney",
"Cynthia",
"Cyril",
"Cyrus",
"Dagmar",
"Dahlia",
"Daija",
"Daisha",
"Daisy",
"Dakota",
"Dale",
"Dallas",
"Dallin",
"Dalton",
"Damaris",
"Dameon",
"Damian",
"Damien",
"Damion",
"Damon",
"Dan",
"Dana",
"Dandre",
"Dane",
"D'angelo",
"Dangelo",
"Danial",
"Daniela",
"Daniella",
"Danielle",
"Danika",
"Dannie",
"Danny",
"Dante",
"Danyka",
"Daphne",
"Daphnee",
"Daphney",
"Darby",
"Daren",
"Darian",
"Dariana",
"Darien",
"Dario",
"Darion",
"Darius",
"Darlene",
"Daron",
"Darrel",
"Darrell",
"Darren",
"Darrick",
"Darrin",
"Darrion",
"Darron",
"Darryl",
"Darwin",
"Daryl",
"Dashawn",
"Dasia",
"Dave",
"David",
"Davin",
"Davion",
"Davon",
"Davonte",
"Dawn",
"Dawson",
"Dax",
"Dayana",
"Dayna",
"Dayne",
"Dayton",
"Dean",
"Deangelo",
"Deanna",
"Deborah",
"Declan",
"Dedric",
"Dedrick",
"Dee",
"Deion",
"Deja",
"Dejah",
"Dejon",
"Dejuan",
"Delaney",
"Delbert",
"Delfina",
"Delia",
"Delilah",
"Dell",
"Della",
"Delmer",
"Delores",
"Delpha",
"Delphia",
"Delphine",
"Delta",
"Demarco",
"Demarcus",
"Demario",
"Demetris",
"Demetrius",
"Demond",
"Dena",
"Denis",
"Dennis",
"Deon",
"Deondre",
"Deontae",
"Deonte",
"Dereck",
"Derek",
"Derick",
"Deron",
"Derrick",
"Deshaun",
"Deshawn",
"Desiree",
"Desmond",
"Dessie",
"Destany",
"Destin",
"Destinee",
"Destiney",
"Destini",
"Destiny",
"Devan",
"Devante",
"Deven",
"Devin",
"Devon",
"Devonte",
"Devyn",
"Dewayne",
"Dewitt",
"Dexter",
"Diamond",
"Diana",
"Dianna",
"Diego",
"Dillan",
"Dillon",
"Dimitri",
"Dina",
"Dino",
"Dion",
"Dixie",
"Dock",
"Dolly",
"Dolores",
"Domenic",
"Domenica",
"Domenick",
"Domenico",
"Domingo",
"Dominic",
"Dominique",
"Don",
"Donald",
"Donato",
"Donavon",
"Donna",
"Donnell",
"Donnie",
"Donny",
"Dora",
"Dorcas",
"Dorian",
"Doris",
"Dorothea",
"Dorothy",
"Dorris",
"Dortha",
"Dorthy",
"Doug",
"Douglas",
"Dovie",
"Doyle",
"Drake",
"Drew",
"Duane",
"Dudley",
"Dulce",
"Duncan",
"Durward",
"Dustin",
"Dusty",
"Dwight",
"Dylan",
"Earl",
"Earlene",
"Earline",
"Earnest",
"Earnestine",
"Easter",
"Easton",
"Ebba",
"Ebony",
"Ed",
"Eda",
"Edd",
"Eddie",
"Eden",
"Edgar",
"Edgardo",
"Edison",
"Edmond",
"Edmund",
"Edna",
"Eduardo",
"Edward",
"Edwardo",
"Edwin",
"Edwina",
"Edyth",
"Edythe",
"Effie",
"Efrain",
"Efren",
"Eileen",
"Einar",
"Eino",
"Eladio",
"Elaina",
"Elbert",
"Elda",
"Eldon",
"Eldora",
"Eldred",
"Eldridge",
"Eleanora",
"Eleanore",
"Eleazar",
"Electa",
"Elena",
"Elenor",
"Elenora",
"Eleonore",
"Elfrieda",
"Eli",
"Elian",
"Eliane",
"Elias",
"Eliezer",
"Elijah",
"Elinor",
"Elinore",
"Elisa",
"Elisabeth",
"Elise",
"Eliseo",
"Elisha",
"Elissa",
"Eliza",
"Elizabeth",
"Ella",
"Ellen",
"Ellie",
"Elliot",
"Elliott",
"Ellis",
"Ellsworth",
"Elmer",
"Elmira",
"Elmo",
"Elmore",
"Elna",
"Elnora",
"Elody",
"Eloisa",
"Eloise",
"Elouise",
"Eloy",
"Elroy",
"Elsa",
"Else",
"Elsie",
"Elta",
"Elton",
"Elva",
"Elvera",
"Elvie",
"Elvis",
"Elwin",
"Elwyn",
"Elyse",
"Elyssa",
"Elza",
"Emanuel",
"Emelia",
"Emelie",
"Emely",
"Emerald",
"Emerson",
"Emery",
"Emie",
"Emil",
"Emile",
"Emilia",
"Emiliano",
"Emilie",
"Emilio",
"Emily",
"Emma",
"Emmalee",
"Emmanuel",
"Emmanuelle",
"Emmet",
"Emmett",
"Emmie",
"Emmitt",
"Emmy",
"Emory",
"Ena",
"Enid",
"Enoch",
"Enola",
"Enos",
"Enrico",
"Enrique",
"Ephraim",
"Era",
"Eriberto",
"Eric",
"Erica",
"Erich",
"Erick",
"Ericka",
"Erik",
"Erika",
"Erin",
"Erling",
"Erna",
"Ernest",
"Ernestina",
"Ernestine",
"Ernesto",
"Ernie",
"Ervin",
"Erwin",
"Eryn",
"Esmeralda",
"Esperanza",
"Esta",
"Esteban",
"Estefania",
"Estel",
"Estell",
"Estella",
"Estelle",
"Estevan",
"Esther",
"Estrella",
"Etha",
"Ethan",
"Ethel",
"Ethelyn",
"Ethyl",
"Ettie",
"Eudora",
"Eugene",
"Eugenia",
"Eula",
"Eulah",
"Eulalia",
"Euna",
"Eunice",
"Eusebio",
"Eva",
"Evalyn",
"Evan",
"Evangeline",
"Evans",
"Eve",
"Eveline",
"Evelyn",
"Everardo",
"Everett",
"Everette",
"Evert",
"Evie",
"Ewald",
"Ewell",
"Ezekiel",
"Ezequiel",
"Ezra",
"Fabian",
"Fabiola",
"Fae",
"Fannie",
"Fanny",
"Fatima",
"Faustino",
"Fausto",
"Favian",
"Fay",
"Faye",
"Federico",
"Felicia",
"Felicita",
"Felicity",
"Felipa",
"Felipe",
"Felix",
"Felton",
"Fermin",
"Fern",
"Fernando",
"Ferne",
"Fidel",
"Filiberto",
"Filomena",
"Finn",
"Fiona",
"Flavie",
"Flavio",
"Fleta",
"Fletcher",
"Flo",
"Florence",
"Florencio",
"Florian",
"Florida",
"Florine",
"Flossie",
"Floy",
"Floyd",
"Ford",
"Forest",
"Forrest",
"Foster",
"Frances",
"Francesca",
"Francesco",
"Francis",
"Francisca",
"Francisco",
"Franco",
"Frank",
"Frankie",
"Franz",
"Fred",
"Freda",
"Freddie",
"Freddy",
"Frederic",
"Frederick",
"Frederik",
"Frederique",
"Fredrick",
"Fredy",
"Freeda",
"Freeman",
"Freida",
"Frida",
"Frieda",
"Friedrich",
"Fritz",
"Furman",
"Gabe",
"Gabriel",
"Gabriella",
"Gabrielle",
"Gaetano",
"Gage",
"Gail",
"Gardner",
"Garett",
"Garfield",
"Garland",
"Garnet",
"Garnett",
"Garret",
"Garrett",
"Garrick",
"Garrison",
"Garry",
"Garth",
"Gaston",
"Gavin",
"Gay",
"Gayle",
"Gaylord",
"Gene",
"General",
"Genesis",
"Genevieve",
"Gennaro",
"Genoveva",
"Geo",
"Geoffrey",
"George",
"Georgette",
"Georgiana",
"Georgianna",
"Geovanni",
"Geovanny",
"Geovany",
"Gerald",
"Geraldine",
"Gerard",
"Gerardo",
"Gerda",
"Gerhard",
"Germaine",
"German",
"Gerry",
"Gerson",
"Gertrude",
"Gia",
"Gianni",
"Gideon",
"Gilbert",
"Gilberto",
"Gilda",
"Giles",
"Gillian",
"Gina",
"Gino",
"Giovani",
"Giovanna",
"Giovanni",
"Giovanny",
"Gisselle",
"Giuseppe",
"Gladyce",
"Gladys",
"Glen",
"Glenda",
"Glenna",
"Glennie",
"Gloria",
"Godfrey",
"Golda",
"Golden",
"Gonzalo",
"Gordon",
"Grace",
"Gracie",
"Graciela",
"Grady",
"Graham",
"Grant",
"Granville",
"Grayce",
"Grayson",
"Green",
"Greg",
"Gregg",
"Gregoria",
"Gregorio",
"Gregory",
"Greta",
"Gretchen",
"Greyson",
"Griffin",
"Grover",
"Guadalupe",
"Gudrun",
"Guido",
"Guillermo",
"Guiseppe",
"Gunnar",
"Gunner",
"Gus",
"Gussie",
"Gust",
"Gustave",
"Guy",
"Gwen",
"Gwendolyn",
"Hadley",
"Hailee",
"Hailey",
"Hailie",
"Hal",
"Haleigh",
"Haley",
"Halie",
"Halle",
"Hallie",
"Hank",
"Hanna",
"Hannah",
"Hans",
"Hardy",
"Harley",
"Harmon",
"Harmony",
"Harold",
"Harrison",
"Harry",
"Harvey",
"Haskell",
"Hassan",
"Hassie",
"Hattie",
"Haven",
"Hayden",
"Haylee",
"Hayley",
"Haylie",
"Hazel",
"Hazle",
"Heath",
"Heather",
"Heaven",
"Heber",
"Hector",
"Heidi",
"Helen",
"Helena",
"Helene",
"Helga",
"Hellen",
"Helmer",
"Heloise",
"Henderson",
"Henri",
"Henriette",
"Henry",
"Herbert",
"Herman",
"Hermann",
"Hermina",
"Herminia",
"Herminio",
"Hershel",
"Herta",
"Hertha",
"Hester",
"Hettie",
"Hilario",
"Hilbert",
"Hilda",
"Hildegard",
"Hillard",
"Hillary",
"Hilma",
"Hilton",
"Hipolito",
"Hiram",
"Hobart",
"Holden",
"Hollie",
"Hollis",
"Holly",
"Hope",
"Horace",
"Horacio",
"Hortense",
"Hosea",
"Houston",
"Howard",
"Howell",
"Hoyt",
"Hubert",
"Hudson",
"Hugh",
"Hulda",
"Humberto",
"Hunter",
"Hyman",
"Ian",
"Ibrahim",
"Icie",
"Ida",
"Idell",
"Idella",
"Ignacio",
"Ignatius",
"Ike",
"Ila",
"Ilene",
"Iliana",
"Ima",
"Imani",
"Imelda",
"Immanuel",
"Imogene",
"Ines",
"Irma",
"Irving",
"Irwin",
"Isaac",
"Isabel",
"Isabell",
"Isabella",
"Isabelle",
"Isac",
"Isadore",
"Isai",
"Isaiah",
"Isaias",
"Isidro",
"Ismael",
"Isobel",
"Isom",
"Israel",
"Issac",
"Itzel",
"Iva",
"Ivah",
"Ivory",
"Ivy",
"Izabella",
"Izaiah",
"Jabari",
"Jace",
"Jacey",
"Jacinthe",
"Jacinto",
"Jack",
"Jackeline",
"Jackie",
"Jacklyn",
"Jackson",
"Jacky",
"Jaclyn",
"Jacquelyn",
"Jacques",
"Jacynthe",
"Jada",
"Jade",
"Jaden",
"Jadon",
"Jadyn",
"Jaeden",
"Jaida",
"Jaiden",
"Jailyn",
"Jaime",
"Jairo",
"Jakayla",
"Jake",
"Jakob",
"Jaleel",
"Jalen",
"Jalon",
"Jalyn",
"Jamaal",
"Jamal",
"Jamar",
"Jamarcus",
"Jamel",
"Jameson",
"Jamey",
"Jamie",
"Jamil",
"Jamir",
"Jamison",
"Jammie",
"Jan",
"Jana",
"Janae",
"Jane",
"Janelle",
"Janessa",
"Janet",
"Janice",
"Janick",
"Janie",
"Janis",
"Janiya",
"Jannie",
"Jany",
"Jaquan",
"Jaquelin",
"Jaqueline",
"Jared",
"Jaren",
"Jarod",
"Jaron",
"Jarred",
"Jarrell",
"Jarret",
"Jarrett",
"Jarrod",
"Jarvis",
"Jasen",
"Jasmin",
"Jason",
"Jasper",
"Jaunita",
"Javier",
"Javon",
"Javonte",
"Jay",
"Jayce",
"Jaycee",
"Jayda",
"Jayde",
"Jayden",
"Jaydon",
"Jaylan",
"Jaylen",
"Jaylin",
"Jaylon",
"Jayme",
"Jayne",
"Jayson",
"Jazlyn",
"Jazmin",
"Jazmyn",
"Jazmyne",
"Jean",
"Jeanette",
"Jeanie",
"Jeanne",
"Jed",
"Jedediah",
"Jedidiah",
"Jeff",
"Jefferey",
"Jeffery",
"Jeffrey",
"Jeffry",
"Jena",
"Jenifer",
"Jennie",
"Jennifer",
"Jennings",
"Jennyfer",
"Jensen",
"Jerad",
"Jerald",
"Jeramie",
"Jeramy",
"Jerel",
"Jeremie",
"Jeremy",
"Jermain",
"Jermaine",
"Jermey",
"Jerod",
"Jerome",
"Jeromy",
"Jerrell",
"Jerrod",
"Jerrold",
"Jerry",
"Jess",
"Jesse",
"Jessica",
"Jessie",
"Jessika",
"Jessy",
"Jessyca",
"Jesus",
"Jett",
"Jettie",
"Jevon",
"Jewel",
"Jewell",
"Jillian",
"Jimmie",
"Jimmy",
"Jo",
"Joan",
"Joana",
"Joanie",
"Joanne",
"Joannie",
"Joanny",
"Joany",
"Joaquin",
"Jocelyn",
"Jodie",
"Jody",
"Joe",
"Joel",
"Joelle",
"Joesph",
"Joey",
"Johan",
"Johann",
"Johanna",
"Johathan",
"John",
"Johnathan",
"Johnathon",
"Johnnie",
"Johnny",
"Johnpaul",
"Johnson",
"Jolie",
"Jon",
"Jonas",
"Jonatan",
"Jonathan",
"Jonathon",
"Jordan",
"Jordane",
"Jordi",
"Jordon",
"Jordy",
"Jordyn",
"Jorge",
"Jose",
"Josefa",
"Josefina",
"Joseph",
"Josephine",
"Josh",
"Joshua",
"Joshuah",
"Josiah",
"Josiane",
"Josianne",
"Josie",
"Josue",
"Jovan",
"Jovani",
"Jovanny",
"Jovany",
"Joy",
"Joyce",
"Juana",
"Juanita",
"Judah",
"Judd",
"Jude",
"Judge",
"Judson",
"Judy",
"Jules",
"Julia",
"Julian",
"Juliana",
"Julianne",
"Julie",
"Julien",
"Juliet",
"Julio",
"Julius",
"June",
"Junior",
"Junius",
"Justen",
"Justice",
"Justina",
"Justine",
"Juston",
"Justus",
"Justyn",
"Juvenal",
"Juwan",
"Kacey",
"Kaci",
"Kacie",
"Kade",
"Kaden",
"Kadin",
"Kaela",
"Kaelyn",
"Kaia",
"Kailee",
"Kailey",
"Kailyn",
"Kaitlin",
"Kaitlyn",
"Kale",
"Kaleb",
"Kaleigh",
"Kaley",
"Kali",
"Kallie",
"Kameron",
"Kamille",
"Kamren",
"Kamron",
"Kamryn",
"Kane",
"Kara",
"Kareem",
"Karelle",
"Karen",
"Kari",
"Kariane",
"Karianne",
"Karina",
"Karine",
"Karl",
"Karlee",
"Karley",
"Karli",
"Karlie",
"Karolann",
"Karson",
"Kasandra",
"Kasey",
"Kassandra",
"Katarina",
"Katelin",
"Katelyn",
"Katelynn",
"Katharina",
"Katherine",
"Katheryn",
"Kathleen",
"Kathlyn",
"Kathryn",
"Kathryne",
"Katlyn",
"Katlynn",
"Katrina",
"Katrine",
"Kattie",
"Kavon",
"Kay",
"Kaya",
"Kaycee",
"Kayden",
"Kayla",
"Kaylah",
"Kaylee",
"Kayleigh",
"Kayley",
"Kayli",
"Kaylie",
"Kaylin",
"Keagan",
"Keanu",
"Keara",
"Keaton",
"Keegan",
"Keeley",
"Keely",
"Keenan",
"Keira",
"Keith",
"Kellen",
"Kelley",
"Kelli",
"Kellie",
"Kelly",
"Kelsi",
"Kelsie",
"Kelton",
"Kelvin",
"Ken",
"Kendall",
"Kendra",
"Kendrick",
"Kenna",
"Kennedi",
"Kennedy",
"Kenneth",
"Kennith",
"Kenny",
"Kenton",
"Kenya",
"Kenyatta",
"Kenyon",
"Keon",
"Keshaun",
"Keshawn",
"Keven",
"Kevin",
"Kevon",
"Keyon",
"Keyshawn",
"Khalid",
"Khalil",
"Kian",
"Kiana",
"Kianna",
"Kiara",
"Kiarra",
"Kiel",
"Kiera",
"Kieran",
"Kiley",
"Kim",
"Kimberly",
"King",
"Kip",
"Kira",
"Kirk",
"Kirsten",
"Kirstin",
"Kitty",
"Kobe",
"Koby",
"Kody",
"Kolby",
"Kole",
"Korbin",
"Korey",
"Kory",
"Kraig",
"Kris",
"Krista",
"Kristian",
"Kristin",
"Kristina",
"Kristofer",
"Kristoffer",
"Kristopher",
"Kristy",
"Krystal",
"Krystel",
"Krystina",
"Kurt",
"Kurtis",
"Kyla",
"Kyle",
"Kylee",
"Kyleigh",
"Kyler",
"Kylie",
"Kyra",
"Lacey",
"Lacy",
"Ladarius",
"Lafayette",
"Laila",
"Laisha",
"Lamar",
"Lambert",
"Lamont",
"Lance",
"Landen",
"Lane",
"Laney",
"Larissa",
"Laron",
"Larry",
"Larue",
"Laura",
"Laurel",
"Lauren",
"Laurence",
"Lauretta",
"Lauriane",
"Laurianne",
"Laurie",
"Laurine",
"Laury",
"Lauryn",
"Lavada",
"Lavern",
"Laverna",
"Laverne",
"Lavina",
"Lavinia",
"Lavon",
"Lavonne",
"Lawrence",
"Lawson",
"Layla",
"Layne",
"Lazaro",
"Lea",
"Leann",
"Leanna",
"Leanne",
"Leatha",
"Leda",
"Lee",
"Leif",
"Leila",
"Leilani",
"Lela",
"Lelah",
"Leland",
"Lelia",
"Lempi",
"Lemuel",
"Lenna",
"Lennie",
"Lenny",
"Lenora",
"Lenore",
"Leo",
"Leola",
"Leon",
"Leonard",
"Leonardo",
"Leone",
"Leonel",
"Leonie",
"Leonor",
"Leonora",
"Leopold",
"Leopoldo",
"Leora",
"Lera",
"Lesley",
"Leslie",
"Lesly",
"Lessie",
"Lester",
"Leta",
"Letha",
"Letitia",
"Levi",
"Lew",
"Lewis",
"Lexi",
"Lexie",
"Lexus",
"Lia",
"Liam",
"Liana",
"Libbie",
"Libby",
"Lila",
"Lilian",
"Liliana",
"Liliane",
"Lilla",
"Lillian",
"Lilliana",
"Lillie",
"Lilly",
"Lily",
"Lilyan",
"Lina",
"Lincoln",
"Linda",
"Lindsay",
"Lindsey",
"Linnea",
"Linnie",
"Linwood",
"Lionel",
"Lisa",
"Lisandro",
"Lisette",
"Litzy",
"Liza",
"Lizeth",
"Lizzie",
"Llewellyn",
"Lloyd",
"Logan",
"Lois",
"Lola",
"Lolita",
"Loma",
"Lon",
"London",
"Lonie",
"Lonnie",
"Lonny",
"Lonzo",
"Lora",
"Loraine",
"Loren",
"Lorena",
"Lorenz",
"Lorenza",
"Lorenzo",
"Lori",
"Lorine",
"Lorna",
"Lottie",
"Lou",
"Louie",
"Louisa",
"Lourdes",
"Louvenia",
"Lowell",
"Loy",
"Loyal",
"Loyce",
"Lucas",
"Luciano",
"Lucie",
"Lucienne",
"Lucile",
"Lucinda",
"Lucio",
"Lucious",
"Lucius",
"Lucy",
"Ludie",
"Ludwig",
"Lue",
"Luella",
"Luigi",
"Luis",
"Luisa",
"Lukas",
"Lula",
"Lulu",
"Luna",
"Lupe",
"Lura",
"Lurline",
"Luther",
"Luz",
"Lyda",
"Lydia",
"Lyla",
"Lynn",
"Lyric",
"Lysanne",
"Mabel",
"Mabelle",
"Mable",
"Mac",
"Macey",
"Maci",
"Macie",
"Mack",
"Mackenzie",
"Macy",
"Madaline",
"Madalyn",
"Maddison",
"Madeline",
"Madelyn",
"Madelynn",
"Madge",
"Madie",
"Madilyn",
"Madisen",
"Madison",
"Madisyn",
"Madonna",
"Madyson",
"Mae",
"Maegan",
"Maeve",
"Mafalda",
"Magali",
"Magdalen",
"Magdalena",
"Maggie",
"Magnolia",
"Magnus",
"Maia",
"Maida",
"Maiya",
"Major",
"Makayla",
"Makenna",
"Makenzie",
"Malachi",
"Malcolm",
"Malika",
"Malinda",
"Mallie",
"Mallory",
"Malvina",
"Mandy",
"Manley",
"Manuel",
"Manuela",
"Mara",
"Marc",
"Marcel",
"Marcelina",
"Marcelino",
"Marcella",
"Marcelle",
"Marcellus",
"Marcelo",
"Marcia",
"Marco",
"Marcos",
"Marcus",
"Margaret",
"Margarete",
"Margarett",
"Margaretta",
"Margarette",
"Margarita",
"Marge",
"Margie",
"Margot",
"Margret",
"Marguerite",
"Maria",
"Mariah",
"Mariam",
"Marian",
"Mariana",
"Mariane",
"Marianna",
"Marianne",
"Mariano",
"Maribel",
"Marie",
"Mariela",
"Marielle",
"Marietta",
"Marilie",
"Marilou",
"Marilyne",
"Marina",
"Mario",
"Marion",
"Marisa",
"Marisol",
"Maritza",
"Marjolaine",
"Marjorie",
"Marjory",
"Mark",
"Markus",
"Marlee",
"Marlen",
"Marlene",
"Marley",
"Marlin",
"Marlon",
"Marques",
"Marquis",
"Marquise",
"Marshall",
"Marta",
"Martin",
"Martina",
"Martine",
"Marty",
"Marvin",
"Mary",
"Maryam",
"Maryjane",
"Maryse",
"Mason",
"Mateo",
"Mathew",
"Mathias",
"Mathilde",
"Matilda",
"Matilde",
"Matt",
"Matteo",
"Mattie",
"Maud",
"Maude",
"Maudie",
"Maureen",
"Maurice",
"Mauricio",
"Maurine",
"Maverick",
"Mavis",
"Max",
"Maxie",
"Maxime",
"Maximilian",
"Maximillia",
"Maximillian",
"Maximo",
"Maximus",
"Maxine",
"Maxwell",
"May",
"Maya",
"Maybell",
"Maybelle",
"Maye",
"Maymie",
"Maynard",
"Mayra",
"Mazie",
"Mckayla",
"Mckenna",
"Mckenzie",
"Meagan",
"Meaghan",
"Meda",
"Megane",
"Meggie",
"Meghan",
"Mekhi",
"Melany",
"Melba",
"Melisa",
"Melissa",
"Mellie",
"Melody",
"Melvin",
"Melvina",
"Melyna",
"Melyssa",
"Mercedes",
"Meredith",
"Merl",
"Merle",
"Merlin",
"Merritt",
"Mertie",
"Mervin",
"Meta",
"Mia",
"Micaela",
"Micah",
"Michael",
"Michaela",
"Michale",
"Micheal",
"Michel",
"Michele",
"Michelle",
"Miguel",
"Mikayla",
"Mike",
"Mikel",
"Milan",
"Miles",
"Milford",
"Miller",
"Millie",
"Milo",
"Milton",
"Mina",
"Minerva",
"Minnie",
"Miracle",
"Mireille",
"Mireya",
"Misael",
"Missouri",
"Misty",
"Mitchel",
"Mitchell",
"Mittie",
"Modesta",
"Modesto",
"Mohamed",
"Mohammad",
"Mohammed",
"Moises",
"Mollie",
"Molly",
"Mona",
"Monica",
"Monique",
"Monroe",
"Monserrat",
"Monserrate",
"Montana",
"Monte",
"Monty",
"Morgan",
"Moriah",
"Morris",
"Mortimer",
"Morton",
"Mose",
"Moses",
"Moshe",
"Mossie",
"Mozell",
"Mozelle",
"Muhammad",
"Muriel",
"Murl",
"Murphy",
"Murray",
"Mustafa",
"Mya",
"Myah",
"Mylene",
"Myles",
"Myra",
"Myriam",
"Myrl",
"Myrna",
"Myron",
"Myrtice",
"Myrtie",
"Myrtis",
"Myrtle",
"Nadia",
"Nakia",
"Name",
"Nannie",
"Naomi",
"Naomie",
"Napoleon",
"Narciso",
"Nash",
"Nasir",
"Nat",
"Natalia",
"Natalie",
"Natasha",
"Nathan",
"Nathanael",
"Nathanial",
"Nathaniel",
"Nathen",
"Nayeli",
"Neal",
"Ned",
"Nedra",
"Neha",
"Neil",
"Nelda",
"Nella",
"Nelle",
"Nellie",
"Nels",
"Nelson",
"Neoma",
"Nestor",
"Nettie",
"Neva",
"Newell",
"Newton",
"Nia",
"Nicholas",
"Nicholaus",
"Nichole",
"Nick",
"Nicklaus",
"Nickolas",
"Nico",
"Nicola",
"Nicolas",
"Nicole",
"Nicolette",
"Nigel",
"Nikita",
"Nikki",
"Nikko",
"Niko",
"Nikolas",
"Nils",
"Nina",
"Noah",
"Noble",
"Noe",
"Noel",
"Noelia",
"Noemi",
"Noemie",
"Noemy",
"Nola",
"Nolan",
"Nona",
"Nora",
"Norbert",
"Norberto",
"Norene",
"Norma",
"Norris",
"Norval",
"Norwood",
"Nova",
"Novella",
"Nya",
"Nyah",
"Nyasia",
"Obie",
"Oceane",
"Ocie",
"Octavia",
"Oda",
"Odell",
"Odessa",
"Odie",
"Ofelia",
"Okey",
"Ola",
"Olaf",
"Ole",
"Olen",
"Oleta",
"Olga",
"Olin",
"Oliver",
"Ollie",
"Oma",
"Omari",
"Omer",
"Ona",
"Onie",
"Opal",
"Ophelia",
"Ora",
"Oral",
"Oran",
"Oren",
"Orie",
"Orin",
"Orion",
"Orland",
"Orlando",
"Orlo",
"Orpha",
"Orrin",
"Orval",
"Orville",
"Osbaldo",
"Osborne",
"Oscar",
"Osvaldo",
"Oswald",
"Oswaldo",
"Otha",
"Otho",
"Otilia",
"Otis",
"Ottilie",
"Ottis",
"Otto",
"Ova",
"Owen",
"Ozella",
"Pablo",
"Paige",
"Palma",
"Pamela",
"Pansy",
"Paolo",
"Paris",
"Parker",
"Pascale",
"Pasquale",
"Pat",
"Patience",
"Patricia",
"Patrick",
"Patsy",
"Pattie",
"Paul",
"Paula",
"Pauline",
"Paxton",
"Payton",
"Pearl",
"Pearlie",
"Pearline",
"Pedro",
"Peggie",
"Penelope",
"Percival",
"Percy",
"Perry",
"Pete",
"Peter",
"Petra",
"Peyton",
"Philip",
"Phoebe",
"Phyllis",
"Pierce",
"Pierre",
"Pietro",
"Pink",
"Pinkie",
"Piper",
"Polly",
"Porter",
"Precious",
"Presley",
"Preston",
"Price",
"Prince",
"Princess",
"Priscilla",
"Providenci",
"Prudence",
"Queen",
"Queenie",
"Quentin",
"Quincy",
"Quinn",
"Quinten",
"Quinton",
"Rachael",
"Rachel",
"Rachelle",
"Rae",
"Raegan",
"Rafael",
"Rafaela",
"Raheem",
"Rahsaan",
"Rahul",
"Raina",
"Raleigh",
"Ralph",
"Ramiro",
"Ramon",
"Ramona",
"Randal",
"Randall",
"Randi",
"Randy",
"Ransom",
"Raoul",
"Raphael",
"Raphaelle",
"Raquel",
"Rashad",
"Rashawn",
"Rasheed",
"Raul",
"Raven",
"Ray",
"Raymond",
"Raymundo",
"Reagan",
"Reanna",
"Reba",
"Rebeca",
"Rebecca",
"Rebeka",
"Rebekah",
"Reece",
"Reed",
"Reese",
"Regan",
"Reggie",
"Reginald",
"Reid",
"Reilly",
"Reina",
"Reinhold",
"Remington",
"Rene",
"Renee",
"Ressie",
"Reta",
"Retha",
"Retta",
"Reuben",
"Reva",
"Rex",
"Rey",
"Reyes",
"Reymundo",
"Reyna",
"Reynold",
"Rhea",
"Rhett",
"Rhianna",
"Rhiannon",
"Rhoda",
"Ricardo",
"Richard",
"Richie",
"Richmond",
"Rick",
"Rickey",
"Rickie",
"Ricky",
"Rico",
"Rigoberto",
"Riley",
"Rita",
"River",
"Robb",
"Robbie",
"Robert",
"Roberta",
"Roberto",
"Robin",
"Robyn",
"Rocio",
"Rocky",
"Rod",
"Roderick",
"Rodger",
"Rodolfo",
"Rodrick",
"Rodrigo",
"Roel",
"Rogelio",
"Roger",
"Rogers",
"Rolando",
"Rollin",
"Roma",
"Romaine",
"Roman",
"Ron",
"Ronaldo",
"Ronny",
"Roosevelt",
"Rory",
"Rosa",
"Rosalee",
"Rosalia",
"Rosalind",
"Rosalinda",
"Rosalyn",
"Rosamond",
"Rosanna",
"Rosario",
"Roscoe",
"Rose",
"Rosella",
"Roselyn",
"Rosemarie",
"Rosemary",
"Rosendo",
"Rosetta",
"Rosie",
"Rosina",
"Roslyn",
"Ross",
"Rossie",
"Rowan",
"Rowena",
"Rowland",
"Roxane",
"Roxanne",
"Roy",
"Royal",
"Royce",
"Rozella",
"Ruben",
"Rubie",
"Ruby",
"Rubye",
"Rudolph",
"Rudy",
"Rupert",
"Russ",
"Russel",
"Russell",
"Rusty",
"Ruth",
"Ruthe",
"Ruthie",
"Ryan",
"Ryann",
"Ryder",
"Rylan",
"Rylee",
"Ryleigh",
"Ryley",
"Sabina",
"Sabrina",
"Sabryna",
"Sadie",
"Sadye",
"Sage",
"Saige",
"Sallie",
"Sally",
"Salma",
"Salvador",
"Salvatore",
"Sam",
"Samanta",
"Samantha",
"Samara",
"Samir",
"Sammie",
"Sammy",
"Samson",
"Sandra",
"Sandrine",
"Sandy",
"Sanford",
"Santa",
"Santiago",
"Santina",
"Santino",
"Santos",
"Sarah",
"Sarai",
"Sarina",
"Sasha",
"Saul",
"Savanah",
"Savanna",
"Savannah",
"Savion",
"Scarlett",
"Schuyler",
"Scot",
"Scottie",
"Scotty",
"Seamus",
"Sean",
"Sebastian",
"Sedrick",
"Selena",
"Selina",
"Selmer",
"Serena",
"Serenity",
"Seth",
"Shad",
"Shaina",
"Shakira",
"Shana",
"Shane",
"Shanel",
"Shanelle",
"Shania",
"Shanie",
"Shaniya",
"Shanna",
"Shannon",
"Shanny",
"Shanon",
"Shany",
"Sharon",
"Shaun",
"Shawn",
"Shawna",
"Shaylee",
"Shayna",
"Shayne",
"Shea",
"Sheila",
"Sheldon",
"Shemar",
"Sheridan",
"Sherman",
"Sherwood",
"Shirley",
"Shyann",
"Shyanne",
"Sibyl",
"Sid",
"Sidney",
"Sienna",
"Sierra",
"Sigmund",
"Sigrid",
"Sigurd",
"Silas",
"Sim",
"Simeon",
"Simone",
"Sincere",
"Sister",
"Skye",
"Skyla",
"Skylar",
"Sofia",
"Soledad",
"Solon",
"Sonia",
"Sonny",
"Sonya",
"Sophia",
"Sophie",
"Spencer",
"Stacey",
"Stacy",
"Stan",
"Stanford",
"Stanley",
"Stanton",
"Stefan",
"Stefanie",
"Stella",
"Stephan",
"Stephania",
"Stephanie",
"Stephany",
"Stephen",
"Stephon",
"Sterling",
"Steve",
"Stevie",
"Stewart",
"Stone",
"Stuart",
"Summer",
"Sunny",
"Susan",
"Susana",
"Susanna",
"Susie",
"Suzanne",
"Sven",
"Syble",
"Sydnee",
"Sydney",
"Sydni",
"Sydnie",
"Sylvan",
"Sylvester",
"Sylvia",
"Tabitha",
"Tad",
"Talia",
"Talon",
"Tamara",
"Tamia",
"Tania",
"Tanner",
"Tanya",
"Tara",
"Taryn",
"Tate",
"Tatum",
"Tatyana",
"Taurean",
"Tavares",
"Taya",
"Taylor",
"Teagan",
"Ted",
"Telly",
"Terence",
"Teresa",
"Terrance",
"Terrell",
"Terrence",
"Terrill",
"Terry",
"Tess",
"Tessie",
"Tevin",
"Thad",
"Thaddeus",
"Thalia",
"Thea",
"Thelma",
"Theo",
"Theodora",
"Theodore",
"Theresa",
"Therese",
"Theresia",
"Theron",
"Thomas",
"Thora",
"Thurman",
"Tia",
"Tiana",
"Tianna",
"Tiara",
"Tierra",
"Tiffany",
"Tillman",
"Timmothy",
"Timmy",
"Timothy",
"Tina",
"Tito",
"Titus",
"Tobin",
"Toby",
"Tod",
"Tom",
"Tomas",
"Tomasa",
"Tommie",
"Toney",
"Toni",
"Tony",
"Torey",
"Torrance",
"Torrey",
"Toy",
"Trace",
"Tracey",
"Tracy",
"Travis",
"Travon",
"Tre",
"Tremaine",
"Tremayne",
"Trent",
"Trenton",
"Tressa",
"Tressie",
"Treva",
"Trever",
"Trevion",
"Trevor",
"Trey",
"Trinity",
"Trisha",
"Tristian",
"Tristin",
"Triston",
"Troy",
"Trudie",
"Trycia",
"Trystan",
"Turner",
"Twila",
"Tyler",
"Tyra",
"Tyree",
"Tyreek",
"Tyrel",
"Tyrell",
"Tyrese",
"Tyrique",
"Tyshawn",
"Tyson",
"Ubaldo",
"Ulices",
"Ulises",
"Una",
"Unique",
"Urban",
"Uriah",
"Uriel",
"Ursula",
"Vada",
"Valentin",
"Valentina",
"Valentine",
"Valerie",
"Vallie",
"Van",
"Vance",
"Vanessa",
"Vaughn",
"Veda",
"Velda",
"Vella",
"Velma",
"Velva",
"Vena",
"Verda",
"Verdie",
"Vergie",
"Verla",
"Verlie",
"Vern",
"Verna",
"Verner",
"Vernice",
"Vernie",
"Vernon",
"Verona",
"Veronica",
"Vesta",
"Vicenta",
"Vicente",
"Vickie",
"Vicky",
"Victor",
"Victoria",
"Vida",
"Vidal",
"Vilma",
"Vince",
"Vincent",
"Vincenza",
"Vincenzo",
"Vinnie",
"Viola",
"Violet",
"Violette",
"Virgie",
"Virgil",
"Virginia",
"Virginie",
"Vita",
"Vito",
"Viva",
"Vivian",
"Viviane",
"Vivianne",
"Vivien",
"Vivienne",
"Vladimir",
"Wade",
"Waino",
"Waldo",
"Walker",
"Wallace",
"Walter",
"Walton",
"Wanda",
"Ward",
"Warren",
"Watson",
"Wava",
"Waylon",
"Wayne",
"Webster",
"Weldon",
"Wellington",
"Wendell",
"Wendy",
"Werner",
"Westley",
"Weston",
"Whitney",
"Wilber",
"Wilbert",
"Wilburn",
"Wiley",
"Wilford",
"Wilfred",
"Wilfredo",
"Wilfrid",
"Wilhelm",
"Wilhelmine",
"Will",
"Willa",
"Willard",
"William",
"Willie",
"Willis",
"Willow",
"Willy",
"Wilma",
"Wilmer",
"Wilson",
"Wilton",
"Winfield",
"Winifred",
"Winnifred",
"Winona",
"Winston",
"Woodrow",
"Wyatt",
"Wyman",
"Xander",
"Xavier",
"Xzavier",
"Yadira",
"Yasmeen",
"Yasmin",
"Yasmine",
"Yazmin",
"Yesenia",
"Yessenia",
"Yolanda",
"Yoshiko",
"Yvette",
"Yvonne",
"Zachariah",
"Zachary",
"Zachery",
"Zack",
"Zackary",
"Zackery",
"Zakary",
"Zander",
"Zane",
"Zaria",
"Zechariah",
"Zelda",
"Zella",
"Zelma",
"Zena",
"Zetta",
"Zion",
"Zita",
"Zoe",
"Zoey",
"Zoie",
"Zoila",
"Zola",
"Zora",
"Zula"
];
},{}],123:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.prefix = require("./prefix");
name.suffix = require("./suffix");
name.title = require("./title");
name.name = require("./name");
},{"./first_name":122,"./last_name":124,"./name":125,"./prefix":126,"./suffix":127,"./title":128}],124:[function(require,module,exports){
module["exports"] = [
"Abbott",
"Abernathy",
"Abshire",
"Adams",
"Altenwerth",
"Anderson",
"Ankunding",
"Armstrong",
"Auer",
"Aufderhar",
"Bahringer",
"Bailey",
"Balistreri",
"Barrows",
"Bartell",
"Bartoletti",
"Barton",
"Bashirian",
"Batz",
"Bauch",
"Baumbach",
"Bayer",
"Beahan",
"Beatty",
"Bechtelar",
"Becker",
"Bednar",
"Beer",
"Beier",
"Berge",
"Bergnaum",
"Bergstrom",
"Bernhard",
"Bernier",
"Bins",
"Blanda",
"Blick",
"Block",
"Bode",
"Boehm",
"Bogan",
"Bogisich",
"Borer",
"Bosco",
"Botsford",
"Boyer",
"Boyle",
"Bradtke",
"Brakus",
"Braun",
"Breitenberg",
"Brekke",
"Brown",
"Bruen",
"Buckridge",
"Carroll",
"Carter",
"Cartwright",
"Casper",
"Cassin",
"Champlin",
"Christiansen",
"Cole",
"Collier",
"Collins",
"Conn",
"Connelly",
"Conroy",
"Considine",
"Corkery",
"Cormier",
"Corwin",
"Cremin",
"Crist",
"Crona",
"Cronin",
"Crooks",
"Cruickshank",
"Cummerata",
"Cummings",
"Dach",
"D'Amore",
"Daniel",
"Dare",
"Daugherty",
"Davis",
"Deckow",
"Denesik",
"Dibbert",
"Dickens",
"Dicki",
"Dickinson",
"Dietrich",
"Donnelly",
"Dooley",
"Douglas",
"Doyle",
"DuBuque",
"Durgan",
"Ebert",
"Effertz",
"Eichmann",
"Emard",
"Emmerich",
"Erdman",
"Ernser",
"Fadel",
"Fahey",
"Farrell",
"Fay",
"Feeney",
"Feest",
"Feil",
"Ferry",
"Fisher",
"Flatley",
"Frami",
"Franecki",
"Friesen",
"Fritsch",
"Funk",
"Gaylord",
"Gerhold",
"Gerlach",
"Gibson",
"Gislason",
"Gleason",
"Gleichner",
"Glover",
"Goldner",
"Goodwin",
"Gorczany",
"Gottlieb",
"Goyette",
"Grady",
"Graham",
"Grant",
"Green",
"Greenfelder",
"Greenholt",
"Grimes",
"Gulgowski",
"Gusikowski",
"Gutkowski",
"Gutmann",
"Haag",
"Hackett",
"Hagenes",
"Hahn",
"Haley",
"Halvorson",
"Hamill",
"Hammes",
"Hand",
"Hane",
"Hansen",
"Harber",
"Harris",
"Hartmann",
"Harvey",
"Hauck",
"Hayes",
"Heaney",
"Heathcote",
"Hegmann",
"Heidenreich",
"Heller",
"Herman",
"Hermann",
"Hermiston",
"Herzog",
"Hessel",
"Hettinger",
"Hickle",
"Hilll",
"Hills",
"Hilpert",
"Hintz",
"Hirthe",
"Hodkiewicz",
"Hoeger",
"Homenick",
"Hoppe",
"Howe",
"Howell",
"Hudson",
"Huel",
"Huels",
"Hyatt",
"Jacobi",
"Jacobs",
"Jacobson",
"Jakubowski",
"Jaskolski",
"Jast",
"Jenkins",
"Jerde",
"Johns",
"Johnson",
"Johnston",
"Jones",
"Kassulke",
"Kautzer",
"Keebler",
"Keeling",
"Kemmer",
"Kerluke",
"Kertzmann",
"Kessler",
"Kiehn",
"Kihn",
"Kilback",
"King",
"Kirlin",
"Klein",
"Kling",
"Klocko",
"Koch",
"Koelpin",
"Koepp",
"Kohler",
"Konopelski",
"Koss",
"Kovacek",
"Kozey",
"Krajcik",
"Kreiger",
"Kris",
"Kshlerin",
"Kub",
"Kuhic",
"Kuhlman",
"Kuhn",
"Kulas",
"Kunde",
"Kunze",
"Kuphal",
"Kutch",
"Kuvalis",
"Labadie",
"Lakin",
"Lang",
"Langosh",
"Langworth",
"Larkin",
"Larson",
"Leannon",
"Lebsack",
"Ledner",
"Leffler",
"Legros",
"Lehner",
"Lemke",
"Lesch",
"Leuschke",
"Lind",
"Lindgren",
"Littel",
"Little",
"Lockman",
"Lowe",
"Lubowitz",
"Lueilwitz",
"Luettgen",
"Lynch",
"Macejkovic",
"MacGyver",
"Maggio",
"Mann",
"Mante",
"Marks",
"Marquardt",
"Marvin",
"Mayer",
"Mayert",
"McClure",
"McCullough",
"McDermott",
"McGlynn",
"McKenzie",
"McLaughlin",
"Medhurst",
"Mertz",
"Metz",
"Miller",
"Mills",
"Mitchell",
"Moen",
"Mohr",
"Monahan",
"Moore",
"Morar",
"Morissette",
"Mosciski",
"Mraz",
"Mueller",
"Muller",
"Murazik",
"Murphy",
"Murray",
"Nader",
"Nicolas",
"Nienow",
"Nikolaus",
"Nitzsche",
"Nolan",
"Oberbrunner",
"O'Connell",
"O'Conner",
"O'Hara",
"O'Keefe",
"O'Kon",
"Okuneva",
"Olson",
"Ondricka",
"O'Reilly",
"Orn",
"Ortiz",
"Osinski",
"Pacocha",
"Padberg",
"Pagac",
"Parisian",
"Parker",
"Paucek",
"Pfannerstill",
"Pfeffer",
"Pollich",
"Pouros",
"Powlowski",
"Predovic",
"Price",
"Prohaska",
"Prosacco",
"Purdy",
"Quigley",
"Quitzon",
"Rath",
"Ratke",
"Rau",
"Raynor",
"Reichel",
"Reichert",
"Reilly",
"Reinger",
"Rempel",
"Renner",
"Reynolds",
"Rice",
"Rippin",
"Ritchie",
"Robel",
"Roberts",
"Rodriguez",
"Rogahn",
"Rohan",
"Rolfson",
"Romaguera",
"Roob",
"Rosenbaum",
"Rowe",
"Ruecker",
"Runolfsdottir",
"Runolfsson",
"Runte",
"Russel",
"Rutherford",
"Ryan",
"Sanford",
"Satterfield",
"Sauer",
"Sawayn",
"Schaden",
"Schaefer",
"Schamberger",
"Schiller",
"Schimmel",
"Schinner",
"Schmeler",
"Schmidt",
"Schmitt",
"Schneider",
"Schoen",
"Schowalter",
"Schroeder",
"Schulist",
"Schultz",
"Schumm",
"Schuppe",
"Schuster",
"Senger",
"Shanahan",
"Shields",
"Simonis",
"Sipes",
"Skiles",
"Smith",
"Smitham",
"Spencer",
"Spinka",
"Sporer",
"Stamm",
"Stanton",
"Stark",
"Stehr",
"Steuber",
"Stiedemann",
"Stokes",
"Stoltenberg",
"Stracke",
"Streich",
"Stroman",
"Strosin",
"Swaniawski",
"Swift",
"Terry",
"Thiel",
"Thompson",
"Tillman",
"Torp",
"Torphy",
"Towne",
"Toy",
"Trantow",
"Tremblay",
"Treutel",
"Tromp",
"Turcotte",
"Turner",
"Ullrich",
"Upton",
"Vandervort",
"Veum",
"Volkman",
"Von",
"VonRueden",
"Waelchi",
"Walker",
"Walsh",
"Walter",
"Ward",
"Waters",
"Watsica",
"Weber",
"Wehner",
"Weimann",
"Weissnat",
"Welch",
"West",
"White",
"Wiegand",
"Wilderman",
"Wilkinson",
"Will",
"Williamson",
"Willms",
"Windler",
"Wintheiser",
"Wisoky",
"Wisozk",
"Witting",
"Wiza",
"Wolf",
"Wolff",
"Wuckert",
"Wunsch",
"Wyman",
"Yost",
"Yundt",
"Zboncak",
"Zemlak",
"Ziemann",
"Zieme",
"Zulauf"
];
},{}],125:[function(require,module,exports){
module["exports"] = [
"#{prefix} #{first_name} #{last_name}",
"#{first_name} #{last_name} #{suffix}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}"
];
},{}],126:[function(require,module,exports){
module["exports"] = [
"Mr.",
"Mrs.",
"Ms.",
"Miss",
"Dr."
];
},{}],127:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Sr.",
"I",
"II",
"III",
"IV",
"V",
"MD",
"DDS",
"PhD",
"DVM"
];
},{}],128:[function(require,module,exports){
module["exports"] = {
"descriptor": [
"Lead",
"Senior",
"Direct",
"Corporate",
"Dynamic",
"Future",
"Product",
"National",
"Regional",
"District",
"Central",
"Global",
"Customer",
"Investor",
"Dynamic",
"International",
"Legacy",
"Forward",
"Internal",
"Human",
"Chief",
"Principal"
],
"level": [
"Solutions",
"Program",
"Brand",
"Security",
"Research",
"Marketing",
"Directives",
"Implementation",
"Integration",
"Functionality",
"Response",
"Paradigm",
"Tactics",
"Identity",
"Markets",
"Group",
"Division",
"Applications",
"Optimization",
"Operations",
"Infrastructure",
"Intranet",
"Communications",
"Web",
"Branding",
"Quality",
"Assurance",
"Mobility",
"Accounts",
"Data",
"Creative",
"Configuration",
"Accountability",
"Interactions",
"Factors",
"Usability",
"Metrics"
],
"job": [
"Supervisor",
"Associate",
"Executive",
"Liason",
"Officer",
"Manager",
"Engineer",
"Specialist",
"Director",
"Coordinator",
"Administrator",
"Architect",
"Analyst",
"Designer",
"Planner",
"Orchestrator",
"Technician",
"Developer",
"Producer",
"Consultant",
"Assistant",
"Facilitator",
"Agent",
"Representative",
"Strategist"
]
};
},{}],129:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-#### x###",
"(###) ###-#### x###",
"1-###-###-#### x###",
"###.###.#### x###",
"###-###-#### x####",
"(###) ###-#### x####",
"1-###-###-#### x####",
"###.###.#### x####",
"###-###-#### x#####",
"(###) ###-#### x#####",
"1-###-###-#### x#####",
"###.###.#### x#####"
];
},{}],130:[function(require,module,exports){
var phone_number = {};
module['exports'] = phone_number;
phone_number.formats = require("./formats");
},{"./formats":129}],131:[function(require,module,exports){
module["exports"] = [
"ants",
"bats",
"bears",
"bees",
"birds",
"buffalo",
"cats",
"chickens",
"cattle",
"dogs",
"dolphins",
"ducks",
"elephants",
"fishes",
"foxes",
"frogs",
"geese",
"goats",
"horses",
"kangaroos",
"lions",
"monkeys",
"owls",
"oxen",
"penguins",
"people",
"pigs",
"rabbits",
"sheep",
"tigers",
"whales",
"wolves",
"zebras",
"banshees",
"crows",
"black cats",
"chimeras",
"ghosts",
"conspirators",
"dragons",
"dwarves",
"elves",
"enchanters",
"exorcists",
"sons",
"foes",
"giants",
"gnomes",
"goblins",
"gooses",
"griffins",
"lycanthropes",
"nemesis",
"ogres",
"oracles",
"prophets",
"sorcerors",
"spiders",
"spirits",
"vampires",
"warlocks",
"vixens",
"werewolves",
"witches",
"worshipers",
"zombies",
"druids"
];
},{}],132:[function(require,module,exports){
var team = {};
module['exports'] = team;
team.creature = require("./creature");
team.name = require("./name");
},{"./creature":131,"./name":133}],133:[function(require,module,exports){
module["exports"] = [
"#{Address.state} #{creature}"
];
},{}],134:[function(require,module,exports){
arguments[4][49][0].apply(exports,arguments)
},{"dup":49}],135:[function(require,module,exports){
module["exports"] = [
"Nova",
"Velha",
"Grande",
"Vila",
"Município de"
];
},{}],136:[function(require,module,exports){
module["exports"] = [
"do Descoberto",
"de Nossa Senhora",
"do Norte",
"do Sul"
];
},{}],137:[function(require,module,exports){
module["exports"] = [
"Afeganistão",
"Albânia",
"Algéria",
"Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antigua and Barbada",
"Argentina",
"Armênia",
"Aruba",
"Austrália",
"Áustria",
"Alzerbajão",
"Bahamas",
"Barém",
"Bangladesh",
"Barbado",
"Belgrado",
"Bélgica",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolívia",
"Bôsnia",
"Botuasuna",
"Bouvetoia",
"Brasil",
"Arquipélago de Chagos",
"Ilhas Virgens",
"Brunei",
"Bulgária",
"Burkina Faso",
"Burundi",
"Cambójia",
"Camarões",
"Canadá",
"Cabo Verde",
"Ilhas Caiman",
"República da África Central",
"Chad",
"Chile",
"China",
"Ilhas Natal",
"Ilhas Cocos",
"Colômbia",
"Comoros",
"Congo",
"Ilhas Cook",
"Costa Rica",
"Costa do Marfim",
"Croácia",
"Cuba",
"Cyprus",
"República Tcheca",
"Dinamarca",
"Djibouti",
"Dominica",
"República Dominicana",
"Equador",
"Egito",
"El Salvador",
"Guiné Equatorial",
"Eritrea",
"Estônia",
"Etiópia",
"Ilhas Faroe",
"Malvinas",
"Fiji",
"Finlândia",
"França",
"Guiné Francesa",
"Polinésia Francesa",
"Gabão",
"Gâmbia",
"Georgia",
"Alemanha",
"Gana",
"Gibraltar",
"Grécia",
"Groelândia",
"Granada",
"Guadalupe",
"Guano",
"Guatemala",
"Guernsey",
"Guiné",
"Guiné-Bissau",
"Guiana",
"Haiti",
"Heard Island and McDonald Islands",
"Vaticano",
"Honduras",
"Hong Kong",
"Hungria",
"Iceland",
"Índia",
"Indonésia",
"Irã",
"Iraque",
"Irlanda",
"Ilha de Man",
"Israel",
"Itália",
"Jamaica",
"Japão",
"Jersey",
"Jordânia",
"Cazaquistão",
"Quênia",
"Kiribati",
"Coreia do Norte",
"Coreia do Sul",
"Kuwait",
"Kyrgyz Republic",
"República Democrática de Lao People",
"Latvia",
"Líbano",
"Lesotho",
"Libéria",
"Libyan Arab Jamahiriya",
"Liechtenstein",
"Lituânia",
"Luxemburgo",
"Macao",
"Macedônia",
"Madagascar",
"Malawi",
"Malásia",
"Maldives",
"Mali",
"Malta",
"Ilhas Marshall",
"Martinica",
"Mauritânia",
"Mauritius",
"Mayotte",
"México",
"Micronésia",
"Moldova",
"Mônaco",
"Mongólia",
"Montenegro",
"Montserrat",
"Marrocos",
"Moçambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Antilhas Holandesas",
"Holanda",
"Nova Caledonia",
"Nova Zelândia",
"Nicarágua",
"Nigéria",
"Niue",
"Ilha Norfolk",
"Northern Mariana Islands",
"Noruega",
"Oman",
"Paquistão",
"Palau",
"Território da Palestina",
"Panamá",
"Nova Guiné Papua",
"Paraguai",
"Peru",
"Filipinas",
"Polônia",
"Portugal",
"Puerto Rico",
"Qatar",
"Romênia",
"Rússia",
"Ruanda",
"São Bartolomeu",
"Santa Helena",
"Santa Lúcia",
"Saint Martin",
"Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines",
"Samoa",
"San Marino",
"Sao Tomé e Príncipe",
"Arábia Saudita",
"Senegal",
"Sérvia",
"Seychelles",
"Serra Leoa",
"Singapura",
"Eslováquia",
"Eslovênia",
"Ilhas Salomão",
"Somália",
"África do Sul",
"South Georgia and the South Sandwich Islands",
"Spanha",
"Sri Lanka",
"Sudão",
"Suriname",
"Svalbard & Jan Mayen Islands",
"Swaziland",
"Suécia",
"Suíça",
"Síria",
"Taiwan",
"Tajiquistão",
"Tanzânia",
"Tailândia",
"Timor-Leste",
"Togo",
"Tokelau",
"Tonga",
"Trinidá e Tobago",
"Tunísia",
"Turquia",
"Turcomenistão",
"Turks and Caicos Islands",
"Tuvalu",
"Uganda",
"Ucrânia",
"Emirados Árabes Unidos",
"Reino Unido",
"Estados Unidos da América",
"Estados Unidos das Ilhas Virgens",
"Uruguai",
"Uzbequistão",
"Vanuatu",
"Venezuela",
"Vietnã",
"Wallis and Futuna",
"Sahara",
"Yemen",
"Zâmbia",
"Zimbábue"
];
},{}],138:[function(require,module,exports){
module["exports"] = [
"Brasil"
];
},{}],139:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.city_prefix = require("./city_prefix");
address.city_suffix = require("./city_suffix");
address.country = require("./country");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.default_country = require("./default_country");
},{"./building_number":134,"./city_prefix":135,"./city_suffix":136,"./country":137,"./default_country":138,"./postcode":140,"./secondary_address":141,"./state":142,"./state_abbr":143,"./street_suffix":144}],140:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-###"
];
},{}],141:[function(require,module,exports){
module["exports"] = [
"Apto. ###",
"Sobrado ##",
"Casa #",
"Lote ##",
"Quadra ##"
];
},{}],142:[function(require,module,exports){
module["exports"] = [
"Acre",
"Alagoas",
"Amapá",
"Amazonas",
"Bahia",
"Ceará",
"Distrito Federal",
"Espírito Santo",
"Goiás",
"Maranhão",
"Mato Grosso",
"Mato Grosso do Sul",
"Minas Gerais",
"Pará",
"Paraíba",
"Paraná",
"Pernambuco",
"Piauí",
"Rio de Janeiro",
"Rio Grande do Norte",
"Rio Grande do Sul",
"Rondônia",
"Roraima",
"Santa Catarina",
"São Paulo",
"Sergipe",
"Tocantins"
];
},{}],143:[function(require,module,exports){
module["exports"] = [
"AC",
"AL",
"AP",
"AM",
"BA",
"CE",
"DF",
"ES",
"GO",
"MA",
"MT",
"MS",
"PA",
"PB",
"PR",
"PE",
"PI",
"RJ",
"RN",
"RS",
"RO",
"RR",
"SC",
"SP"
];
},{}],144:[function(require,module,exports){
module["exports"] = [
"Rua",
"Avenida",
"Travessa",
"Ponte",
"Alameda",
"Marginal",
"Viela",
"Rodovia"
];
},{}],145:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
company.name = require("./name");
},{"./name":146,"./suffix":147}],146:[function(require,module,exports){
module["exports"] = [
"#{Name.last_name} #{suffix}",
"#{Name.last_name}-#{Name.last_name}",
"#{Name.last_name}, #{Name.last_name} e #{Name.last_name}"
];
},{}],147:[function(require,module,exports){
module["exports"] = [
"S.A.",
"LTDA",
"e Associados",
"Comércio"
];
},{}],148:[function(require,module,exports){
var pt_BR = {};
module['exports'] = pt_BR;
pt_BR.title = "Portuguese (Brazil)";
pt_BR.address = require("./address");
pt_BR.company = require("./company");
pt_BR.internet = require("./internet");
pt_BR.lorem = require("./lorem");
pt_BR.name = require("./name");
pt_BR.phone_number = require("./phone_number");
},{"./address":139,"./company":145,"./internet":151,"./lorem":152,"./name":155,"./phone_number":160}],149:[function(require,module,exports){
module["exports"] = [
"br",
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],150:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com",
"live.com",
"bol.com.br"
];
},{}],151:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.domain_suffix = require("./domain_suffix");
},{"./domain_suffix":149,"./free_email":150}],152:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
},{"./words":153}],153:[function(require,module,exports){
arguments[4][121][0].apply(exports,arguments)
},{"dup":121}],154:[function(require,module,exports){
module["exports"] = [
"Alessandro",
"Alessandra",
"Alexandre",
"Aline",
"Antônio",
"Breno",
"Bruna",
"Carlos",
"Carla",
"Célia",
"Cecília",
"César",
"Danilo",
"Dalila",
"Deneval",
"Eduardo",
"Eduarda",
"Esther",
"Elísio",
"Fábio",
"Fabrício",
"Fabrícia",
"Félix",
"Felícia",
"Feliciano",
"Frederico",
"Fabiano",
"Gustavo",
"Guilherme",
"Gúbio",
"Heitor",
"Hélio",
"Hugo",
"Isabel",
"Isabela",
"Ígor",
"João",
"Joana",
"Júlio César",
"Júlio",
"Júlia",
"Janaína",
"Karla",
"Kléber",
"Lucas",
"Lorena",
"Lorraine",
"Larissa",
"Ladislau",
"Marcos",
"Meire",
"Marcelo",
"Marcela",
"Margarida",
"Mércia",
"Márcia",
"Marli",
"Morgana",
"Maria",
"Norberto",
"Natália",
"Nataniel",
"Núbia",
"Ofélia",
"Paulo",
"Paula",
"Pablo",
"Pedro",
"Raul",
"Rafael",
"Rafaela",
"Ricardo",
"Roberto",
"Roberta",
"Sílvia",
"Sílvia",
"Silas",
"Suélen",
"Sara",
"Salvador",
"Sirineu",
"Talita",
"Tertuliano",
"Vicente",
"Víctor",
"Vitória",
"Yango",
"Yago",
"Yuri",
"Washington",
"Warley"
];
},{}],155:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.prefix = require("./prefix");
name.suffix = require("./suffix");
},{"./first_name":154,"./last_name":156,"./prefix":157,"./suffix":158}],156:[function(require,module,exports){
module["exports"] = [
"Silva",
"Souza",
"Carvalho",
"Santos",
"Reis",
"Xavier",
"Franco",
"Braga",
"Macedo",
"Batista",
"Barros",
"Moraes",
"Costa",
"Pereira",
"Carvalho",
"Melo",
"Saraiva",
"Nogueira",
"Oliveira",
"Martins",
"Moreira",
"Albuquerque"
];
},{}],157:[function(require,module,exports){
module["exports"] = [
"Sr.",
"Sra.",
"Srta.",
"Dr."
];
},{}],158:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Neto",
"Filho"
];
},{}],159:[function(require,module,exports){
module["exports"] = [
"(##) ####-####",
"+55 (##) ####-####",
"(##) #####-####"
];
},{}],160:[function(require,module,exports){
arguments[4][130][0].apply(exports,arguments)
},{"./formats":159,"dup":130}],161:[function(require,module,exports){
var Lorem = function (faker) {
var self = this;
var Helpers = faker.helpers;
self.words = function (num) {
if (typeof num == 'undefined') { num = 3; }
return Helpers.shuffle(faker.definitions.lorem.words).slice(0, num);
};
self.sentence = function (wordCount, range) {
if (typeof wordCount == 'undefined') { wordCount = 3; }
if (typeof range == 'undefined') { range = 7; }
// strange issue with the node_min_test failing for captialize, please fix and add faker.lorem.back
//return faker.lorem.words(wordCount + Helpers.randomNumber(range)).join(' ').capitalize();
var sentence = faker.lorem.words(wordCount + faker.random.number(range)).join(' ');
return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.';
};
self.sentences = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
var sentences = [];
for (sentenceCount; sentenceCount > 0; sentenceCount--) {
sentences.push(faker.lorem.sentence());
}
return sentences.join("\n");
};
self.paragraph = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
return faker.lorem.sentences(sentenceCount + faker.random.number(3));
};
self.paragraphs = function (paragraphCount, separator) {
if (typeof separator === "undefined") {
separator = "\n \r";
}
if (typeof paragraphCount == 'undefined') { paragraphCount = 3; }
var paragraphs = [];
for (paragraphCount; paragraphCount > 0; paragraphCount--) {
paragraphs.push(faker.lorem.paragraph());
}
return paragraphs.join(separator);
}
return self;
};
module["exports"] = Lorem;
},{}],162:[function(require,module,exports){
function Name (faker) {
this.firstName = function (gender) {
if (typeof faker.definitions.name.male_first_name !== "undefined" && typeof faker.definitions.name.female_first_name !== "undefined") {
// some locale datasets ( like ru ) have first_name split by gender. since the name.first_name field does not exist in these datasets,
// we must randomly pick a name from either gender array so faker.name.firstName will return the correct locale data ( and not fallback )
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_first_name)
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_first_name);
}
}
return faker.random.arrayElement(faker.definitions.name.first_name);
};
this.lastName = function (gender) {
if (typeof faker.definitions.name.male_last_name !== "undefined" && typeof faker.definitions.name.female_last_name !== "undefined") {
// some locale datasets ( like ru ) have last_name split by gender. i have no idea how last names can have genders, but also i do not speak russian
// see above comment of firstName method
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_last_name);
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_last_name);
}
}
return faker.random.arrayElement(faker.definitions.name.last_name);
};
this.findName = function (firstName, lastName, gender) {
var r = faker.random.number(8);
var prefix, suffix;
// in particular locales first and last names split by gender,
// thus we keep consistency by passing 0 as male and 1 as female
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
firstName = firstName || faker.name.firstName(gender);
lastName = lastName || faker.name.lastName(gender);
switch (r) {
case 0:
prefix = faker.name.prefix();
if (prefix) {
return prefix + " " + firstName + " " + lastName;
}
case 1:
suffix = faker.name.prefix();
if (suffix) {
return firstName + " " + lastName + " " + suffix;
}
}
return firstName + " " + lastName;
};
this.jobTitle = function () {
return faker.name.jobDescriptor() + " " +
faker.name.jobArea() + " " +
faker.name.jobType();
};
this.prefix = function () {
return faker.random.arrayElement(faker.definitions.name.prefix);
};
this.suffix = function () {
return faker.random.arrayElement(faker.definitions.name.suffix);
};
this.title = function() {
var descriptor = faker.random.arrayElement(faker.definitions.name.title.descriptor),
level = faker.random.arrayElement(faker.definitions.name.title.level),
job = faker.random.arrayElement(faker.definitions.name.title.job);
return descriptor + " " + level + " " + job;
};
this.jobDescriptor = function () {
return faker.random.arrayElement(faker.definitions.name.title.descriptor);
};
this.jobArea = function () {
return faker.random.arrayElement(faker.definitions.name.title.level);
};
this.jobType = function () {
return faker.random.arrayElement(faker.definitions.name.title.job);
};
}
module['exports'] = Name;
},{}],163:[function(require,module,exports){
var Phone = function (faker) {
var self = this;
self.phoneNumber = function (format) {
format = format || faker.phone.phoneFormats();
return faker.helpers.replaceSymbolWithNumber(format);
};
// FIXME: this is strange passing in an array index.
self.phoneNumberFormat = function (phoneFormatsArrayIndex) {
phoneFormatsArrayIndex = phoneFormatsArrayIndex || 0;
return faker.helpers.replaceSymbolWithNumber(faker.definitions.phone_number.formats[phoneFormatsArrayIndex]);
};
self.phoneFormats = function () {
return faker.random.arrayElement(faker.definitions.phone_number.formats);
};
return self;
};
module['exports'] = Phone;
},{}],164:[function(require,module,exports){
var mersenne = require('../vendor/mersenne');
function Random (faker, seed) {
// Use a user provided seed if it exists
if (seed) {
if (Array.isArray(seed) && seed.length) {
mersenne.seed_array(seed);
}
else {
mersenne.seed(seed);
}
}
// returns a single random number based on a max number or range
this.number = function (options) {
if (typeof options === "number") {
options = {
max: options
};
}
options = options || {};
if (typeof options.min === "undefined") {
options.min = 0;
}
if (typeof options.max === "undefined") {
options.max = 99999;
}
if (typeof options.precision === "undefined") {
options.precision = 1;
}
// Make the range inclusive of the max value
var max = options.max;
if (max >= 0) {
max += options.precision;
}
var randomNumber = options.precision * Math.floor(
mersenne.rand(max / options.precision, options.min / options.precision));
return randomNumber;
}
// takes an array and returns a random element of the array
this.arrayElement = function (array) {
array = array || ["a", "b", "c"];
var r = faker.random.number({ max: array.length - 1 });
return array[r];
}
// takes an object and returns the randomly key or value
this.objectElement = function (object, field) {
object = object || { "foo": "bar", "too": "car" };
var array = Object.keys(object);
var key = faker.random.arrayElement(array);
return field === "key" ? key : object[key];
}
this.uuid = function () {
var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var replacePlaceholders = function (placeholder) {
var random = Math.random()*16|0;
var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
return value.toString(16);
};
return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
}
this.boolean =function () {
return !!faker.random.number(1)
}
return this;
}
module['exports'] = Random;
// module.exports = random;
},{"../vendor/mersenne":166}],165:[function(require,module,exports){
var Faker = require('../lib');
var faker = new Faker({ locale: 'pt_BR', localeFallback: 'en' });
faker.locales['pt_BR'] = require('../lib/locales/pt_BR');
faker.locales['en'] = require('../lib/locales/en');
module['exports'] = faker;
},{"../lib":47,"../lib/locales/en":114,"../lib/locales/pt_BR":148}],166:[function(require,module,exports){
// this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class,
// an almost straight conversion from the original program, mt19937ar.c,
// translated by y. okada on July 17, 2006.
// and modified a little at july 20, 2006, but there are not any substantial differences.
// in this program, procedure descriptions and comments of original source code were not removed.
// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.
// lines commented with /* and */ are original comments.
// lines commented with // are additional comments in this JavaScript version.
// before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances.
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
function MersenneTwister19937()
{
/* constants should be scoped inside the class */
var N, M, MATRIX_A, UPPER_MASK, LOWER_MASK;
/* Period parameters */
//c//#define N 624
//c//#define M 397
//c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */
//c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
//c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
N = 624;
M = 397;
MATRIX_A = 0x9908b0df; /* constant vector a */
UPPER_MASK = 0x80000000; /* most significant w-r bits */
LOWER_MASK = 0x7fffffff; /* least significant r bits */
//c//static unsigned long mt[N]; /* the array for the state vector */
//c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
var mt = new Array(N); /* the array for the state vector */
var mti = N+1; /* mti==N+1 means mt[N] is not initialized */
function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.
{
return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;
}
function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;
}
function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return unsigned32((n1 + n2) & 0xffffffff)
}
function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
var sum = 0;
for (var i = 0; i < 32; ++i){
if ((n1 >>> i) & 0x1){
sum = addition32(sum, unsigned32(n2 << i));
}
}
return sum;
}
/* initializes mt[N] with a seed */
//c//void init_genrand(unsigned long s)
this.init_genrand = function (s)
{
//c//mt[0]= s & 0xffffffff;
mt[0]= unsigned32(s & 0xffffffff);
for (mti=1; mti<N; mti++) {
mt[mti] =
//c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//c//mt[mti] &= 0xffffffff;
mt[mti] = unsigned32(mt[mti] & 0xffffffff);
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//c//void init_by_array(unsigned long init_key[], int key_length)
this.init_by_array = function (init_key, key_length)
{
//c//int i, j, k;
var i, j, k;
//c//init_genrand(19650218);
this.init_genrand(19650218);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))
//c// + init_key[j] + j; /* non linear */
mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);
mt[i] =
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
unsigned32(mt[i] & 0xffffffff);
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))
//c//- i; /* non linear */
mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
mt[i] = unsigned32(mt[i] & 0xffffffff);
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
/* moved outside of genrand_int32() by jwatte 2010-11-17; generate less garbage */
var mag01 = [0x0, MATRIX_A];
/* generates a random number on [0,0xffffffff]-interval */
//c//unsigned long genrand_int32(void)
this.genrand_int32 = function ()
{
//c//unsigned long y;
//c//static unsigned long mag01[2]={0x0UL, MATRIX_A};
var y;
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
//c//int kk;
var kk;
if (mti == N+1) /* if init_genrand() has not been called, */
//c//init_genrand(5489); /* a default initial seed is used */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
for (;kk<N-1;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
//c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
//c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));
mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
//c//y ^= (y >> 11);
//c//y ^= (y << 7) & 0x9d2c5680;
//c//y ^= (y << 15) & 0xefc60000;
//c//y ^= (y >> 18);
y = unsigned32(y ^ (y >>> 11));
y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));
y = unsigned32(y ^ ((y << 15) & 0xefc60000));
y = unsigned32(y ^ (y >>> 18));
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
//c//long genrand_int31(void)
this.genrand_int31 = function ()
{
//c//return (genrand_int32()>>1);
return (this.genrand_int32()>>>1);
}
/* generates a random number on [0,1]-real-interval */
//c//double genrand_real1(void)
this.genrand_real1 = function ()
{
//c//return genrand_int32()*(1.0/4294967295.0);
return this.genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
//c//double genrand_real2(void)
this.genrand_real2 = function ()
{
//c//return genrand_int32()*(1.0/4294967296.0);
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//c//double genrand_real3(void)
this.genrand_real3 = function ()
{
//c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);
return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
//c//double genrand_res53(void)
this.genrand_res53 = function ()
{
//c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
// Exports: Public API
// Export the twister class
exports.MersenneTwister19937 = MersenneTwister19937;
// Export a simplified function to generate random numbers
var gen = new MersenneTwister19937;
gen.init_genrand((new Date).getTime() % 1000000000);
// Added max, min range functionality, Marak Squires Sept 11 2014
exports.rand = function(max, min) {
if (max === undefined)
{
min = 0;
max = 32768;
}
return Math.floor(gen.genrand_real2() * (max - min) + min);
}
exports.seed = function(S) {
if (typeof(S) != 'number')
{
throw new Error("seed(S) must take numeric argument; is " + typeof(S));
}
gen.init_genrand(S);
}
exports.seed_array = function(A) {
if (typeof(A) != 'object')
{
throw new Error("seed_array(A) must take array of numbers; is " + typeof(A));
}
gen.init_by_array(A);
}
},{}],167:[function(require,module,exports){
/*
* password-generator
* Copyright(c) 2011-2013 Bermi Ferrer <bermi@bermilabs.com>
* MIT Licensed
*/
(function (root) {
var localName, consonant, letter, password, vowel;
letter = /[a-zA-Z]$/;
vowel = /[aeiouAEIOU]$/;
consonant = /[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/;
// Defines the name of the local variable the passwordGenerator library will use
// this is specially useful if window.passwordGenerator is already being used
// by your application and you want a different name. For example:
// // Declare before including the passwordGenerator library
// var localPasswordGeneratorLibraryName = 'pass';
localName = root.localPasswordGeneratorLibraryName || "generatePassword",
password = function (length, memorable, pattern, prefix) {
var char, n;
if (length == null) {
length = 10;
}
if (memorable == null) {
memorable = true;
}
if (pattern == null) {
pattern = /\w/;
}
if (prefix == null) {
prefix = '';
}
if (prefix.length >= length) {
return prefix;
}
if (memorable) {
if (prefix.match(consonant)) {
pattern = vowel;
} else {
pattern = consonant;
}
}
n = Math.floor(Math.random() * 94) + 33;
char = String.fromCharCode(n);
if (memorable) {
char = char.toLowerCase();
}
if (!char.match(pattern)) {
return password(length, memorable, pattern, prefix);
}
return password(length, memorable, pattern, "" + prefix + char);
};
((typeof exports !== 'undefined') ? exports : root)[localName] = password;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = password;
}
}
// Establish the root object, `window` in the browser, or `global` on the server.
}(this));
},{}],168:[function(require,module,exports){
/*
Copyright (c) 2012-2014 Jeffrey Mealo
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.
------------------------------------------------------------------------------------------------------------------------
Based loosely on Luka Pusic's PHP Script: http://360percents.com/posts/php-random-user-agent-generator/
The license for that script is as follows:
"THE BEER-WARE LICENSE" (Revision 42):
<pusic93@gmail.com> wrote this file. As long as you retain this notice you can do whatever you want with this stuff.
If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Luka Pusic
*/
function rnd(a, b) {
//calling rnd() with no arguments is identical to rnd(0, 100)
a = a || 0;
b = b || 100;
if (typeof b === 'number' && typeof a === 'number') {
//rnd(int min, int max) returns integer between min, max
return (function (min, max) {
if (min > max) {
throw new RangeError('expected min <= max; got min = ' + min + ', max = ' + max);
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}(a, b));
}
if (Object.prototype.toString.call(a) === "[object Array]") {
//returns a random element from array (a), even weighting
return a[Math.floor(Math.random() * a.length)];
}
if (a && typeof a === 'object') {
//returns a random key from the passed object; keys are weighted by the decimal probability in their value
return (function (obj) {
var rand = rnd(0, 100) / 100, min = 0, max = 0, key, return_val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
max = obj[key] + min;
return_val = key;
if (rand >= min && rand <= max) {
break;
}
min = min + obj[key];
}
}
return return_val;
}(a));
}
throw new TypeError('Invalid arguments passed to rnd. (' + (b ? a + ', ' + b : a) + ')');
}
function randomLang() {
return rnd(['AB', 'AF', 'AN', 'AR', 'AS', 'AZ', 'BE', 'BG', 'BN', 'BO', 'BR', 'BS', 'CA', 'CE', 'CO', 'CS',
'CU', 'CY', 'DA', 'DE', 'EL', 'EN', 'EO', 'ES', 'ET', 'EU', 'FA', 'FI', 'FJ', 'FO', 'FR', 'FY',
'GA', 'GD', 'GL', 'GV', 'HE', 'HI', 'HR', 'HT', 'HU', 'HY', 'ID', 'IS', 'IT', 'JA', 'JV', 'KA',
'KG', 'KO', 'KU', 'KW', 'KY', 'LA', 'LB', 'LI', 'LN', 'LT', 'LV', 'MG', 'MK', 'MN', 'MO', 'MS',
'MT', 'MY', 'NB', 'NE', 'NL', 'NN', 'NO', 'OC', 'PL', 'PT', 'RM', 'RO', 'RU', 'SC', 'SE', 'SK',
'SL', 'SO', 'SQ', 'SR', 'SV', 'SW', 'TK', 'TR', 'TY', 'UK', 'UR', 'UZ', 'VI', 'VO', 'YI', 'ZH']);
}
function randomBrowserAndOS() {
var browser = rnd({
chrome: .45132810566,
iexplorer: .27477061836,
firefox: .19384170608,
safari: .06186781118,
opera: .01574236955
}),
os = {
chrome: {win: .89, mac: .09 , lin: .02},
firefox: {win: .83, mac: .16, lin: .01},
opera: {win: .91, mac: .03 , lin: .06},
safari: {win: .04 , mac: .96 },
iexplorer: ['win']
};
return [browser, rnd(os[browser])];
}
function randomProc(arch) {
var procs = {
lin:['i686', 'x86_64'],
mac: {'Intel' : .48, 'PPC': .01, 'U; Intel':.48, 'U; PPC' :.01},
win:['', 'WOW64', 'Win64; x64']
};
return rnd(procs[arch]);
}
function randomRevision(dots) {
var return_val = '';
//generate a random revision
//dots = 2 returns .x.y where x & y are between 0 and 9
for (var x = 0; x < dots; x++) {
return_val += '.' + rnd(0, 9);
}
return return_val;
}
var version_string = {
net: function () {
return [rnd(1, 4), rnd(0, 9), rnd(10000, 99999), rnd(0, 9)].join('.');
},
nt: function () {
return rnd(5, 6) + '.' + rnd(0, 3);
},
ie: function () {
return rnd(7, 11);
},
trident: function () {
return rnd(3, 7) + '.' + rnd(0, 1);
},
osx: function (delim) {
return [10, rnd(5, 10), rnd(0, 9)].join(delim || '.');
},
chrome: function () {
return [rnd(13, 39), 0, rnd(800, 899), 0].join('.');
},
presto: function () {
return '2.9.' + rnd(160, 190);
},
presto2: function () {
return rnd(10, 12) + '.00';
},
safari: function () {
return rnd(531, 538) + '.' + rnd(0, 2) + '.' + rnd(0,2);
}
};
var browser = {
firefox: function firefox(arch) {
//https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference
var firefox_ver = rnd(5, 15) + randomRevision(2),
gecko_ver = 'Gecko/20100101 Firefox/' + firefox_ver,
proc = randomProc(arch),
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + ((proc) ? '; ' + proc : '')
: (arch === 'mac') ? '(Macintosh; ' + proc + ' Mac OS X ' + version_string.osx()
: '(X11; Linux ' + proc;
return 'Mozilla/5.0 ' + os_ver + '; rv:' + firefox_ver.slice(0, -2) + ') ' + gecko_ver;
},
iexplorer: function iexplorer() {
var ver = version_string.ie();
if (ver >= 11) {
//http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx
return 'Mozilla/5.0 (Windows NT 6.' + rnd(1,3) + '; Trident/7.0; ' + rnd(['Touch; ', '']) + 'rv:11.0) like Gecko';
}
//http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx
return 'Mozilla/5.0 (compatible; MSIE ' + ver + '.0; Windows NT ' + version_string.nt() + '; Trident/' +
version_string.trident() + ((rnd(0, 1) === 1) ? '; .NET CLR ' + version_string.net() : '') + ')';
},
opera: function opera(arch) {
//http://www.opera.com/docs/history/
var presto_ver = ' Presto/' + version_string.presto() + ' Version/' + version_string.presto2() + ')',
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + '; U; ' + randomLang() + presto_ver
: (arch === 'lin') ? '(X11; Linux ' + randomProc(arch) + '; U; ' + randomLang() + presto_ver
: '(Macintosh; Intel Mac OS X ' + version_string.osx() + ' U; ' + randomLang() + ' Presto/' +
version_string.presto() + ' Version/' + version_string.presto2() + ')';
return 'Opera/' + rnd(9, 14) + '.' + rnd(0, 99) + ' ' + os_ver;
},
safari: function safari(arch) {
var safari = version_string.safari(),
ver = rnd(4, 7) + '.' + rnd(0,1) + '.' + rnd(0,10),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X '+ version_string.osx('_') + ' rv:' + rnd(2, 6) + '.0; '+ randomLang() + ') '
: '(Windows; U; Windows NT ' + version_string.nt() + ')';
return 'Mozilla/5.0 ' + os_ver + 'AppleWebKit/' + safari + ' (KHTML, like Gecko) Version/' + ver + ' Safari/' + safari;
},
chrome: function chrome(arch) {
var safari = version_string.safari(),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X ' + version_string.osx('_') + ') '
: (arch === 'win') ? '(Windows; U; Windows NT ' + version_string.nt() + ')'
: '(X11; Linux ' + randomProc(arch);
return 'Mozilla/5.0 ' + os_ver + ' AppleWebKit/' + safari + ' (KHTML, like Gecko) Chrome/' + version_string.chrome() + ' Safari/' + safari;
}
};
exports.generate = function generate() {
var random = randomBrowserAndOS();
return browser[random[0]](random[1]);
};
},{}],169:[function(require,module,exports){
var ret = require('ret');
var DRange = require('discontinuous-range');
var types = ret.types;
/**
* If code is alphabetic, converts to other case.
* If not alphabetic, returns back code.
*
* @param {Number} code
* @return {Number}
*/
function toOtherCase(code) {
return code + (97 <= code && code <= 122 ? -32 :
65 <= code && code <= 90 ? 32 : 0);
}
/**
* Randomly returns a true or false value.
*
* @return {Boolean}
*/
function randBool() {
return !this.randInt(0, 1);
}
/**
* Randomly selects and returns a value from the array.
*
* @param {Array.<Object>} arr
* @return {Object}
*/
function randSelect(arr) {
if (arr instanceof DRange) {
return arr.index(this.randInt(0, arr.length - 1));
}
return arr[this.randInt(0, arr.length - 1)];
}
/**
* expands a token to a DiscontinuousRange of characters which has a
* length and an index function (for random selecting)
*
* @param {Object} token
* @return {DiscontinuousRange}
*/
function expand(token) {
if (token.type === ret.types.CHAR) {
return new DRange(token.value);
} else if (token.type === ret.types.RANGE) {
return new DRange(token.from, token.to);
} else {
var drange = new DRange();
for (var i = 0; i < token.set.length; i++) {
var subrange = expand.call(this, token.set[i]);
drange.add(subrange);
if (this.ignoreCase) {
for (var j = 0; j < subrange.length; j++) {
var code = subrange.index(j);
var otherCaseCode = toOtherCase(code);
if (code !== otherCaseCode) {
drange.add(otherCaseCode);
}
}
}
}
if (token.not) {
return this.defaultRange.clone().subtract(drange);
} else {
return drange;
}
}
}
/**
* Checks if some custom properties have been set for this regexp.
*
* @param {RandExp} randexp
* @param {RegExp} regexp
*/
function checkCustom(randexp, regexp) {
if (typeof regexp.max === 'number') {
randexp.max = regexp.max;
}
if (regexp.defaultRange instanceof DRange) {
randexp.defaultRange = regexp.defaultRange;
}
if (typeof regexp.randInt === 'function') {
randexp.randInt = regexp.randInt;
}
}
/**
* @constructor
* @param {RegExp|String} regexp
* @param {String} m
*/
var RandExp = module.exports = function(regexp, m) {
this.defaultRange = this.defaultRange.clone();
if (regexp instanceof RegExp) {
this.ignoreCase = regexp.ignoreCase;
this.multiline = regexp.multiline;
checkCustom(this, regexp);
regexp = regexp.source;
} else if (typeof regexp === 'string') {
this.ignoreCase = m && m.indexOf('i') !== -1;
this.multiline = m && m.indexOf('m') !== -1;
} else {
throw new Error('Expected a regexp or string');
}
this.tokens = ret(regexp);
};
// When a repetitional token has its max set to Infinite,
// randexp won't actually generate a random amount between min and Infinite
// instead it will see Infinite as min + 100.
RandExp.prototype.max = 100;
// Generates the random string.
RandExp.prototype.gen = function() {
return gen.call(this, this.tokens, []);
};
// Enables use of randexp with a shorter call.
RandExp.randexp = function(regexp, m) {
var randexp;
if (regexp._randexp === undefined) {
randexp = new RandExp(regexp, m);
regexp._randexp = randexp;
} else {
randexp = regexp._randexp;
}
checkCustom(randexp, regexp);
return randexp.gen();
};
// This enables sugary /regexp/.gen syntax.
RandExp.sugar = function() {
/* jshint freeze:false */
RegExp.prototype.gen = function() {
return RandExp.randexp(this);
};
};
// This allows expanding to include additional characters
// for instance: RandExp.defaultRange.add(0, 65535);
RandExp.prototype.defaultRange = new DRange(32, 126);
/**
* Randomly generates and returns a number between a and b (inclusive).
*
* @param {Number} a
* @param {Number} b
* @return {Number}
*/
RandExp.prototype.randInt = function(a, b) {
return a + Math.floor(Math.random() * (1 + b - a));
};
/**
* Generate random string modeled after given tokens.
*
* @param {Object} token
* @param {Array.<String>} groups
* @return {String}
*/
function gen(token, groups) {
var stack, str, n, i, l;
switch (token.type) {
case types.ROOT:
case types.GROUP:
// Ignore lookaheads for now.
if (token.followedBy || token.notFollowedBy) { return ''; }
// Insert placeholder until group string is generated.
if (token.remember && token.groupNumber === undefined) {
token.groupNumber = groups.push(null) - 1;
}
stack = token.options ?
randSelect.call(this, token.options) : token.stack;
str = '';
for (i = 0, l = stack.length; i < l; i++) {
str += gen.call(this, stack[i], groups);
}
if (token.remember) {
groups[token.groupNumber] = str;
}
return str;
case types.POSITION:
// Do nothing for now.
return '';
case types.SET:
var expandedSet = expand.call(this, token);
if (!expandedSet.length) { return ''; }
return String.fromCharCode(randSelect.call(this, expandedSet));
case types.REPETITION:
// Randomly generate number between min and max.
n = this.randInt(token.min,
token.max === Infinity ? token.min + this.max : token.max);
str = '';
for (i = 0; i < n; i++) {
str += gen.call(this, token.value, groups);
}
return str;
case types.REFERENCE:
return groups[token.value - 1] || '';
case types.CHAR:
var code = this.ignoreCase && randBool.call(this) ?
toOtherCase(token.value) : token.value;
return String.fromCharCode(code);
}
}
},{"discontinuous-range":37,"ret":170}],170:[function(require,module,exports){
var util = require('./util');
var types = require('./types');
var sets = require('./sets');
var positions = require('./positions');
module.exports = function(regexpStr) {
var i = 0, l, c,
start = { type: types.ROOT, stack: []},
// Keep track of last clause/group and stack.
lastGroup = start,
last = start.stack,
groupStack = [];
var repeatErr = function(i) {
util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
};
// Decode a few escaped characters.
var str = util.strToChars(regexpStr);
l = str.length;
// Iterate through each character in string.
while (i < l) {
c = str[i++];
switch (c) {
// Handle escaped characters, inclues a few sets.
case '\\':
c = str[i++];
switch (c) {
case 'b':
last.push(positions.wordBoundary());
break;
case 'B':
last.push(positions.nonWordBoundary());
break;
case 'w':
last.push(sets.words());
break;
case 'W':
last.push(sets.notWords());
break;
case 'd':
last.push(sets.ints());
break;
case 'D':
last.push(sets.notInts());
break;
case 's':
last.push(sets.whitespace());
break;
case 'S':
last.push(sets.notWhitespace());
break;
default:
// Check if c is integer.
// In which case it's a reference.
if (/\d/.test(c)) {
last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
// Escaped character.
} else {
last.push({ type: types.CHAR, value: c.charCodeAt(0) });
}
}
break;
// Positionals.
case '^':
last.push(positions.begin());
break;
case '$':
last.push(positions.end());
break;
// Handle custom sets.
case '[':
// Check if this class is 'anti' i.e. [^abc].
var not;
if (str[i] === '^') {
not = true;
i++;
} else {
not = false;
}
// Get all the characters in class.
var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
// Increase index by length of class.
i += classTokens[1];
last.push({
type: types.SET,
set: classTokens[0],
not: not,
});
break;
// Class of any character except \n.
case '.':
last.push(sets.anyChar());
break;
// Push group onto stack.
case '(':
// Create group.
var group = {
type: types.GROUP,
stack: [],
remember: true,
};
c = str[i];
// If if this is a special kind of group.
if (c === '?') {
c = str[i + 1];
i += 2;
// Match if followed by.
if (c === '=') {
group.followedBy = true;
// Match if not followed by.
} else if (c === '!') {
group.notFollowedBy = true;
} else if (c !== ':') {
util.error(regexpStr,
'Invalid group, character \'' + c +
'\' after \'?\' at column ' + (i - 1));
}
group.remember = false;
}
// Insert subgroup into current group stack.
last.push(group);
// Remember the current group for when the group closes.
groupStack.push(lastGroup);
// Make this new group the current group.
lastGroup = group;
last = group.stack;
break;
// Pop group out of stack.
case ')':
if (groupStack.length === 0) {
util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
}
lastGroup = groupStack.pop();
// Check if this group has a PIPE.
// To get back the correct last stack.
last = lastGroup.options ?
lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
break;
// Use pipe character to give more choices.
case '|':
// Create array where options are if this is the first PIPE
// in this clause.
if (!lastGroup.options) {
lastGroup.options = [lastGroup.stack];
delete lastGroup.stack;
}
// Create a new stack and add to options for rest of clause.
var stack = [];
lastGroup.options.push(stack);
last = stack;
break;
// Repetition.
// For every repetition, remove last element from last stack
// then insert back a RANGE object.
// This design is chosen because there could be more than
// one repetition symbols in a regex i.e. `a?+{2,3}`.
case '{':
var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
if (rs !== null) {
if (last.length === 0) {
repeatErr(i);
}
min = parseInt(rs[1], 10);
max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
i += rs[0].length;
last.push({
type: types.REPETITION,
min: min,
max: max,
value: last.pop(),
});
} else {
last.push({
type: types.CHAR,
value: 123,
});
}
break;
case '?':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 0,
max: 1,
value: last.pop(),
});
break;
case '+':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 1,
max: Infinity,
value: last.pop(),
});
break;
case '*':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 0,
max: Infinity,
value: last.pop(),
});
break;
// Default is a character that is not `\[](){}?+*^$`.
default:
last.push({
type: types.CHAR,
value: c.charCodeAt(0),
});
}
}
// Check if any groups have not been closed.
if (groupStack.length !== 0) {
util.error(regexpStr, 'Unterminated group');
}
return start;
};
module.exports.types = types;
},{"./positions":171,"./sets":172,"./types":173,"./util":174}],171:[function(require,module,exports){
var types = require('./types');
exports.wordBoundary = function() {
return { type: types.POSITION, value: 'b' };
};
exports.nonWordBoundary = function() {
return { type: types.POSITION, value: 'B' };
};
exports.begin = function() {
return { type: types.POSITION, value: '^' };
};
exports.end = function() {
return { type: types.POSITION, value: '$' };
};
},{"./types":173}],172:[function(require,module,exports){
var types = require('./types');
var INTS = function() {
return [{ type: types.RANGE , from: 48, to: 57 }];
};
var WORDS = function() {
return [
{ type: types.CHAR, value: 95 },
{ type: types.RANGE, from: 97, to: 122 },
{ type: types.RANGE, from: 65, to: 90 }
].concat(INTS());
};
var WHITESPACE = function() {
return [
{ type: types.CHAR, value: 9 },
{ type: types.CHAR, value: 10 },
{ type: types.CHAR, value: 11 },
{ type: types.CHAR, value: 12 },
{ type: types.CHAR, value: 13 },
{ type: types.CHAR, value: 32 },
{ type: types.CHAR, value: 160 },
{ type: types.CHAR, value: 5760 },
{ type: types.CHAR, value: 6158 },
{ type: types.CHAR, value: 8192 },
{ type: types.CHAR, value: 8193 },
{ type: types.CHAR, value: 8194 },
{ type: types.CHAR, value: 8195 },
{ type: types.CHAR, value: 8196 },
{ type: types.CHAR, value: 8197 },
{ type: types.CHAR, value: 8198 },
{ type: types.CHAR, value: 8199 },
{ type: types.CHAR, value: 8200 },
{ type: types.CHAR, value: 8201 },
{ type: types.CHAR, value: 8202 },
{ type: types.CHAR, value: 8232 },
{ type: types.CHAR, value: 8233 },
{ type: types.CHAR, value: 8239 },
{ type: types.CHAR, value: 8287 },
{ type: types.CHAR, value: 12288 },
{ type: types.CHAR, value: 65279 }
];
};
var NOTANYCHAR = function() {
return [
{ type: types.CHAR, value: 10 },
{ type: types.CHAR, value: 13 },
{ type: types.CHAR, value: 8232 },
{ type: types.CHAR, value: 8233 },
];
};
// Predefined class objects.
exports.words = function() {
return { type: types.SET, set: WORDS(), not: false };
};
exports.notWords = function() {
return { type: types.SET, set: WORDS(), not: true };
};
exports.ints = function() {
return { type: types.SET, set: INTS(), not: false };
};
exports.notInts = function() {
return { type: types.SET, set: INTS(), not: true };
};
exports.whitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: false };
};
exports.notWhitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: true };
};
exports.anyChar = function() {
return { type: types.SET, set: NOTANYCHAR(), not: true };
};
},{"./types":173}],173:[function(require,module,exports){
module.exports = {
ROOT : 0,
GROUP : 1,
POSITION : 2,
SET : 3,
RANGE : 4,
REPETITION : 5,
REFERENCE : 6,
CHAR : 7,
};
},{}],174:[function(require,module,exports){
var types = require('./types');
var sets = require('./sets');
// All of these are private and only used by randexp.
// It's assumed that they will always be called with the correct input.
var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
/**
* Finds character representations in str and convert all to
* their respective characters
*
* @param {String} str
* @return {String}
*/
exports.strToChars = function(str) {
/* jshint maxlen: false */
var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
if (lbs) {
return s;
}
var code = b ? 8 :
a16 ? parseInt(a16, 16) :
b16 ? parseInt(b16, 16) :
c8 ? parseInt(c8, 8) :
dctrl ? CTRL.indexOf(dctrl) :
SLSH[eslsh];
var c = String.fromCharCode(code);
// Escape special regex characters.
if (/[\[\]{}\^$.|?*+()]/.test(c)) {
c = '\\' + c;
}
return c;
});
return str;
};
/**
* turns class into tokens
* reads str until it encounters a ] not preceeded by a \
*
* @param {String} str
* @param {String} regexpStr
* @return {Array.<Array.<Object>, Number>}
*/
exports.tokenizeClass = function(str, regexpStr) {
/* jshint maxlen: false */
var tokens = [];
var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g;
var rs, c;
while ((rs = regexp.exec(str)) != null) {
if (rs[1]) {
tokens.push(sets.words());
} else if (rs[2]) {
tokens.push(sets.ints());
} else if (rs[3]) {
tokens.push(sets.whitespace());
} else if (rs[4]) {
tokens.push(sets.notWords());
} else if (rs[5]) {
tokens.push(sets.notInts());
} else if (rs[6]) {
tokens.push(sets.notWhitespace());
} else if (rs[7]) {
tokens.push({
type: types.RANGE,
from: (rs[8] || rs[9]).charCodeAt(0),
to: rs[10].charCodeAt(0),
});
} else if (c = rs[12]) {
tokens.push({
type: types.CHAR,
value: c.charCodeAt(0),
});
} else {
return [tokens, regexp.lastIndex];
}
}
exports.error(regexpStr, 'Unterminated character class');
};
/**
* Shortcut to throw errors.
*
* @param {String} regexp
* @param {String} msg
*/
exports.error = function(regexp, msg) {
throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
};
},{"./sets":172,"./types":173}],"json-schema-faker":[function(require,module,exports){
module.exports = require('../lib/')
.extend('faker', function() {
try {
return require('faker/locale/pt_BR');
} catch (e) {
return null;
}
});
},{"../lib/":20,"faker/locale/pt_BR":165}]},{},["json-schema-faker"])("json-schema-faker")
}); |
import utils from '../other/utils';
export default formlyUtil;
// @ngInject
function formlyUtil() {
return utils;
}
|
var _ = require('lodash');
module.exports = function createOverviewDump() {
return {
$runAfter: ['processing-docs'],
$runBefore: ['docs-processed'],
$process: function(docs) {
var overviewDoc = {
id: 'overview-dump',
aliases: ['overview-dump'],
path: 'overview-dump',
outputPath: 'overview-dump.html',
modules: []
};
_.forEach(docs, function(doc) {
if (doc.docType === 'package') {
overviewDoc.modules.push(doc);
}
});
docs.push(overviewDoc);
}
};
}; |
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive
This manager also supports multitouch.
@class InteractionManager
@constructor
@param stage {Stage}
@type Stage
*/
PIXI.InteractionManager = function(stage)
{
/**
* a refference to the stage
* @property stage
* @type Stage
*/
this.stage = stage;
// helpers
this.tempPoint = new PIXI.Point();
//this.tempMatrix = mat3.create();
this.mouseoverEnabled = true;
/**
* the mouse data
* @property mouse
* @type InteractionData
*/
this.mouse = new PIXI.InteractionData();
/**
* an object that stores current touches (InteractionData) by id reference
* @property touchs
* @type Object
*/
this.touchs = {};
//tiny little interactiveData pool!
this.pool = [];
this.interactiveItems = [];
this.last = 0;
}
// constructor
PIXI.InteractionManager.constructor = PIXI.InteractionManager;
PIXI.InteractionManager.prototype.collectInteractiveSprite = function(displayObject, iParent)
{
var children = displayObject.children;
var length = children.length;
//this.interactiveItems = [];
/// make an interaction tree... {item.__interactiveParent}
for (var i = length-1; i >= 0; i--)
{
var child = children[i];
if(child.visible) {
// push all interactive bits
if(child.interactive)
{
iParent.interactiveChildren = true;
//child.__iParent = iParent;
this.interactiveItems.push(child);
if(child.children.length > 0)
{
this.collectInteractiveSprite(child, child);
}
}
else
{
child.__iParent = null;
if(child.children.length > 0)
{
this.collectInteractiveSprite(child, iParent);
}
}
}
}
}
PIXI.InteractionManager.prototype.setTarget = function(target)
{
if (window.navigator.msPointerEnabled)
{
// time to remove some of that zoom in ja..
target.view.style["-ms-content-zooming"] = "none";
target.view.style["-ms-touch-action"] = "none"
// DO some window specific touch!
}
this.target = target;
target.view.addEventListener('mousemove', this.onMouseMove.bind(this), true);
target.view.addEventListener('mousedown', this.onMouseDown.bind(this), true);
document.body.addEventListener('mouseup', this.onMouseUp.bind(this), true);
target.view.addEventListener('mouseout', this.onMouseUp.bind(this), true);
// aint no multi touch just yet!
target.view.addEventListener("touchstart", this.onTouchStart.bind(this), true);
target.view.addEventListener("touchend", this.onTouchEnd.bind(this), true);
target.view.addEventListener("touchmove", this.onTouchMove.bind(this), true);
}
PIXI.InteractionManager.prototype.update = function()
{
if(!this.target)return;
// frequency of 30fps??
var now = Date.now();
var diff = now - this.last;
diff = (diff * 30) / 1000;
if(diff < 1)return;
this.last = now;
//
// ok.. so mouse events??
// yes for now :)
// OPTIMSE - how often to check??
if(this.dirty)
{
this.dirty = false;
var len = this.interactiveItems.length;
for (var i=0; i < this.interactiveItems.length; i++) {
this.interactiveItems[i].interactiveChildren = false;
}
this.interactiveItems = [];
if(this.stage.interactive)this.interactiveItems.push(this.stage);
// go through and collect all the objects that are interactive..
this.collectInteractiveSprite(this.stage, this.stage);
}
// loop through interactive objects!
var length = this.interactiveItems.length;
this.target.view.style.cursor = "default";
for (var i = 0; i < length; i++)
{
var item = this.interactiveItems[i];
if(!item.visible)continue;
// OPTIMISATION - only calculate every time if the mousemove function exists..
// OK so.. does the object have any other interactive functions?
// hit-test the clip!
if(item.mouseover || item.mouseout || item.buttonMode)
{
// ok so there are some functions so lets hit test it..
item.__hit = this.hitTest(item, this.mouse);
// ok so deal with interactions..
// loks like there was a hit!
if(item.__hit)
{
if(item.buttonMode)this.target.view.style.cursor = "pointer";
if(!item.__isOver)
{
if(item.mouseover)item.mouseover(this.mouse);
item.__isOver = true;
}
}
else
{
if(item.__isOver)
{
// roll out!
if(item.mouseout)item.mouseout(this.mouse);
item.__isOver = false;
}
}
}
// --->
}
}
PIXI.InteractionManager.prototype.onMouseMove = function(event)
{
// TODO optimize by not check EVERY TIME! maybe half as often? //
var rect = this.target.view.getBoundingClientRect();
this.mouse.global.x = (event.clientX - rect.left) * (this.target.width / rect.width);
this.mouse.global.y = (event.clientY - rect.top) * ( this.target.height / rect.height);
var length = this.interactiveItems.length;
var global = this.mouse.global;
for (var i = 0; i < length; i++)
{
var item = this.interactiveItems[i];
if(item.mousemove)
{
//call the function!
item.mousemove(this.mouse);
}
}
}
PIXI.InteractionManager.prototype.onMouseDown = function(event)
{
event.preventDefault();
// loop through inteaction tree...
// hit test each item! ->
// get interactive items under point??
//stage.__i
var length = this.interactiveItems.length;
var global = this.mouse.global;
var index = 0;
var parent = this.stage;
// while
// hit test
for (var i = 0; i < length; i++)
{
var item = this.interactiveItems[i];
if(item.mousedown || item.click)
{
item.__mouseIsDown = true;
item.__hit = this.hitTest(item, this.mouse);
if(item.__hit)
{
//call the function!
if(item.mousedown)item.mousedown(this.mouse);
item.__isDown = true;
// just the one!
if(!item.interactiveChildren)break;
}
}
}
}
PIXI.InteractionManager.prototype.onMouseUp = function(event)
{
var global = this.mouse.global;
var length = this.interactiveItems.length;
var up = false;
for (var i = 0; i < length; i++)
{
var item = this.interactiveItems[i];
if(item.mouseup || item.mouseupoutside || item.click)
{
item.__hit = this.hitTest(item, this.mouse);
if(item.__hit && !up)
{
//call the function!
if(item.mouseup)
{
item.mouseup(this.mouse);
}
if(item.__isDown)
{
if(item.click)item.click(this.mouse);
}
if(!item.interactiveChildren)up = true;
}
else
{
if(item.__isDown)
{
if(item.mouseupoutside)item.mouseupoutside(this.mouse);
}
}
item.__isDown = false;
}
}
}
PIXI.InteractionManager.prototype.hitTest = function(item, interactionData)
{
var global = interactionData.global;
if(!item.visible)return false;
var isSprite = (item instanceof PIXI.Sprite),
worldTransform = item.worldTransform,
a00 = worldTransform[0], a01 = worldTransform[1], a02 = worldTransform[2],
a10 = worldTransform[3], a11 = worldTransform[4], a12 = worldTransform[5],
id = 1 / (a00 * a11 + a01 * -a10),
x = a11 * id * global.x + -a01 * id * global.y + (a12 * a01 - a02 * a11) * id,
y = a00 * id * global.y + -a10 * id * global.x + (-a12 * a00 + a02 * a10) * id;
//a sprite or display object with a hit area defined
if(item.hitArea)
{
var hitArea = item.hitArea;
//Polygon hit area
if(item.hitArea instanceof PIXI.Polygon) {
var inside = false;
// use some raycasting to test hits
// https://github.com/substack/point-in-polygon/blob/master/index.js
for(var i = 0, j = item.hitArea.points.length - 1; i < item.hitArea.points.length; j = i++) {
var xi = item.hitArea.points[i].x, yi = item.hitArea.points[i].y,
xj = item.hitArea.points[j].x, yj = item.hitArea.points[j].y,
intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if(intersect) inside = !inside;
}
if(inside) {
if(isSprite) interactionData.target = item;
return true;
}
}
//Rectangle hit area
else {
var x1 = hitArea.x;
if(x > x1 && x < x1 + hitArea.width)
{
var y1 = hitArea.y;
if(y > y1 && y < y1 + hitArea.height)
{
if(isSprite) interactionData.target = item;
return true;
}
}
}
}
// a sprite with no hitarea defined
else if(isSprite)
{
var width = item.texture.frame.width,
height = item.texture.frame.height,
x1 = -width * item.anchor.x,
y1;
if(x > x1 && x < x1 + width)
{
y1 = -height * item.anchor.y;
if(y > y1 && y < y1 + height)
{
// set the target property if a hit is true!
interactionData.target = item
return true;
}
}
}
var length = item.children.length;
for (var i = 0; i < length; i++)
{
var tempItem = item.children[i];
var hit = this.hitTest(tempItem, interactionData);
if(hit)return true;
}
return false;
}
PIXI.InteractionManager.prototype.onTouchMove = function(event)
{
var rect = this.target.view.getBoundingClientRect();
var changedTouches = event.changedTouches;
for (var i=0; i < changedTouches.length; i++)
{
var touchEvent = changedTouches[i];
var touchData = this.touchs[touchEvent.identifier];
// update the touch position
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
}
var length = this.interactiveItems.length;
for (var i = 0; i < length; i++)
{
var item = this.interactiveItems[i];
if(item.touchmove)item.touchmove(touchData);
}
}
PIXI.InteractionManager.prototype.onTouchStart = function(event)
{
event.preventDefault();
var rect = this.target.view.getBoundingClientRect();
var changedTouches = event.changedTouches;
for (var i=0; i < changedTouches.length; i++)
{
var touchEvent = changedTouches[i];
var touchData = this.pool.pop();
if(!touchData)touchData = new PIXI.InteractionData();
this.touchs[touchEvent.identifier] = touchData;
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
var length = this.interactiveItems.length;
for (var j = 0; j < length; j++)
{
var item = this.interactiveItems[j];
if(item.touchstart || item.tap)
{
item.__hit = this.hitTest(item, touchData);
if(item.__hit)
{
//call the function!
if(item.touchstart)item.touchstart(touchData);
item.__isDown = true;
item.__touchData = touchData;
if(!item.interactiveChildren)break;
}
}
}
}
}
PIXI.InteractionManager.prototype.onTouchEnd = function(event)
{
var rect = this.target.view.getBoundingClientRect();
var changedTouches = event.changedTouches;
for (var i=0; i < changedTouches.length; i++)
{
var touchEvent = changedTouches[i];
var touchData = this.touchs[touchEvent.identifier];
var up = false;
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
var length = this.interactiveItems.length;
for (var j = 0; j < length; j++)
{
var item = this.interactiveItems[j];
var itemTouchData = item.__touchData; // <-- Here!
item.__hit = this.hitTest(item, touchData);
if(itemTouchData == touchData)
{
// so this one WAS down...
// hitTest??
if(item.touchend || item.tap)
{
if(item.__hit && !up)
{
if(item.touchend)item.touchend(touchData);
if(item.__isDown)
{
if(item.tap)item.tap(touchData);
}
if(!item.interactiveChildren)up = true;
}
else
{
if(item.__isDown)
{
if(item.touchendoutside)item.touchendoutside(touchData);
}
}
item.__isDown = false;
}
item.__touchData = null;
}
else
{
}
}
// remove the touch..
this.pool.push(touchData);
this.touchs[touchEvent.identifier] = null;
}
}
/**
@class InteractionData
@constructor
*/
PIXI.InteractionData = function()
{
/**
* This point stores the global coords of where the touch/mouse event happened
* @property global
* @type Point
*/
this.global = new PIXI.Point();
// this is here for legacy... but will remove
this.local = new PIXI.Point();
/**
* The target Sprite that was interacted with
* @property target
* @type Sprite
*/
this.target;
}
/**
* This will return the local coords of the specified displayObject for this InteractionData
* @method getLocalPosition
* @param displayObject {DisplayObject} The DisplayObject that you would like the local coords off
* @return {Point} A point containing the coords of the InteractionData position relative to the DisplayObject
*/
PIXI.InteractionData.prototype.getLocalPosition = function(displayObject)
{
var worldTransform = displayObject.worldTransform;
var global = this.global;
// do a cheeky transform to get the mouse coords;
var a00 = worldTransform[0], a01 = worldTransform[1], a02 = worldTransform[2],
a10 = worldTransform[3], a11 = worldTransform[4], a12 = worldTransform[5],
id = 1 / (a00 * a11 + a01 * -a10);
// set the mouse coords...
return new PIXI.Point(a11 * id * global.x + -a01 * id * global.y + (a12 * a01 - a02 * a11) * id,
a00 * id * global.y + -a10 * id * global.x + (-a12 * a00 + a02 * a10) * id)
}
// constructor
PIXI.InteractionData.constructor = PIXI.InteractionData;
|
module.exports = require('./wrapperPlant');
|
/*!
* # Semantic UI 2.1.7 - Modal
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.modal = function(parameters) {
var
$allModules = $(this),
$window = $(window),
$document = $(document),
$body = $('body'),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.modal.settings, parameters)
: $.extend({}, $.fn.modal.settings),
selector = settings.selector,
className = settings.className,
namespace = settings.namespace,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$close = $module.find(selector.close),
$allModals,
$otherModals,
$focusedElement,
$dimmable,
$dimmer,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
observer,
module
;
module = {
initialize: function() {
module.verbose('Initializing dimmer', $context);
module.create.id();
module.create.dimmer();
module.refreshModals();
module.bind.events();
if(settings.observeChanges) {
module.observeChanges();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of modal');
instance = module;
$module
.data(moduleNamespace, instance)
;
},
create: {
dimmer: function() {
var
defaultSettings = {
debug : settings.debug,
dimmerName : 'modals',
duration : {
show : settings.duration,
hide : settings.duration
}
},
dimmerSettings = $.extend(true, defaultSettings, settings.dimmerSettings)
;
if(settings.inverted) {
dimmerSettings.variation = (dimmerSettings.variation !== undefined)
? dimmerSettings.variation + ' inverted'
: 'inverted'
;
}
if($.fn.dimmer === undefined) {
module.error(error.dimmer);
return;
}
module.debug('Creating dimmer with settings', dimmerSettings);
$dimmable = $context.dimmer(dimmerSettings);
if(settings.detachable) {
module.verbose('Modal is detachable, moving content into dimmer');
$dimmable.dimmer('add content', $module);
}
else {
module.set.undetached();
}
if(settings.blurring) {
$dimmable.addClass(className.blurring);
}
$dimmer = $dimmable.dimmer('get dimmer');
},
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
}
},
destroy: function() {
module.verbose('Destroying previous modal');
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
$window.off(elementNamespace);
$close.off(eventNamespace);
$context.dimmer('destroy');
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.debug('DOM tree modified, refreshing');
module.refresh();
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
refresh: function() {
module.remove.scrolling();
module.cacheSizes();
module.set.screenHeight();
module.set.type();
module.set.position();
},
refreshModals: function() {
$otherModals = $module.siblings(selector.modal);
$allModals = $otherModals.add($module);
},
attachEvents: function(selector, event) {
var
$toggle = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($toggle.length > 0) {
module.debug('Attaching modal events to element', selector, event);
$toggle
.off(eventNamespace)
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound, selector);
}
},
bind: {
events: function() {
module.verbose('Attaching events');
$module
.on('click' + eventNamespace, selector.close, module.event.close)
.on('click' + eventNamespace, selector.approve, module.event.approve)
.on('click' + eventNamespace, selector.deny, module.event.deny)
;
$window
.on('resize' + elementNamespace, module.event.resize)
;
}
},
get: {
id: function() {
return (Math.random().toString(16) + '000000000').substr(2,8);
}
},
event: {
approve: function() {
if(settings.onApprove.call(element, $(this)) === false) {
module.verbose('Approve callback returned false cancelling hide');
return;
}
module.hide();
},
deny: function() {
if(settings.onDeny.call(element, $(this)) === false) {
module.verbose('Deny callback returned false cancelling hide');
return;
}
module.hide();
},
close: function() {
module.hide();
},
click: function(event) {
var
$target = $(event.target),
isInModal = ($target.closest(selector.modal).length > 0),
isInDOM = $.contains(document.documentElement, event.target)
;
if(!isInModal && isInDOM) {
module.debug('Dimmer clicked, hiding all modals');
if( module.is.active() ) {
module.remove.clickaway();
if(settings.allowMultiple) {
module.hide();
}
else {
module.hideAll();
}
}
}
},
debounce: function(method, delay) {
clearTimeout(module.timer);
module.timer = setTimeout(method, delay);
},
keyboard: function(event) {
var
keyCode = event.which,
escapeKey = 27
;
if(keyCode == escapeKey) {
if(settings.closable) {
module.debug('Escape key pressed hiding modal');
module.hide();
}
else {
module.debug('Escape key pressed, but closable is set to false');
}
event.preventDefault();
}
},
resize: function() {
if( $dimmable.dimmer('is active') ) {
requestAnimationFrame(module.refresh);
}
}
},
toggle: function() {
if( module.is.active() || module.is.animating() ) {
module.hide();
}
else {
module.show();
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.refreshModals();
module.showModal(callback);
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.refreshModals();
module.hideModal(callback);
},
showModal: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.animating() || !module.is.active() ) {
module.showDimmer();
module.cacheSizes();
module.set.position();
module.set.screenHeight();
module.set.type();
module.set.clickaway();
if( !settings.allowMultiple && module.others.active() ) {
module.hideOthers(module.showModal);
}
else {
settings.onShow.call(element);
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.debug('Showing modal with css animations');
$module
.transition({
debug : settings.debug,
animation : settings.transition + ' in',
queue : settings.queue,
duration : settings.duration,
useFailSafe : true,
onComplete : function() {
settings.onVisible.apply(element);
module.add.keyboardShortcuts();
module.save.focus();
module.set.active();
if(settings.autofocus) {
module.set.autofocus();
}
callback();
}
})
;
}
else {
module.error(error.noTransition);
}
}
}
else {
module.debug('Modal is already visible');
}
},
hideModal: function(callback, keepDimmed) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.debug('Hiding modal');
if(settings.onHide.call(element, $(this)) === false) {
module.verbose('Hide callback returned false cancelling hide');
return;
}
if( module.is.animating() || module.is.active() ) {
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.remove.active();
$module
.transition({
debug : settings.debug,
animation : settings.transition + ' out',
queue : settings.queue,
duration : settings.duration,
useFailSafe : true,
onStart : function() {
if(!module.others.active() && !keepDimmed) {
module.hideDimmer();
}
module.remove.keyboardShortcuts();
},
onComplete : function() {
settings.onHidden.call(element);
module.restore.focus();
callback();
}
})
;
}
else {
module.error(error.noTransition);
}
}
},
showDimmer: function() {
if($dimmable.dimmer('is animating') || !$dimmable.dimmer('is active') ) {
module.debug('Showing dimmer');
$dimmable.dimmer('show');
}
else {
module.debug('Dimmer already visible');
}
},
hideDimmer: function() {
if( $dimmable.dimmer('is animating') || ($dimmable.dimmer('is active')) ) {
$dimmable.dimmer('hide', function() {
module.remove.clickaway();
module.remove.screenHeight();
});
}
else {
module.debug('Dimmer is not visible cannot hide');
return;
}
},
hideAll: function(callback) {
var
$visibleModals = $allModals.filter('.' + className.active + ', .' + className.animating)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( $visibleModals.length > 0 ) {
module.debug('Hiding all visible modals');
module.hideDimmer();
$visibleModals
.modal('hide modal', callback)
;
}
},
hideOthers: function(callback) {
var
$visibleModals = $otherModals.filter('.' + className.active + ', .' + className.animating)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( $visibleModals.length > 0 ) {
module.debug('Hiding other modals', $otherModals);
$visibleModals
.modal('hide modal', callback, true)
;
}
},
others: {
active: function() {
return ($otherModals.filter('.' + className.active).length > 0);
},
animating: function() {
return ($otherModals.filter('.' + className.animating).length > 0);
}
},
add: {
keyboardShortcuts: function() {
module.verbose('Adding keyboard shortcuts');
$document
.on('keyup' + eventNamespace, module.event.keyboard)
;
}
},
save: {
focus: function() {
$focusedElement = $(document.activeElement).blur();
}
},
restore: {
focus: function() {
if($focusedElement && $focusedElement.length > 0) {
$focusedElement.focus();
}
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
clickaway: function() {
if(settings.closable) {
$dimmer
.off('click' + elementNamespace)
;
}
},
bodyStyle: function() {
if($body.attr('style') === '') {
module.verbose('Removing style attribute');
$body.removeAttr('style');
}
},
screenHeight: function() {
module.debug('Removing page height');
$body
.css('height', '')
;
},
keyboardShortcuts: function() {
module.verbose('Removing keyboard shortcuts');
$document
.off('keyup' + eventNamespace)
;
},
scrolling: function() {
$dimmable.removeClass(className.scrolling);
$module.removeClass(className.scrolling);
}
},
cacheSizes: function() {
var
modalHeight = $module.outerHeight()
;
if(module.cache === undefined || modalHeight !== 0) {
module.cache = {
pageHeight : $(document).outerHeight(),
height : modalHeight + settings.offset,
contextHeight : (settings.context == 'body')
? $(window).height()
: $dimmable.height()
};
}
module.debug('Caching modal and container sizes', module.cache);
},
can: {
fit: function() {
return ( ( module.cache.height + (settings.padding * 2) ) < module.cache.contextHeight);
}
},
is: {
active: function() {
return $module.hasClass(className.active);
},
animating: function() {
return $module.transition('is supported')
? $module.transition('is animating')
: $module.is(':visible')
;
},
scrolling: function() {
return $dimmable.hasClass(className.scrolling);
},
modernBrowser: function() {
// appName for IE11 reports 'Netscape' can no longer use
return !(window.ActiveXObject || "ActiveXObject" in window);
}
},
set: {
autofocus: function() {
var
$inputs = $module.find(':input').filter(':visible'),
$autofocus = $inputs.filter('[autofocus]'),
$input = ($autofocus.length > 0)
? $autofocus.first()
: $inputs.first()
;
if($input.length > 0) {
$input.focus();
}
},
clickaway: function() {
if(settings.closable) {
$dimmer
.on('click' + elementNamespace, module.event.click)
;
}
},
screenHeight: function() {
if( module.can.fit() ) {
$body.css('height', '');
}
else {
module.debug('Modal is taller than page content, resizing page height');
$body
.css('height', module.cache.height + (settings.padding * 2) )
;
}
},
active: function() {
$module.addClass(className.active);
},
scrolling: function() {
$dimmable.addClass(className.scrolling);
$module.addClass(className.scrolling);
},
type: function() {
if(module.can.fit()) {
module.verbose('Modal fits on screen');
if(!module.others.active() && !module.others.animating()) {
module.remove.scrolling();
}
}
else {
module.verbose('Modal cannot fit on screen setting to scrolling');
module.set.scrolling();
}
},
position: function() {
module.verbose('Centering modal on page', module.cache);
if(module.can.fit()) {
$module
.css({
top: '',
marginTop: -(module.cache.height / 2)
})
;
}
else {
$module
.css({
marginTop : '',
top : $document.scrollTop()
})
;
}
},
undetached: function() {
$dimmable.addClass(className.undetached);
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.modal.settings = {
name : 'Modal',
namespace : 'modal',
debug : false,
verbose : false,
performance : true,
observeChanges : false,
allowMultiple : false,
detachable : true,
closable : true,
autofocus : true,
inverted : false,
blurring : false,
dimmerSettings : {
closable : false,
useCSS : true
},
context : 'body',
queue : false,
duration : 500,
offset : 0,
transition : 'scale',
// padding with edge of page
padding : 50,
// called before show animation
onShow : function(){},
// called after show animation
onVisible : function(){},
// called before hide animation
onHide : function(){ return true; },
// called after hide animation
onHidden : function(){},
// called after approve selector match
onApprove : function(){ return true; },
// called after deny selector match
onDeny : function(){ return true; },
selector : {
close : '> .close',
approve : '.actions .positive, .actions .approve, .actions .ok',
deny : '.actions .negative, .actions .deny, .actions .cancel',
modal : '.ui.modal'
},
error : {
dimmer : 'UI Dimmer, a required component is not included in this page',
method : 'The method you called is not defined.',
notFound : 'The element you specified could not be found'
},
className : {
active : 'active',
animating : 'animating',
blurring : 'blurring',
scrolling : 'scrolling',
undetached : 'undetached'
}
};
})( jQuery, window, document );
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.2.0
* @link http://www.ag-grid.com/
* @license MIT
*/
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 __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 utils_1 = require("../utils");
var column_1 = require("../entities/column");
var rowNode_1 = require("../entities/rowNode");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var expressionService_1 = require("../expressionService");
var rowRenderer_1 = require("./rowRenderer");
var templateService_1 = require("../templateService");
var columnController_1 = require("../columnController/columnController");
var valueService_1 = require("../valueService");
var eventService_1 = require("../eventService");
var constants_1 = require("../constants");
var events_1 = require("../events");
var context_1 = require("../context/context");
var gridApi_1 = require("../gridApi");
var focusedCellController_1 = require("../focusedCellController");
var gridCell_1 = require("../entities/gridCell");
var focusService_1 = require("../misc/focusService");
var cellEditorFactory_1 = require("./cellEditorFactory");
var component_1 = require("../widgets/component");
var popupService_1 = require("../widgets/popupService");
var cellRendererFactory_1 = require("./cellRendererFactory");
var cellRendererService_1 = require("./cellRendererService");
var valueFormatterService_1 = require("./valueFormatterService");
var checkboxSelectionComponent_1 = require("./checkboxSelectionComponent");
var setLeftFeature_1 = require("./features/setLeftFeature");
var RenderedCell = (function (_super) {
__extends(RenderedCell, _super);
function RenderedCell(column, node, rowIndex, scope, renderedRow) {
_super.call(this, '<div/>');
this.firstRightPinned = false;
this.lastLeftPinned = false;
// because we reference eGridCell everywhere in this class,
// we keep a local reference
this.eGridCell = this.getGui();
this.column = column;
this.node = node;
this.rowIndex = rowIndex;
this.scope = scope;
this.renderedRow = renderedRow;
this.gridCell = new gridCell_1.GridCell(rowIndex, node.floating, column);
}
RenderedCell.prototype.destroy = function () {
_super.prototype.destroy.call(this);
if (this.cellEditor && this.cellEditor.destroy) {
this.cellEditor.destroy();
}
if (this.cellRenderer && this.cellRenderer.destroy) {
this.cellRenderer.destroy();
}
};
RenderedCell.prototype.setPinnedClasses = function () {
var _this = this;
var firstPinnedChangedListener = function () {
if (_this.firstRightPinned !== _this.column.isFirstRightPinned()) {
_this.firstRightPinned = _this.column.isFirstRightPinned();
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-first-right-pinned', _this.firstRightPinned);
}
if (_this.lastLeftPinned !== _this.column.isLastLeftPinned()) {
_this.lastLeftPinned = _this.column.isLastLeftPinned();
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-last-left-pinned', _this.lastLeftPinned);
}
};
this.column.addEventListener(column_1.Column.EVENT_FIRST_RIGHT_PINNED_CHANGED, firstPinnedChangedListener);
this.column.addEventListener(column_1.Column.EVENT_LAST_LEFT_PINNED_CHANGED, firstPinnedChangedListener);
this.addDestroyFunc(function () {
_this.column.removeEventListener(column_1.Column.EVENT_FIRST_RIGHT_PINNED_CHANGED, firstPinnedChangedListener);
_this.column.removeEventListener(column_1.Column.EVENT_LAST_LEFT_PINNED_CHANGED, firstPinnedChangedListener);
});
firstPinnedChangedListener();
};
RenderedCell.prototype.getParentRow = function () {
return this.eParentRow;
};
RenderedCell.prototype.setParentRow = function (eParentRow) {
this.eParentRow = eParentRow;
};
RenderedCell.prototype.calculateCheckboxSelection = function () {
// never allow selection on floating rows
if (this.node.floating) {
return false;
}
// if boolean set, then just use it
var colDef = this.column.getColDef();
if (typeof colDef.checkboxSelection === 'boolean') {
return colDef.checkboxSelection;
}
// if function, then call the function to find out. we first check colDef for
// a function, and if missing then check gridOptions, so colDef has precedence
var selectionFunc;
if (typeof colDef.checkboxSelection === 'function') {
selectionFunc = colDef.checkboxSelection;
}
if (!selectionFunc && this.gridOptionsWrapper.getCheckboxSelection()) {
selectionFunc = this.gridOptionsWrapper.getCheckboxSelection();
}
if (selectionFunc) {
var params = this.createParams();
return selectionFunc(params);
}
return false;
};
RenderedCell.prototype.getColumn = function () {
return this.column;
};
RenderedCell.prototype.getValue = function () {
var data = this.getDataForRow();
return this.valueService.getValueUsingSpecificData(this.column, data, this.node);
};
RenderedCell.prototype.getDataForRow = function () {
if (this.node.footer) {
// if footer, we always show the data
return this.node.data;
}
else if (this.node.group) {
// if header and header is expanded, we show data in footer only
var footersEnabled = this.gridOptionsWrapper.isGroupIncludeFooter();
var suppressHideHeader = this.gridOptionsWrapper.isGroupSuppressBlankHeader();
if (this.node.expanded && footersEnabled && !suppressHideHeader) {
return undefined;
}
else {
return this.node.data;
}
}
else {
// otherwise it's a normal node, just return data as normal
return this.node.data;
}
};
RenderedCell.prototype.addRangeSelectedListener = function () {
var _this = this;
if (!this.rangeController) {
return;
}
var rangeCountLastTime = 0;
var rangeSelectedListener = function () {
var rangeCount = _this.rangeController.getCellRangeCount(_this.gridCell);
if (rangeCountLastTime !== rangeCount) {
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-range-selected', rangeCount !== 0);
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-range-selected-1', rangeCount === 1);
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-range-selected-2', rangeCount === 2);
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-range-selected-3', rangeCount === 3);
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-range-selected-4', rangeCount >= 4);
rangeCountLastTime = rangeCount;
}
};
this.eventService.addEventListener(events_1.Events.EVENT_RANGE_SELECTION_CHANGED, rangeSelectedListener);
this.addDestroyFunc(function () {
_this.eventService.removeEventListener(events_1.Events.EVENT_RANGE_SELECTION_CHANGED, rangeSelectedListener);
});
rangeSelectedListener();
};
RenderedCell.prototype.addHighlightListener = function () {
var _this = this;
if (!this.rangeController) {
return;
}
var clipboardListener = function (event) {
var cellId = _this.gridCell.createId();
var shouldFlash = event.cells[cellId];
if (shouldFlash) {
_this.animateCellWithHighlight();
}
};
this.eventService.addEventListener(events_1.Events.EVENT_FLASH_CELLS, clipboardListener);
this.addDestroyFunc(function () {
_this.eventService.removeEventListener(events_1.Events.EVENT_FLASH_CELLS, clipboardListener);
});
};
RenderedCell.prototype.addChangeListener = function () {
var _this = this;
var cellChangeListener = function (event) {
if (event.column === _this.column) {
_this.refreshCell();
_this.animateCellWithDataChanged();
}
};
this.addDestroyableEventListener(this.node, rowNode_1.RowNode.EVENT_CELL_CHANGED, cellChangeListener);
};
RenderedCell.prototype.animateCellWithDataChanged = function () {
if (this.gridOptionsWrapper.isEnableCellChangeFlash() || this.column.getColDef().enableCellChangeFlash) {
this.animateCell('data-changed');
}
};
RenderedCell.prototype.animateCellWithHighlight = function () {
this.animateCell('highlight');
};
RenderedCell.prototype.animateCell = function (cssName) {
var _this = this;
var fullName = 'ag-cell-' + cssName;
var animationFullName = 'ag-cell-' + cssName + '-animation';
// we want to highlight the cells, without any animation
utils_1.Utils.addCssClass(this.eGridCell, fullName);
utils_1.Utils.removeCssClass(this.eGridCell, animationFullName);
// then once that is applied, we remove the highlight with animation
setTimeout(function () {
utils_1.Utils.removeCssClass(_this.eGridCell, fullName);
utils_1.Utils.addCssClass(_this.eGridCell, animationFullName);
setTimeout(function () {
// and then to leave things as we got them, we remove the animation
utils_1.Utils.removeCssClass(_this.eGridCell, animationFullName);
}, 1000);
}, 500);
};
RenderedCell.prototype.addCellFocusedListener = function () {
var _this = this;
// set to null, not false, as we need to set 'ag-cell-no-focus' first time around
var cellFocusedLastTime = null;
var cellFocusedListener = function (event) {
var cellFocused = _this.focusedCellController.isCellFocused(_this.gridCell);
// see if we need to change the classes on this cell
if (cellFocused !== cellFocusedLastTime) {
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-focus', cellFocused);
utils_1.Utils.addOrRemoveCssClass(_this.eGridCell, 'ag-cell-no-focus', !cellFocused);
cellFocusedLastTime = cellFocused;
}
// if this cell was just focused, see if we need to force browser focus, his can
// happen if focus is programmatically set.
if (cellFocused && event && event.forceBrowserFocus) {
_this.eGridCell.focus();
}
// if another cell was focused, and we are editing, then stop editing
if (_this.editingCell && !cellFocused) {
_this.stopEditing();
}
};
this.eventService.addEventListener(events_1.Events.EVENT_CELL_FOCUSED, cellFocusedListener);
this.addDestroyFunc(function () {
_this.eventService.removeEventListener(events_1.Events.EVENT_CELL_FOCUSED, cellFocusedListener);
});
cellFocusedListener();
};
RenderedCell.prototype.setWidthOnCell = function () {
var _this = this;
var widthChangedListener = function () {
_this.eGridCell.style.width = _this.column.getActualWidth() + "px";
};
this.column.addEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener);
this.addDestroyFunc(function () {
_this.column.removeEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener);
});
widthChangedListener();
};
RenderedCell.prototype.init = function () {
this.value = this.getValue();
this.checkboxSelection = this.calculateCheckboxSelection();
this.setWidthOnCell();
this.setPinnedClasses();
this.addRangeSelectedListener();
this.addHighlightListener();
this.addChangeListener();
this.addCellFocusedListener();
this.addKeyDownListener();
this.addKeyPressListener();
// this.addFocusListener();
var setLeftFeature = new setLeftFeature_1.SetLeftFeature(this.column, this.eGridCell);
this.addDestroyFunc(setLeftFeature.destroy.bind(setLeftFeature));
// only set tab index if cell selection is enabled
if (!this.gridOptionsWrapper.isSuppressCellSelection()) {
this.eGridCell.setAttribute("tabindex", "-1");
}
// these are the grid styles, don't change between soft refreshes
this.addClasses();
this.setInlineEditingClass();
this.createParentOfValue();
this.populateCell();
};
RenderedCell.prototype.onEnterKeyDown = function () {
if (this.editingCell) {
this.stopEditing();
this.focusCell(true);
}
else {
this.startEditingIfEnabled(constants_1.Constants.KEY_ENTER);
}
};
RenderedCell.prototype.onF2KeyDown = function () {
if (!this.editingCell) {
this.startEditingIfEnabled(constants_1.Constants.KEY_F2);
}
};
RenderedCell.prototype.onEscapeKeyDown = function () {
if (this.editingCell) {
this.stopEditing(true);
this.focusCell(true);
}
};
RenderedCell.prototype.onPopupEditorClosed = function () {
if (this.editingCell) {
this.stopEditing(true);
// we only focus cell again if this cell is still focused. it is possible
// it is not focused if the user cancelled the edit by clicking on another
// cell outside of this one
if (this.focusedCellController.isCellFocused(this.gridCell)) {
this.focusCell(true);
}
}
};
RenderedCell.prototype.onTabKeyDown = function (event) {
var editNextCell;
if (this.editingCell) {
// if editing, we stop editing, then start editing next cell
this.stopEditing();
editNextCell = true;
}
else {
// otherwise we just move to the next cell
editNextCell = false;
}
var foundCell = this.rowRenderer.moveFocusToNextCell(this.rowIndex, this.column, this.node.floating, event.shiftKey, editNextCell);
// only prevent default if we found a cell. so if user is on last cell and hits tab, then we default
// to the normal tabbing so user can exit the grid.
if (foundCell) {
event.preventDefault();
}
};
RenderedCell.prototype.onBackspaceOrDeleteKeyPressed = function (key) {
if (!this.editingCell) {
this.startEditingIfEnabled(key);
}
};
RenderedCell.prototype.onSpaceKeyPressed = function (event) {
if (!this.editingCell && this.gridOptionsWrapper.isRowSelection()) {
var selected = this.node.isSelected();
this.node.setSelected(!selected);
}
// prevent default as space key, by default, moves browser scroll down
event.preventDefault();
};
RenderedCell.prototype.onNavigationKeyPressed = function (event, key) {
if (this.editingCell) {
this.stopEditing();
}
this.rowRenderer.navigateToNextCell(key, this.rowIndex, this.column, this.node.floating);
// if we don't prevent default, the grid will scroll with the navigation keys
event.preventDefault();
};
RenderedCell.prototype.addKeyPressListener = function () {
var _this = this;
var keyPressListener = function (event) {
// check this, in case focus is on a (for example) a text field inside the cell,
// in which cse we should not be listening for these key pressed
var eventTarget = utils_1.Utils.getTarget(event);
var eventOnChildComponent = eventTarget !== _this.getGui();
if (eventOnChildComponent) {
return;
}
if (!_this.editingCell) {
var pressedChar = String.fromCharCode(event.charCode);
if (pressedChar === ' ') {
_this.onSpaceKeyPressed(event);
}
else {
if (RenderedCell.PRINTABLE_CHARACTERS.indexOf(pressedChar) >= 0) {
_this.startEditingIfEnabled(null, pressedChar);
// if we don't prevent default, then the keypress also gets applied to the text field
// (at least when doing the default editor), but we need to allow the editor to decide
// what it wants to do. we only do this IF editing was started - otherwise it messes
// up when the use is not doing editing, but using rendering with text fields in cellRenderer
// (as it would block the the user from typing into text fields).
event.preventDefault();
}
}
}
};
this.eGridCell.addEventListener('keypress', keyPressListener);
this.addDestroyFunc(function () {
_this.eGridCell.removeEventListener('keypress', keyPressListener);
});
};
RenderedCell.prototype.onKeyDown = function (event) {
var key = event.which || event.keyCode;
switch (key) {
case constants_1.Constants.KEY_ENTER:
this.onEnterKeyDown();
break;
case constants_1.Constants.KEY_F2:
this.onF2KeyDown();
break;
case constants_1.Constants.KEY_ESCAPE:
this.onEscapeKeyDown();
break;
case constants_1.Constants.KEY_TAB:
this.onTabKeyDown(event);
break;
case constants_1.Constants.KEY_BACKSPACE:
case constants_1.Constants.KEY_DELETE:
this.onBackspaceOrDeleteKeyPressed(key);
break;
case constants_1.Constants.KEY_DOWN:
case constants_1.Constants.KEY_UP:
case constants_1.Constants.KEY_RIGHT:
case constants_1.Constants.KEY_LEFT:
this.onNavigationKeyPressed(event, key);
break;
}
};
RenderedCell.prototype.addKeyDownListener = function () {
var _this = this;
var editingKeyListener = this.onKeyDown.bind(this);
this.eGridCell.addEventListener('keydown', editingKeyListener);
this.addDestroyFunc(function () {
_this.eGridCell.removeEventListener('keydown', editingKeyListener);
});
};
RenderedCell.prototype.createCellEditor = function (keyPress, charPress) {
var colDef = this.column.getColDef();
var cellEditor = this.cellEditorFactory.createCellEditor(colDef.cellEditor);
if (cellEditor.init) {
var params = {
value: this.getValue(),
keyPress: keyPress,
charPress: charPress,
column: this.column,
node: this.node,
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext(),
onKeyDown: this.onKeyDown.bind(this),
stopEditing: this.stopEditingAndFocus.bind(this),
eGridCell: this.eGridCell
};
if (colDef.cellEditorParams) {
utils_1.Utils.assign(params, colDef.cellEditorParams);
}
if (cellEditor.init) {
cellEditor.init(params);
}
}
return cellEditor;
};
// cell editors call this, when they want to stop for reasons other
// than what we pick up on. eg selecting from a dropdown ends editing.
RenderedCell.prototype.stopEditingAndFocus = function () {
this.stopEditing();
this.focusCell(true);
};
// called by rowRenderer when user navigates via tab key
RenderedCell.prototype.startEditingIfEnabled = function (keyPress, charPress) {
if (!this.isCellEditable()) {
return;
}
var cellEditor = this.createCellEditor(keyPress, charPress);
if (cellEditor.isCancelBeforeStart && cellEditor.isCancelBeforeStart()) {
if (cellEditor.destroy) {
cellEditor.destroy();
}
return;
}
if (!cellEditor.getGui) {
console.warn("ag-Grid: cellEditor for column " + this.column.getId() + " is missing getGui() method");
return;
}
this.cellEditor = cellEditor;
this.editingCell = true;
this.cellEditorInPopup = this.cellEditor.isPopup && this.cellEditor.isPopup();
this.setInlineEditingClass();
if (this.cellEditorInPopup) {
this.addPopupCellEditor();
}
else {
this.addInCellEditor();
}
if (cellEditor.afterGuiAttached) {
cellEditor.afterGuiAttached();
}
};
RenderedCell.prototype.addInCellEditor = function () {
utils_1.Utils.removeAllChildren(this.eGridCell);
this.eGridCell.appendChild(this.cellEditor.getGui());
if (this.gridOptionsWrapper.isAngularCompileRows()) {
this.$compile(this.eGridCell)(this.scope);
}
};
RenderedCell.prototype.addPopupCellEditor = function () {
var _this = this;
var ePopupGui = this.cellEditor.getGui();
this.hideEditorPopup = this.popupService.addAsModalPopup(ePopupGui, true,
// callback for when popup disappears
function () {
// we only call stopEditing if we are editing, as
// it's possible the popup called 'stop editing'
// before this, eg if 'enter key' was pressed on
// the editor
if (_this.editingCell) {
_this.onPopupEditorClosed();
}
});
this.popupService.positionPopupOverComponent({
eventSource: this.eGridCell,
ePopup: ePopupGui,
keepWithinBounds: true
});
if (this.gridOptionsWrapper.isAngularCompileRows()) {
this.$compile(ePopupGui)(this.scope);
}
};
RenderedCell.prototype.focusCell = function (forceBrowserFocus) {
this.focusedCellController.setFocusedCell(this.rowIndex, this.column, this.node.floating, forceBrowserFocus);
};
// pass in 'true' to cancel the editing.
RenderedCell.prototype.stopEditing = function (cancel) {
if (cancel === void 0) { cancel = false; }
if (!this.editingCell) {
return;
}
this.editingCell = false;
// also have another option here to cancel after editing, so for example user could have a popup editor and
// it is closed by user clicking outside the editor. then the editor will close automatically (with false
// passed above) and we need to see if the editor wants to accept the new value.
var cancelAfterEnd = this.cellEditor.isCancelAfterEnd && this.cellEditor.isCancelAfterEnd();
var acceptNewValue = !cancel && !cancelAfterEnd;
if (acceptNewValue) {
var newValue = this.cellEditor.getValue();
this.valueService.setValue(this.node, this.column, newValue);
this.value = this.getValue();
}
if (this.cellEditor.destroy) {
this.cellEditor.destroy();
}
if (this.cellEditorInPopup) {
this.hideEditorPopup();
this.hideEditorPopup = null;
}
else {
utils_1.Utils.removeAllChildren(this.eGridCell);
// put the cell back the way it was before editing
if (this.checkboxSelection) {
// if wrapper, then put the wrapper back
this.eGridCell.appendChild(this.eCellWrapper);
}
else {
// if cellRenderer, then put the gui back in. if the renderer has
// a refresh, it will be called. however if it doesn't, then later
// the renderer will be destroyed and a new one will be created.
if (this.cellRenderer) {
this.eGridCell.appendChild(this.cellRenderer.getGui());
}
}
}
this.setInlineEditingClass();
this.refreshCell();
};
RenderedCell.prototype.createParams = function () {
var params = {
node: this.node,
data: this.node.data,
value: this.value,
rowIndex: this.rowIndex,
colDef: this.column.getColDef(),
$scope: this.scope,
context: this.gridOptionsWrapper.getContext(),
api: this.gridApi,
columnApi: this.columnApi
};
return params;
};
RenderedCell.prototype.createEvent = function (event) {
var agEvent = this.createParams();
agEvent.event = event;
return agEvent;
};
RenderedCell.prototype.isCellEditable = function () {
if (this.editingCell) {
return false;
}
// never allow editing of groups
if (this.node.group) {
return false;
}
return this.column.isCellEditable(this.node);
};
RenderedCell.prototype.onMouseEvent = function (eventName, mouseEvent) {
switch (eventName) {
case 'click':
this.onCellClicked(mouseEvent);
break;
case 'mousedown':
this.onMouseDown();
break;
case 'dblclick':
this.onCellDoubleClicked(mouseEvent);
break;
case 'contextmenu':
this.onContextMenu(mouseEvent);
break;
}
};
RenderedCell.prototype.onContextMenu = function (mouseEvent) {
// to allow us to debug in chrome, we ignore the event if ctrl is pressed,
// thus the normal menu is displayed
if (mouseEvent.ctrlKey || mouseEvent.metaKey) {
return;
}
var colDef = this.column.getColDef();
var agEvent = this.createEvent(mouseEvent);
this.eventService.dispatchEvent(events_1.Events.EVENT_CELL_CONTEXT_MENU, agEvent);
if (colDef.onCellContextMenu) {
colDef.onCellContextMenu(agEvent);
}
if (this.contextMenuFactory && !this.gridOptionsWrapper.isSuppressContextMenu()) {
this.contextMenuFactory.showMenu(this.node, this.column, this.value, mouseEvent);
mouseEvent.preventDefault();
}
};
RenderedCell.prototype.onCellDoubleClicked = function (mouseEvent) {
var colDef = this.column.getColDef();
// always dispatch event to eventService
var agEvent = this.createEvent(mouseEvent);
this.eventService.dispatchEvent(events_1.Events.EVENT_CELL_DOUBLE_CLICKED, agEvent);
// check if colDef also wants to handle event
if (typeof colDef.onCellDoubleClicked === 'function') {
colDef.onCellDoubleClicked(agEvent);
}
if (!this.gridOptionsWrapper.isSingleClickEdit()) {
this.startEditingIfEnabled();
}
};
RenderedCell.prototype.onMouseDown = function () {
// we pass false to focusCell, as we don't want the cell to focus
// also get the browser focus. if we did, then the cellRenderer could
// have a text field in it, for example, and as the user clicks on the
// text field, the text field, the focus doesn't get to the text
// field, instead to goes to the div behind, making it impossible to
// select the text field.
this.focusCell(false);
// if it's a right click, then if the cell is already in range,
// don't change the range, however if the cell is not in a range,
// we set a new range
if (this.rangeController) {
var thisCell = this.gridCell;
var cellAlreadyInRange = this.rangeController.isCellInAnyRange(thisCell);
if (!cellAlreadyInRange) {
this.rangeController.setRangeToCell(thisCell);
}
}
};
RenderedCell.prototype.onCellClicked = function (mouseEvent) {
var agEvent = this.createEvent(mouseEvent);
this.eventService.dispatchEvent(events_1.Events.EVENT_CELL_CLICKED, agEvent);
var colDef = this.column.getColDef();
if (colDef.onCellClicked) {
colDef.onCellClicked(agEvent);
}
if (this.gridOptionsWrapper.isSingleClickEdit()) {
this.startEditingIfEnabled();
}
};
// if we are editing inline, then we don't have the padding in the cell (set in the themes)
// to allow the text editor full access to the entire cell
RenderedCell.prototype.setInlineEditingClass = function () {
var editingInline = this.editingCell && !this.cellEditorInPopup;
utils_1.Utils.addOrRemoveCssClass(this.eGridCell, 'ag-cell-inline-editing', editingInline);
utils_1.Utils.addOrRemoveCssClass(this.eGridCell, 'ag-cell-not-inline-editing', !editingInline);
};
RenderedCell.prototype.populateCell = function () {
// populate
this.putDataIntoCell();
// style
this.addStylesFromColDef();
this.addClassesFromColDef();
this.addClassesFromRules();
};
RenderedCell.prototype.addStylesFromColDef = function () {
var colDef = this.column.getColDef();
if (colDef.cellStyle) {
var cssToUse;
if (typeof colDef.cellStyle === 'function') {
var cellStyleParams = {
value: this.value,
data: this.node.data,
node: this.node,
colDef: colDef,
column: this.column,
$scope: this.scope,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
var cellStyleFunc = colDef.cellStyle;
cssToUse = cellStyleFunc(cellStyleParams);
}
else {
cssToUse = colDef.cellStyle;
}
if (cssToUse) {
utils_1.Utils.addStylesToElement(this.eGridCell, cssToUse);
}
}
};
RenderedCell.prototype.addClassesFromColDef = function () {
var _this = this;
var colDef = this.column.getColDef();
if (colDef.cellClass) {
var classToUse;
if (typeof colDef.cellClass === 'function') {
var cellClassParams = {
value: this.value,
data: this.node.data,
node: this.node,
colDef: colDef,
$scope: this.scope,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
var cellClassFunc = colDef.cellClass;
classToUse = cellClassFunc(cellClassParams);
}
else {
classToUse = colDef.cellClass;
}
if (typeof classToUse === 'string') {
utils_1.Utils.addCssClass(this.eGridCell, classToUse);
}
else if (Array.isArray(classToUse)) {
classToUse.forEach(function (cssClassItem) {
utils_1.Utils.addCssClass(_this.eGridCell, cssClassItem);
});
}
}
};
RenderedCell.prototype.addClassesFromRules = function () {
var colDef = this.column.getColDef();
var classRules = colDef.cellClassRules;
if (typeof classRules === 'object' && classRules !== null) {
var params = {
value: this.value,
data: this.node.data,
node: this.node,
colDef: colDef,
rowIndex: this.rowIndex,
api: this.gridOptionsWrapper.getApi(),
context: this.gridOptionsWrapper.getContext()
};
var classNames = Object.keys(classRules);
for (var i = 0; i < classNames.length; i++) {
var className = classNames[i];
var rule = classRules[className];
var resultOfRule;
if (typeof rule === 'string') {
resultOfRule = this.expressionService.evaluate(rule, params);
}
else if (typeof rule === 'function') {
resultOfRule = rule(params);
}
if (resultOfRule) {
utils_1.Utils.addCssClass(this.eGridCell, className);
}
else {
utils_1.Utils.removeCssClass(this.eGridCell, className);
}
}
}
};
RenderedCell.prototype.createParentOfValue = function () {
if (this.checkboxSelection) {
this.eCellWrapper = document.createElement('span');
utils_1.Utils.addCssClass(this.eCellWrapper, 'ag-cell-wrapper');
this.eGridCell.appendChild(this.eCellWrapper);
var cbSelectionComponent = new checkboxSelectionComponent_1.CheckboxSelectionComponent();
this.context.wireBean(cbSelectionComponent);
cbSelectionComponent.init({ rowNode: this.node });
this.eCellWrapper.appendChild(cbSelectionComponent.getGui());
this.addDestroyFunc(function () { return cbSelectionComponent.destroy(); });
// eventually we call eSpanWithValue.innerHTML = xxx, so cannot include the checkbox (above) in this span
this.eSpanWithValue = document.createElement('span');
utils_1.Utils.addCssClass(this.eSpanWithValue, 'ag-cell-value');
this.eCellWrapper.appendChild(this.eSpanWithValue);
this.eParentOfValue = this.eSpanWithValue;
}
else {
utils_1.Utils.addCssClass(this.eGridCell, 'ag-cell-value');
this.eParentOfValue = this.eGridCell;
}
};
RenderedCell.prototype.isVolatile = function () {
return this.column.getColDef().volatile;
};
RenderedCell.prototype.refreshCell = function (animate, newData) {
if (animate === void 0) { animate = false; }
if (newData === void 0) { newData = false; }
this.value = this.getValue();
// if it's 'new data', then we don't refresh the cellRenderer, even if refresh method is available.
// this is because if the whole data is new (ie we are showing stock price 'BBA' now and not 'SSD')
// then we are not showing a movement in the stock price, rather we are showing different stock.
if (!newData && this.cellRenderer && this.cellRenderer.refresh) {
// if the cell renderer has a refresh method, we call this instead of doing a refresh
// note: should pass in params here instead of value?? so that client has formattedValue
var valueFormatted = this.formatValue(this.value);
var cellRendererParams = this.column.getColDef().cellRendererParams;
var params = this.createRendererAndRefreshParams(valueFormatted, cellRendererParams);
this.cellRenderer.refresh(params);
// need to check rules. note, we ignore colDef classes and styles, these are assumed to be static
this.addClassesFromRules();
}
else {
// otherwise we rip out the cell and replace it
utils_1.Utils.removeAllChildren(this.eParentOfValue);
// remove old renderer component if it exists
if (this.cellRenderer && this.cellRenderer.destroy) {
this.cellRenderer.destroy();
}
this.cellRenderer = null;
this.populateCell();
// if angular compiling, then need to also compile the cell again (angular compiling sucks, please wait...)
if (this.gridOptionsWrapper.isAngularCompileRows()) {
this.$compile(this.eGridCell)(this.scope);
}
}
if (animate) {
this.animateCellWithDataChanged();
}
};
RenderedCell.prototype.putDataIntoCell = function () {
// template gets preference, then cellRenderer, then do it ourselves
var colDef = this.column.getColDef();
var valueFormatted = this.valueFormatterService.formatValue(this.column, this.node, this.scope, this.rowIndex, this.value);
if (colDef.template) {
// template is really only used for angular 1 - as people using ng1 are used to providing templates with
// bindings in it. in ng2, people will hopefully want to provide components, not templates.
this.eParentOfValue.innerHTML = colDef.template;
}
else if (colDef.templateUrl) {
// likewise for templateUrl - it's for ng1 really - when we move away from ng1, we can take these out.
// niall was pro angular 1 when writing template and templateUrl, if writing from scratch now, would
// not do these, but would follow a pattern that was friendly towards components, not templates.
var template = this.templateService.getTemplate(colDef.templateUrl, this.refreshCell.bind(this, true));
if (template) {
this.eParentOfValue.innerHTML = template;
}
}
else if (colDef.floatingCellRenderer && this.node.floating) {
// if floating, then give preference to floating cell renderer
this.useCellRenderer(colDef.floatingCellRenderer, colDef.floatingCellRendererParams, valueFormatted);
}
else if (colDef.cellRenderer) {
// use normal cell renderer
this.useCellRenderer(colDef.cellRenderer, colDef.cellRendererParams, valueFormatted);
}
else {
// if we insert undefined, then it displays as the string 'undefined', ugly!
var valueToRender = utils_1.Utils.exists(valueFormatted) ? valueFormatted : this.value;
if (utils_1.Utils.exists(valueToRender) && valueToRender !== '') {
// not using innerHTML to prevent injection of HTML
// https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations
this.eParentOfValue.textContent = valueToRender.toString();
}
}
if (colDef.tooltipField) {
var data = this.getDataForRow();
if (utils_1.Utils.exists(data)) {
var tooltip = data[colDef.tooltipField];
this.eParentOfValue.setAttribute('title', tooltip);
}
}
};
RenderedCell.prototype.formatValue = function (value) {
return this.valueFormatterService.formatValue(this.column, this.node, this.scope, this.rowIndex, value);
};
RenderedCell.prototype.createRendererAndRefreshParams = function (valueFormatted, cellRendererParams) {
var params = {
value: this.value,
valueFormatted: valueFormatted,
valueGetter: this.getValue,
formatValue: this.formatValue.bind(this),
data: this.node.data,
node: this.node,
colDef: this.column.getColDef(),
column: this.column,
$scope: this.scope,
rowIndex: this.rowIndex,
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext(),
refreshCell: this.refreshCell.bind(this),
eGridCell: this.eGridCell,
eParentOfValue: this.eParentOfValue,
addRenderedRowListener: this.renderedRow.addEventListener.bind(this.renderedRow)
};
if (cellRendererParams) {
utils_1.Utils.assign(params, cellRendererParams);
}
return params;
};
RenderedCell.prototype.useCellRenderer = function (cellRendererKey, cellRendererParams, valueFormatted) {
var params = this.createRendererAndRefreshParams(valueFormatted, cellRendererParams);
this.cellRenderer = this.cellRendererService.useCellRenderer(cellRendererKey, this.eParentOfValue, params);
};
RenderedCell.prototype.addClasses = function () {
utils_1.Utils.addCssClass(this.eGridCell, 'ag-cell');
this.eGridCell.setAttribute("colId", this.column.getColId());
if (this.node.group && this.node.footer) {
utils_1.Utils.addCssClass(this.eGridCell, 'ag-footer-cell');
}
if (this.node.group && !this.node.footer) {
utils_1.Utils.addCssClass(this.eGridCell, 'ag-group-cell');
}
};
RenderedCell.PRINTABLE_CHARACTERS = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!"£$%^&*()_+-=[];\'#,./\|<>?:@~{}';
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], RenderedCell.prototype, "context", void 0);
__decorate([
context_1.Autowired('columnApi'),
__metadata('design:type', columnController_1.ColumnApi)
], RenderedCell.prototype, "columnApi", void 0);
__decorate([
context_1.Autowired('gridApi'),
__metadata('design:type', gridApi_1.GridApi)
], RenderedCell.prototype, "gridApi", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], RenderedCell.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('expressionService'),
__metadata('design:type', expressionService_1.ExpressionService)
], RenderedCell.prototype, "expressionService", void 0);
__decorate([
context_1.Autowired('rowRenderer'),
__metadata('design:type', rowRenderer_1.RowRenderer)
], RenderedCell.prototype, "rowRenderer", void 0);
__decorate([
context_1.Autowired('$compile'),
__metadata('design:type', Object)
], RenderedCell.prototype, "$compile", void 0);
__decorate([
context_1.Autowired('templateService'),
__metadata('design:type', templateService_1.TemplateService)
], RenderedCell.prototype, "templateService", void 0);
__decorate([
context_1.Autowired('valueService'),
__metadata('design:type', valueService_1.ValueService)
], RenderedCell.prototype, "valueService", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata('design:type', eventService_1.EventService)
], RenderedCell.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], RenderedCell.prototype, "columnController", void 0);
__decorate([
context_1.Optional('rangeController'),
__metadata('design:type', Object)
], RenderedCell.prototype, "rangeController", void 0);
__decorate([
context_1.Autowired('focusedCellController'),
__metadata('design:type', focusedCellController_1.FocusedCellController)
], RenderedCell.prototype, "focusedCellController", void 0);
__decorate([
context_1.Optional('contextMenuFactory'),
__metadata('design:type', Object)
], RenderedCell.prototype, "contextMenuFactory", void 0);
__decorate([
context_1.Autowired('focusService'),
__metadata('design:type', focusService_1.FocusService)
], RenderedCell.prototype, "focusService", void 0);
__decorate([
context_1.Autowired('cellEditorFactory'),
__metadata('design:type', cellEditorFactory_1.CellEditorFactory)
], RenderedCell.prototype, "cellEditorFactory", void 0);
__decorate([
context_1.Autowired('cellRendererFactory'),
__metadata('design:type', cellRendererFactory_1.CellRendererFactory)
], RenderedCell.prototype, "cellRendererFactory", void 0);
__decorate([
context_1.Autowired('popupService'),
__metadata('design:type', popupService_1.PopupService)
], RenderedCell.prototype, "popupService", void 0);
__decorate([
context_1.Autowired('cellRendererService'),
__metadata('design:type', cellRendererService_1.CellRendererService)
], RenderedCell.prototype, "cellRendererService", void 0);
__decorate([
context_1.Autowired('valueFormatterService'),
__metadata('design:type', valueFormatterService_1.ValueFormatterService)
], RenderedCell.prototype, "valueFormatterService", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], RenderedCell.prototype, "init", null);
return RenderedCell;
})(component_1.Component);
exports.RenderedCell = RenderedCell;
|
#!/usr/bin/env node
// TODO(vojta): pre-commit hook for validating messages
// TODO(vojta): report errors, currently Q silence everything which really sucks
var child = require('child_process');
var fs = require('fs');
var util = require('util');
var q = require('qq');
var GIT_LOG_CMD = 'git log --grep="%s" -E --format=%s %s..HEAD';
var GIT_TAG_CMD = 'git describe --tags --abbrev=0';
var HEADER_TPL = '<a name="%s"></a>\n# %s (%s)\n\n';
var LINK_ISSUE = '[#%s](https://github.com/angular/angular.js/issues/%s)';
var LINK_COMMIT = '[%s](https://github.com/angular/angular.js/commit/%s)';
var EMPTY_COMPONENT = '$$';
var warn = function() {
console.log('WARNING:', util.format.apply(null, arguments));
};
var parseRawCommit = function(raw) {
if (!raw) return null;
var lines = raw.split('\n');
var msg = {}, match;
msg.hash = lines.shift();
msg.subject = lines.shift();
msg.closes = [];
msg.breaks = [];
lines.forEach(function(line) {
match = line.match(/(?:Closes|Fixes)\s#(\d+)/);
if (match) msg.closes.push(parseInt(match[1]));
});
match = raw.match(/BREAKING CHANGE:([\s\S]*)/);
if (match) {
msg.breaking = match[1];
}
msg.body = lines.join('\n');
match = msg.subject.match(/^(.*)\((.*)\)\:\s(.*)$/);
if (!match || !match[1] || !match[3]) {
warn('Incorrect message: %s %s', msg.hash, msg.subject);
return null;
}
msg.type = match[1];
msg.component = match[2];
msg.subject = match[3];
return msg;
};
var linkToIssue = function(issue) {
return util.format(LINK_ISSUE, issue, issue);
};
var linkToCommit = function(hash) {
return util.format(LINK_COMMIT, hash.substr(0, 8), hash);
};
var currentDate = function() {
var now = new Date();
var pad = function(i) {
return ('0' + i).substr(-2);
};
return util.format('%d-%s-%s', now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate()));
};
var printSection = function(stream, title, section, printCommitLinks) {
printCommitLinks = printCommitLinks === undefined ? true : printCommitLinks;
var components = Object.getOwnPropertyNames(section).sort();
if (!components.length) return;
stream.write(util.format('\n## %s\n\n', title));
components.forEach(function(name) {
var prefix = '-';
var nested = section[name].length > 1;
if (name !== EMPTY_COMPONENT) {
if (nested) {
stream.write(util.format('- **%s:**\n', name));
prefix = ' -';
} else {
prefix = util.format('- **%s:**', name);
}
}
section[name].forEach(function(commit) {
if (printCommitLinks) {
stream.write(util.format('%s %s\n (%s', prefix, commit.subject, linkToCommit(commit.hash)));
if (commit.closes.length) {
stream.write(',\n ' + commit.closes.map(linkToIssue).join(', '));
}
stream.write(')\n');
} else {
stream.write(util.format('%s %s', prefix, commit.subject));
}
});
});
stream.write('\n');
};
var readGitLog = function(grep, from) {
var deferred = q.defer();
// TODO(vojta): if it's slow, use spawn and stream it instead
child.exec(util.format(GIT_LOG_CMD, grep, '%H%n%s%n%b%n==END==', from), function(code, stdout, stderr) {
var commits = [];
stdout.split('\n==END==\n').forEach(function(rawCommit) {
var commit = parseRawCommit(rawCommit);
if (commit) commits.push(commit);
});
deferred.resolve(commits);
});
return deferred.promise;
};
var writeChangelog = function(stream, commits, version) {
var sections = {
fix: {},
feat: {},
perf: {},
breaks: {}
};
sections.breaks[EMPTY_COMPONENT] = [];
commits.forEach(function(commit) {
var section = sections[commit.type];
var component = commit.component || EMPTY_COMPONENT;
if (section) {
section[component] = section[component] || [];
section[component].push(commit);
}
if (commit.breaking) {
sections.breaks[component] = sections.breaks[component] || [];
sections.breaks[component].push({
subject: util.format("due to %s,\n %s", linkToCommit(commit.hash), commit.breaking),
hash: commit.hash,
closes: []
});
};
});
stream.write(util.format(HEADER_TPL, version, version, currentDate()));
printSection(stream, 'Bug Fixes', sections.fix);
printSection(stream, 'Features', sections.feat);
printSection(stream, 'Performance Improvements', sections.perf);
printSection(stream, 'Breaking Changes', sections.breaks, false);
}
var getPreviousTag = function() {
var deferred = q.defer();
child.exec(GIT_TAG_CMD, function(code, stdout, stderr) {
if (code) deferred.reject('Cannot get the previous tag.');
else deferred.resolve(stdout.replace('\n', ''));
});
return deferred.promise;
};
var generate = function(version, file) {
getPreviousTag().then(function(tag) {
console.log('Reading git log since', tag);
readGitLog('^fix|^feat|^perf|BREAKING', tag).then(function(commits) {
console.log('Parsed', commits.length, 'commits');
console.log('Generating changelog to', file || 'stdout', '(', version, ')');
writeChangelog(file ? fs.createWriteStream(file) : process.stdout, commits, version);
});
});
};
// publish for testing
exports.parseRawCommit = parseRawCommit;
// hacky start if not run by jasmine :-D
if (process.argv.join('').indexOf('jasmine-node') === -1) {
generate(process.argv[2], process.argv[3]);
}
|
/**
* multiscroll.js 0.1.5 Beta
* https://github.com/alvarotrigo/multiscroll.js
* MIT licensed
*
* Copyright (C) 2013 alvarotrigo.com - A project by Alvaro Trigo
*/
(function($) {
$.fn.multiscroll = function(options) {
// Create some defaults, extending them with any options that were provided
options = $.extend({
'verticalCentered' : true,
'scrollingSpeed': 700,
'easing': 'easeInQuart',
'menu': false,
'sectionsColor': [],
'anchors':[],
'navigation': false,
'navigationPosition': 'right',
'navigationColor': '#000',
'navigationTooltips': [],
'loopBottom': false,
'loopTop': false,
'css3': false,
'paddingTop': 0,
'paddingBottom': 0,
'fixedElements': null,
'normalScrollElements': null,
'keyboardScrolling': true,
'touchSensitivity': 5,
//events
'afterLoad': null,
'onLeave': null,
'afterRender': null,
'afterResize': null
}, options);
//Defines the delay to take place before being able to scroll to the next section
//BE CAREFUL! Not recommened to change it under 400 for a good behavior in laptops and
//Apple devices (laptops, mouses...)
var scrollDelay = 600;
var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
var numberSections = $('.ms-left').find('.ms-section').length;
var isMoving = false;
var nav;
var windowHeight = $(window).height();
addMouseWheelHandler();
addTouchHandler();
//if css3 is not supported, it will use jQuery animations
if(options.css3){
options.css3 = support3d();
}
$('html, body').css({
'overflow' : 'hidden',
'height' : '100%'
});
//creating the navigation dots
if (options.navigation) {
$('body').append('<div id="multiscroll-nav"><ul></ul></div>');
nav = $('#multiscroll-nav');
nav.css('color', options.navigationColor);
nav.addClass(options.navigationPosition);
}
$('.ms-right, .ms-left').css({
'width': '50%',
'position': 'absolute',
'height': '100%',
'-ms-touch-action': 'none'
});
$('.ms-right').css({
'right': '1px', //http://stackoverflow.com/questions/23675457/chrome-and-opera-creating-small-padding-when-using-displaytable
'top': '0',
'-ms-touch-action': 'none',
'touch-action': 'none'
});
$('.ms-left').css({
'left': '0',
'top': '0',
'-ms-touch-action': 'none',
'touch-action': 'none'
});
$('.ms-left .ms-section, .ms-right .ms-section').each(function(){
var sectionIndex = $(this).index();
if(options.paddingTop || options.paddingBottom){
$(this).css('padding', options.paddingTop + ' 0 ' + options.paddingBottom + ' 0');
}
if (typeof options.sectionsColor[sectionIndex] !== 'undefined') {
$(this).css('background-color', options.sectionsColor[sectionIndex]);
}
if (typeof options.anchors[sectionIndex] !== 'undefined') {
$(this).attr('data-anchor', options.anchors[sectionIndex]);
}
if(options.verticalCentered){
addTableClass($(this));
}
//only for the left panel
if($(this).closest('.ms-left').length && options.navigation) {
var link = '';
if(options.anchors.length){
link = options.anchors[sectionIndex];
}
var tooltip = options.navigationTooltips[sectionIndex];
if(typeof tooltip === 'undefined'){
tooltip = '';
}
if (options.navigation) {
nav.find('ul').append('<li data-tooltip="' + tooltip + '"><a href="#' + link + '"><span></span></a></li>');
}
}
});
//inverting the right panel
$('.ms-right').html( $('.ms-right').find('.ms-section').get().reverse());
$('.ms-left .ms-section, .ms-right .ms-section').each(function(){
var sectionIndex = $(this).index();
$(this).css({
'height': '100%'
});
if(!sectionIndex && options.navigation ){
//activating the navigation bullet
nav.find('li').eq(sectionIndex).find('a').addClass('active');
}
}).promise().done(function(){
//if no active section is defined, the 1st one will be the default one
if(!$('.ms-left .ms-section.active').length){
$('.ms-right').find('.ms-section').last().addClass('active');
$('.ms-left').find('.ms-section').first().addClass('active');
}
$.isFunction( options.afterRender ) && options.afterRender.call( this);
//scrolling to the defined active section and adjusting right and left panels
silentScroll();
$(window).on('load', function() {
scrollToAnchor();
});
});
//detecting any change on the URL to scroll to the given anchor link
//(a way to detect back history button as we play with the hashes on the URL)
$(window).on('hashchange',function(){
var value = window.location.hash.replace('#', '');
var sectionAnchor = value;
if(sectionAnchor.length){
var section = $('.ms-left').find('[data-anchor="'+sectionAnchor+'"]');
var isFirstScrollMove = (typeof lastScrolledDestiny === 'undefined' );
if (isFirstScrollMove || sectionAnchor !== lastScrolledDestiny){
scrollPage(section);
}
}
});
/**
* Sliding with arrow keys, both, vertical and horizontal
*/
$(document).keydown(function(e) {
if(e.which == 40 || e.which == 38){
e.preventDefault();
}
//Moving the main page with the keyboard arrows if keyboard scrolling is enabled
if (options.keyboardScrolling && !isMoving) {
switch (e.which) {
//up
case 38:
case 33:
$.fn.multiscroll.moveSectionUp();
break;
//down
case 40:
case 34:
$.fn.multiscroll.moveSectionDown();
break;
//Home
case 36:
$.fn.multiscroll.moveTo(1);
break;
//End
case 35:
$.fn.multiscroll.moveTo( $('.ms-left .ms-section').length );
break;
default:
return; // exit this handler for other keys
}
}
});
/**
* Disabling any action when pressing of the mouse wheel (Chrome, IE, Opera, Safari)
*/
$(document).mousedown(function(e) {
if(e.button == 1){
e.preventDefault();
return false;
}
});
//navigation action
$(document).on('click', '#multiscroll-nav a', function(e){
e.preventDefault();
var index = $(this).parent().index();
scrollPage($('.ms-left .ms-section').eq(index));
});
//navigation tooltips
$(document).on({
mouseenter: function(){
var tooltip = $(this).data('tooltip');
$('<div class="multiscroll-tooltip ' + options.navigationPosition +'">' + tooltip + '</div>').hide().appendTo($(this)).fadeIn(200);
},
mouseleave: function(){
$(this).find('.multiscroll-tooltip').fadeOut(200, function() {
$(this).remove();
});
}
}, '#multiscroll-nav li');
if(options.normalScrollElements){
$(document).on('mouseenter', options.normalScrollElements, function () {
$.fn.multiscroll.setMouseWheelScrolling(false);
});
$(document).on('mouseleave', options.normalScrollElements, function(){
$.fn.multiscroll.setMouseWheelScrolling(true);
});
}
//when resizing the site, we adjust the heights of the sections
$(window).resize(function() {
doneResizing();
});
/**
* When resizing is finished, we adjust the slides sizes and positions
*/
function doneResizing() {
windowHeight = $(window).height();
$('.ms-tableCell').each(function() {
$(this).css({ height: getTableHeight($(this).parent()) });
});
silentScroll();
$.isFunction( options.afterResize ) && options.afterResize.call( this);
}
function silentScroll(){
//moving the right section to the bottom
if(options.css3){
transformContainer($('.ms-left'), 'translate3d(0px, -' + $('.ms-left').find('.ms-section.active').position().top + 'px, 0px)', false);
transformContainer($('.ms-right'), 'translate3d(0px, -' + $('.ms-right').find('.ms-section.active').position().top + 'px, 0px)', false);
}else{
$('.ms-left').css('top', -$('.ms-left').find('.ms-section.active').position().top );
$('.ms-right').css('top', -$('.ms-right').find('.ms-section.active').position().top );
}
}
$.fn.multiscroll.moveSectionUp = function(){
var prev = $('.ms-left .ms-section.active').prev('.ms-section');
if(!prev.length && options.loopTop){
prev = $('.ms-left .ms-section').last();
}
if (prev.length) {
scrollPage(prev);
}
};
$.fn.multiscroll.moveSectionDown = function (){
var next = $('.ms-left .ms-section.active').next('.ms-section');
if(!next.length && options.loopBottom ){
next = $('.ms-left .ms-section').first();
}
if(next.length){
scrollPage(next);
}
};
$.fn.multiscroll.moveTo = function (section){
var destiny = '';
if(isNaN(section)){
destiny = $('.ms-left [data-anchor="'+section+'"]');
}else{
destiny = $('.ms-left .ms-section').eq( (section -1) );
}
scrollPage(destiny);
};
function scrollPage(leftDestination){
var leftDestinationIndex = leftDestination.index();
var rightDestination = $('.ms-right').find('.ms-section').eq( numberSections -1 - leftDestinationIndex);
var rightDestinationIndex = numberSections - 1 - leftDestinationIndex;
var anchorLink = leftDestination.data('anchor');
var activeSection = $('.ms-left .ms-section.active');
var leavingSection = activeSection.index() + 1;
var yMovement = getYmovement(leftDestination);
//preventing from activating the MouseWheelHandler event
//more than once if the page is scrolling
isMoving = true;
setURLHash(anchorLink);
var topPos = {
'left' : leftDestination.position().top,
'right': rightDestination.position().top
};
rightDestination.addClass('active').siblings().removeClass('active');
leftDestination.addClass('active').siblings().removeClass('active');
// Use CSS3 translate functionality or...
if (options.css3){
//callback (onLeave)
$.isFunction(options.onLeave) && options.onLeave.call(this, leavingSection, (leftDestinationIndex + 1), yMovement);
var translate3dLeft = 'translate3d(0px, -' + topPos['left'] + 'px, 0px)';
var translate3dRight = 'translate3d(0px, -' + topPos['right'] + 'px, 0px)';
transformContainer($('.ms-left'), translate3dLeft, true);
transformContainer($('.ms-right'), translate3dRight, true);
setTimeout(function () {
//callback (afterLoad)
$.isFunction(options.afterLoad) && options.afterLoad.call(this, anchorLink, (leftDestinationIndex + 1));
setTimeout(function () {
isMoving = false;
}, scrollDelay);
}, options.scrollingSpeed);
}else{
//callback (onLeave)
$.isFunction(options.onLeave) && options.onLeave.call(this, leavingSection, (leftDestinationIndex + 1), yMovement);
$('.ms-left').animate({
'top': -topPos['left']
}, options.scrollingSpeed, options.easing, function(){
$.isFunction(options.afterLoad) && options.afterLoad.call(this, anchorLink, (leftDestinationIndex + 1));
setTimeout(function () {
isMoving = false;
}, scrollDelay);
});
$('.ms-right').animate({
'top': -topPos['right']
}, options.scrollingSpeed, options.easing);
}
//flag to avoid callingn `scrollPage()` twice in case of using anchor links
lastScrolledDestiny = anchorLink;
activateMenuElement(anchorLink);
activateNavDots(anchorLink, leftDestinationIndex);
}
/**
* Removes the auto scrolling action fired by the mouse wheel and tackpad.
* After this function is called, the mousewheel and trackpad movements won't scroll through sections.
*/
function removeMouseWheelHandler(){
if (document.addEventListener) {
document.removeEventListener('mousewheel', MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
document.removeEventListener('wheel', MouseWheelHandler, false); //Firefox
} else {
document.detachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8
}
}
/**
* Adds the auto scrolling action for the mouse wheel and tackpad.
* After this function is called, the mousewheel and trackpad movements will scroll through sections
*/
function addMouseWheelHandler(){
if (document.addEventListener) {
document.addEventListener("mousewheel", MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
document.addEventListener("wheel", MouseWheelHandler, false); //Firefox
} else {
document.attachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8
}
}
/**
* Detecting mousewheel scrolling
*
* http://blogs.sitepointstatic.com/examples/tech/mouse-wheel/index.html
* http://www.sitepoint.com/html5-javascript-mouse-wheel/
*/
function MouseWheelHandler(e) {
// cross-browser wheel delta
e = window.event || e;
var delta = Math.max(-1, Math.min(1,
(e.wheelDelta || -e.deltaY || -e.detail)));
if (!isMoving) { //if theres any #
//scrolling down?
if (delta < 0) {
$.fn.multiscroll.moveSectionDown();
}
//scrolling up?
else {
$.fn.multiscroll.moveSectionUp();
}
}
return false;
}
/**
* Adds a css3 transform property to the container class with or without animation depending on the animated param.
*/
function transformContainer(container, translate3d, animated){
container.toggleClass('ms-easing', animated);
container.css(getTransforms(translate3d));
}
/**
* Returns the transform styles for all browsers
*/
function getTransforms(translate3d){
return {
'-webkit-transform': translate3d,
'-moz-transform': translate3d,
'-ms-transform':translate3d,
'transform': translate3d
};
}
/**
* Activating the website navigation dots according to the given slide name.
*/
function activateNavDots(name, sectionIndex){
if(options.navigation){
$('#multiscroll-nav').find('.active').removeClass('active');
if(name){
$('#multiscroll-nav').find('a[href="#' + name + '"]').addClass('active');
}else{
$('#multiscroll-nav').find('li').eq(sectionIndex).find('a').addClass('active');
}
}
}
/**
* Activating the website main menu elements according to the given slide name.
*/
function activateMenuElement(name){
if(options.menu){
$(options.menu).find('.active').removeClass('active');
$(options.menu).find('[data-menuanchor="'+name+'"]').addClass('active');
}
}
/**
* Retuns `up` or `down` depending on the scrolling movement to reach its destination
* from the current section.
*/
function getYmovement(destiny){
var fromIndex = $('.ms-left .ms-section.active').index();
var toIndex = destiny.index();
if(fromIndex > toIndex){
return 'up';
}
return 'down';
}
/**
* Sets the URL hash for a section with slides
*/
function setURLHash(anchorLink){
if(options.anchors.length){
location.hash = anchorLink;
}
}
/**
* Checks for translate3d support
* @return boolean
* http://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
*/
function support3d() {
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'OTransform':'-o-transform',
'msTransform':'-ms-transform',
'MozTransform':'-moz-transform',
'transform':'transform'
};
// Add it to the body to get the computed style.
document.body.insertBefore(el, null);
for (var t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = "translate3d(1px,1px,1px)";
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
/**
* Wraps an element in order to center it vertically by using a class style.
*/
function addTableClass(element){
element.addClass('ms-table').wrapInner('<div class="ms-tableCell" style="height: ' + getTableHeight(element) + 'px" />');
}
/**
* Gets the height of the section after removing the paddings.
*/
function getTableHeight(section){
var sectionHeight = windowHeight;
if(options.paddingTop || options.paddingBottom){
var paddings = parseInt(section.css('padding-top')) + parseInt(section.css('padding-bottom'));
sectionHeight = (windowHeight - paddings);
}
return sectionHeight;
}
/**
* Scrolls the page to the existent anchor in the URL
*/
function scrollToAnchor(){
//getting the anchor link in the URL and deleting the `#`
var sectionAnchor = window.location.hash.replace('#', '');
var section = $('.ms-left .ms-section[data-anchor="'+sectionAnchor+'"]');
if(sectionAnchor.length){ //if theres any #
scrollPage(section);
}
}
/**
* Adds or remove the possiblity of scrolling through sections by using the keyboard arrow keys
*/
$.fn.multiscroll.setKeyboardScrolling = function (value){
options.keyboardScrolling = value;
};
/**
* Adds or remove the possiblity of scrolling through sections by using the mouse wheel or the trackpad.
*/
$.fn.multiscroll.setMouseWheelScrolling = function (value){
if(value){
addMouseWheelHandler();
}else{
removeMouseWheelHandler();
}
};
/**
* Defines the scrolling speed
*/
$.fn.multiscroll.setScrollingSpeed = function(value){
options.scrollingSpeed = value;
};
var touchStartY = 0;
var touchStartX = 0;
var touchEndY = 0;
var touchEndX = 0;
/* Detecting touch events
* As we are changing the top property of the page on scrolling, we can not use the traditional way to detect it.
* This way, the touchstart and the touch moves shows an small difference between them which is the
* used one to determine the direction.
*/
function touchMoveHandler(event){
var e = event.originalEvent;
//preventing the easing on iOS devices
event.preventDefault();
var activeSection = $('.ms-left .ms-section.active');
if (!isMoving) { //if theres any #
var touchEvents = getEventsPage(e);
touchEndY = touchEvents['y'];
touchEndX = touchEvents['x'];
//is the movement greater than the minimum resistance to scroll?
if (Math.abs(touchStartY - touchEndY) > ($(window).height() / 100 * options.touchSensitivity)) {
if (touchStartY > touchEndY) {
$.fn.multiscroll.moveSectionDown();
} else if (touchEndY > touchStartY) {
$.fn.multiscroll.moveSectionUp();
}
}
}
}
/**
* Handler to get he coordinates of the starting touch
*/
function touchStartHandler(event){
var e = event.originalEvent;
var touchEvents = getEventsPage(e);
touchStartY = touchEvents['y'];
touchStartX = touchEvents['x'];
}
/**
* Adds the possibility to auto scroll through sections on touch devices.
*/
function addTouchHandler(){
if(isTouch){
//Microsoft pointers
MSPointer = getMSPointer();
$(document).off('touchstart ' + MSPointer.down).on('touchstart ' + MSPointer.down, touchStartHandler);
$(document).off('touchmove ' + MSPointer.move).on('touchmove ' + MSPointer.move, touchMoveHandler);
}
}
/**
* Removes the auto scrolling for touch devices.
*/
function removeTouchHandler(){
if(isTouch){
//Microsoft pointers
MSPointer = getMSPointer();
$(document).off('touchstart ' + MSPointer.down);
$(document).off('touchmove ' + MSPointer.move);
}
}
/*
* Returns and object with Microsoft pointers (for IE<11 and for IE >= 11)
* http://msdn.microsoft.com/en-us/library/ie/dn304886(v=vs.85).aspx
*/
function getMSPointer(){
var pointer;
//IE >= 11
if(window.PointerEvent){
pointer = { down: "pointerdown", move: "pointermove"};
}
//IE < 11
else{
pointer = { down: "MSPointerDown", move: "MSPointerMove"};
}
return pointer;
}
/**
* Gets the pageX and pageY properties depending on the browser.
* https://github.com/alvarotrigo/fullPage.js/issues/194#issuecomment-34069854
*/
function getEventsPage(e){
var events = new Array();
if (window.navigator.msPointerEnabled){
events['y'] = e.pageY;
events['x'] = e.pageX;
}else{
events['y'] = e.touches[0].pageY;
events['x'] = e.touches[0].pageX;
}
return events;
}
};
})(jQuery);
|
import $ from 'jquery';
import Sortable from 'sortablejs';
import PageFilters, { Instance as PageFiltersInstance } from './filter';
import './page';
// Pages Ordering
let Ordering = null;
let orderingElement = $('#ordering');
if (orderingElement.length) {
Ordering = new Sortable(orderingElement.get(0), {
filter: '.ignore',
onUpdate: function(event) {
let item = $(event.item);
let index = orderingElement.children().index(item) + 1;
$('[data-order]').val(index);
}
});
}
export default {
Ordering,
PageFilters: {
PageFilters,
Instance: PageFiltersInstance
}
};
|
!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.random={})}(this,function(n){"use strict";var t=function(n){return function(){for(var t=0,r=0;n>r;++r)t+=Math.random();return t}},r=function(n){var r=t(n);return function(){return r()/n}},e=function(n,t){var r=arguments.length;return r?1===r?(n=+n,t=1):(n=+n,t=+t):(n=0,t=1),function(){var r,e,o;do r=2*Math.random()-1,e=2*Math.random()-1,o=r*r+e*e;while(!o||o>1);return n+t*r*Math.sqrt(-2*Math.log(o)/o)}},o=function(){var n=e.apply(this,arguments);return function(){return Math.exp(n())}},u=function(n,t){var r=arguments.length;return r?1===r?(t=+n,n=0):(n=+n,t=+t-n):(n=0,t=1),function(){return Math.random()*t+n}};n.uniform=u,n.normal=e,n.logNormal=o,n.bates=r,n.irwinHall=t}); |
SyncedCron.options = {
log: false,
collectionName: 'cronHistory',
utc: false,
collectionTTL: 172800
}
defaultFrequency = 7; // once a week
defaultTime = '00:00';
var getSchedule = function (parser) {
var frequency = getSetting('newsletterFrequency', defaultFrequency);
var recur = parser.recur();
var schedule;
switch (frequency) {
case 1: // every day
// sched = {schedules: [{dw: [1,2,3,4,5,6,0]}]};
schedule = recur.on(1,2,3,4,5,6,0).dayOfWeek();
case 2: // Mondays, Wednesdays, Fridays
// sched = {schedules: [{dw: [2,4,6]}]};
schedule = recur.on(2,4,6).dayOfWeek();
case 3: // Mondays, Thursdays
// sched = {schedules: [{dw: [2,5]}]};
schedule = recur.on(2,5).dayOfWeek();
case 7: // Once a week (Mondays)
// sched = {schedules: [{dw: [2]}]};
schedule = recur.on(2).dayOfWeek();
default: // Once a week (Mondays)
schedule = recur.on(2).dayOfWeek();
}
return schedule.on(getSetting('newsletterTime', defaultTime)).time();
}
Meteor.methods({
getNextJob: function () {
var nextJob = SyncedCron.nextScheduledAtDate('scheduleNewsletter');
console.log(nextJob);
return nextJob;
}
});
var addJob = function () {
SyncedCron.add({
name: 'scheduleNewsletter',
schedule: function(parser) {
// parser is a later.parse object
return getSchedule(parser);
},
job: function() {
scheduleNextCampaign();
}
});
}
Meteor.startup(function () {
if (getSetting('enableNewsletter', false)) {
addJob();
}
}); |
/*!
* Fine Uploader
*
* Copyright 2015, Widen Enterprises, Inc. info@fineuploader.com
*
* Version: 5.3.0-11
*
* Homepage: http://fineuploader.com
*
* Repository: git://github.com/FineUploader/fine-uploader.git
*
* Licensed only under the Widen Commercial License (http://fineuploader.com/licensing).
*/
/*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */
/* jshint -W079 */
var qq = function(element) {
"use strict";
return {
hide: function() {
element.style.display = "none";
return this;
},
/** Returns the function which detaches attached event */
attach: function(type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
}
return function() {
qq(element).detach(type, fn);
};
},
detach: function(type, fn) {
if (element.removeEventListener) {
element.removeEventListener(type, fn, false);
} else if (element.attachEvent) {
element.detachEvent("on" + type, fn);
}
return this;
},
contains: function(descendant) {
// The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains)
// says a `null` (or ostensibly `undefined`) parameter
// passed into `Node.contains` should result in a false return value.
// IE7 throws an exception if the parameter is `undefined` though.
if (!descendant) {
return false;
}
// compareposition returns false in this case
if (element === descendant) {
return true;
}
if (element.contains) {
return element.contains(descendant);
} else {
/*jslint bitwise: true*/
return !!(descendant.compareDocumentPosition(element) & 8);
}
},
/**
* Insert this element before elementB.
*/
insertBefore: function(elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function() {
element.parentNode.removeChild(element);
return this;
},
/**
* Sets styles for an element.
* Fixes opacity in IE6-8.
*/
css: function(styles) {
/*jshint eqnull: true*/
if (element.style == null) {
throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
}
/*jshint -W116*/
if (styles.opacity != null) {
if (typeof element.style.opacity !== "string" && typeof (element.filters) !== "undefined") {
styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function(name, considerParent) {
var re = new RegExp("(^| )" + name + "( |$)");
return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));
},
addClass: function(name) {
if (!qq(element).hasClass(name)) {
element.className += " " + name;
}
return this;
},
removeClass: function(name) {
var re = new RegExp("(^| )" + name + "( |$)");
element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function(className) {
var candidates,
result = [];
if (element.querySelectorAll) {
return element.querySelectorAll("." + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function(idx, val) {
if (qq(val).hasClass(className)) {
result.push(val);
}
});
return result;
},
children: function() {
var children = [],
child = element.firstChild;
while (child) {
if (child.nodeType === 1) {
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function(text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function() {
return qq(element).setText("");
},
// Returns true if the attribute exists on the element
// AND the value of the attribute is NOT "false" (case-insensitive)
hasAttribute: function(attrName) {
var attrVal;
if (element.hasAttribute) {
if (!element.hasAttribute(attrName)) {
return false;
}
/*jshint -W116*/
return (/^false$/i).exec(element.getAttribute(attrName)) == null;
}
else {
attrVal = element[attrName];
if (attrVal === undefined) {
return false;
}
/*jshint -W116*/
return (/^false$/i).exec(attrVal) == null;
}
}
};
};
(function() {
"use strict";
qq.canvasToBlob = function(canvas, mime, quality) {
return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
};
qq.dataUriToBlob = function(dataUri) {
var arrayBuffer, byteString,
createBlob = function(data, mime) {
var BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder,
blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
}
else {
return new Blob([data], {type: mime});
}
},
intArray, mimeString;
// convert base64 to raw binary data held in a string
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
}
else {
byteString = decodeURI(dataUri.split(",")[1]);
}
// extract the MIME
mimeString = dataUri.split(",")[0]
.split(":")[1]
.split(";")[0];
// write the bytes of the binary string to an ArrayBuffer
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return createBlob(arrayBuffer, mimeString);
};
qq.log = function(message, level) {
if (window.console) {
if (!level || level === "info") {
window.console.log(message);
}
else
{
if (window.console[level]) {
window.console[level](message);
}
else {
window.console.log("<" + level + "> " + message);
}
}
}
};
qq.isObject = function(variable) {
return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
};
qq.isFunction = function(variable) {
return typeof (variable) === "function";
};
/**
* Check the type of a value. Is it an "array"?
*
* @param value value to test.
* @returns true if the value is an array or associated with an `ArrayBuffer`
*/
qq.isArray = function(value) {
return Object.prototype.toString.call(value) === "[object Array]" ||
(value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer);
};
// Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API.
qq.isItemList = function(maybeItemList) {
return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
};
// Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement`
// object that is associated with collections of Nodes.
qq.isNodeList = function(maybeNodeList) {
return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" ||
// If `HTMLCollection` is the actual type of the object, we must determine this
// by checking for expected properties/methods on the object
(maybeNodeList.item && maybeNodeList.namedItem);
};
qq.isString = function(maybeString) {
return Object.prototype.toString.call(maybeString) === "[object String]";
};
qq.trimStr = function(string) {
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, "");
};
/**
* @param str String to format.
* @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string.
*/
qq.format = function(str) {
var args = Array.prototype.slice.call(arguments, 1),
newStr = str,
nextIdxToReplace = newStr.indexOf("{}");
qq.each(args, function(idx, val) {
var strBefore = newStr.substring(0, nextIdxToReplace),
strAfter = newStr.substring(nextIdxToReplace + 2);
newStr = strBefore + val + strAfter;
nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
// End the loop if we have run out of tokens (when the arguments exceed the # of tokens)
if (nextIdxToReplace < 0) {
return false;
}
});
return newStr;
};
qq.isFile = function(maybeFile) {
return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
};
qq.isFileList = function(maybeFileList) {
return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
};
qq.isFileOrInput = function(maybeFileOrInput) {
return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
};
qq.isInput = function(maybeInput, notFile) {
var evaluateType = function(type) {
var normalizedType = type.toLowerCase();
if (notFile) {
return normalizedType !== "file";
}
return normalizedType === "file";
};
if (window.HTMLInputElement) {
if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
if (maybeInput.tagName) {
if (maybeInput.tagName.toLowerCase() === "input") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
return false;
};
qq.isBlob = function(maybeBlob) {
if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
return true;
}
};
qq.isXhrUploadSupported = function() {
var input = document.createElement("input");
input.type = "file";
return (
input.multiple !== undefined &&
typeof File !== "undefined" &&
typeof FormData !== "undefined" &&
typeof (qq.createXhrInstance()).upload !== "undefined");
};
// Fall back to ActiveX is native XHR is disabled (possible in any version of IE).
qq.createXhrInstance = function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (error) {
qq.log("Neither XHR or ActiveX are supported!", "error");
return null;
}
};
qq.isFolderDropSupported = function(dataTransfer) {
return dataTransfer.items &&
dataTransfer.items.length > 0 &&
dataTransfer.items[0].webkitGetAsEntry;
};
qq.isFileChunkingSupported = function() {
return !qq.androidStock() && //Android's stock browser cannot upload Blobs correctly
qq.isXhrUploadSupported() &&
(File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
};
qq.sliceBlob = function(fileOrBlob, start, end) {
var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
return slicer.call(fileOrBlob, start, end);
};
qq.arrayBufferToHex = function(buffer) {
var bytesAsHex = "",
bytes = new Uint8Array(buffer);
qq.each(bytes, function(idx, byt) {
var byteAsHexStr = byt.toString(16);
if (byteAsHexStr.length < 2) {
byteAsHexStr = "0" + byteAsHexStr;
}
bytesAsHex += byteAsHexStr;
});
return bytesAsHex;
};
qq.readBlobToHex = function(blob, startOffset, length) {
var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length),
fileReader = new FileReader(),
promise = new qq.Promise();
fileReader.onload = function() {
promise.success(qq.arrayBufferToHex(fileReader.result));
};
fileReader.onerror = promise.failure;
fileReader.readAsArrayBuffer(initialBlob);
return promise;
};
qq.extend = function(first, second, extendNested) {
qq.each(second, function(prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
}
else {
first[prop] = val;
}
});
return first;
};
/**
* Allow properties in one object to override properties in another,
* keeping track of the original values from the target object.
*
* Note that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked.
*
* @param target Update properties in this object from some source
* @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target.
* @returns {object} The target object
*/
qq.override = function(target, sourceFn) {
var super_ = {},
source = sourceFn(super_);
qq.each(source, function(srcPropName, srcPropVal) {
if (target[srcPropName] !== undefined) {
super_[srcPropName] = target[srcPropName];
}
target[srcPropName] = srcPropVal;
});
return target;
};
/**
* Searches for a given element (elt) in the array, returns -1 if it is not present.
*/
qq.indexOf = function(arr, elt, from) {
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
var len = arr.length;
if (from < 0) {
from += len;
}
for (; from < len; from += 1) {
if (arr.hasOwnProperty(from) && arr[from] === elt) {
return from;
}
}
return -1;
};
//this is a version 4 UUID
qq.getUniqueId = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
/*jslint eqeq: true, bitwise: true*/
var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
//
// Browsers and platforms detection
qq.ie = function() {
return navigator.userAgent.indexOf("MSIE") !== -1 ||
navigator.userAgent.indexOf("Trident") !== -1;
};
qq.ie7 = function() {
return navigator.userAgent.indexOf("MSIE 7") !== -1;
};
qq.ie8 = function() {
return navigator.userAgent.indexOf("MSIE 8") !== -1;
};
qq.ie10 = function() {
return navigator.userAgent.indexOf("MSIE 10") !== -1;
};
qq.ie11 = function() {
return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
};
qq.safari = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
};
qq.opera = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
};
qq.firefox = function() {
return (!qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "");
};
qq.windows = function() {
return navigator.platform === "Win32";
};
qq.android = function() {
return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
};
// We need to identify the Android stock browser via the UA string to work around various bugs in this browser,
// such as the one that prevents a `Blob` from being uploaded.
qq.androidStock = function() {
return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
};
qq.ios6 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
};
qq.ios7 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
};
qq.ios8 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
};
// iOS 8.0.0
qq.ios800 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
};
qq.ios = function() {
/*jshint -W014 */
return navigator.userAgent.indexOf("iPad") !== -1
|| navigator.userAgent.indexOf("iPod") !== -1
|| navigator.userAgent.indexOf("iPhone") !== -1;
};
qq.iosChrome = function() {
return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
};
qq.iosSafari = function() {
return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
};
qq.iosSafariWebView = function() {
return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
};
//
// Events
qq.preventDefault = function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
/**
* Creates and returns element from html string
* Uses innerHTML to create an element
*/
qq.toElement = (function() {
var div = document.createElement("div");
return function(html) {
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}());
//key and value are passed to callback for each entry in the iterable item
qq.each = function(iterableItem, callback) {
var keyOrIndex, retVal;
if (iterableItem) {
// Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items
if (window.Storage && iterableItem.constructor === window.Storage) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
if (retVal === false) {
break;
}
}
}
// `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays
// when iterating over items inside the object.
else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
else if (qq.isString(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
if (retVal === false) {
break;
}
}
}
else {
for (keyOrIndex in iterableItem) {
if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
}
}
};
//include any args that should be passed to the new function after the context arg
qq.bind = function(oldFunc, context) {
if (qq.isFunction(oldFunc)) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var newArgs = qq.extend([], args);
if (arguments.length) {
newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
}
return oldFunc.apply(context, newArgs);
};
}
throw new Error("first parameter must be a function!");
};
/**
* obj2url() takes a json-object as argument and generates
* a querystring. pretty much like jQuery.param()
*
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
*
* will result in:
*
* `http://any.url/upload?otherParam=value&a=b&c=d`
*
* @param Object JSON-Object
* @param String current querystring-part
* @return String encoded querystring
*/
qq.obj2url = function(obj, temp, prefixDone) {
/*jshint laxbreak: true*/
var uristrings = [],
prefix = "&",
add = function(nextObj, i) {
var nextTemp = temp
? (/\[\]$/.test(temp)) // prevent double-encoding
? temp
: temp + "[" + i + "]"
: i;
if ((nextTemp !== "undefined") && (i !== "undefined")) {
uristrings.push(
(typeof nextObj === "object")
? qq.obj2url(nextObj, nextTemp, true)
: (Object.prototype.toString.call(nextObj) === "[object Function]")
? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj())
: encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj)
);
}
};
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? "" : "&" : "?";
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if ((Object.prototype.toString.call(obj) === "[object Array]") && (typeof obj !== "undefined")) {
qq.each(obj, function(idx, val) {
add(val, idx);
});
} else if ((typeof obj !== "undefined") && (obj !== null) && (typeof obj === "object")) {
qq.each(obj, function(prop, val) {
add(val, prop);
});
} else {
uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
} else {
return uristrings.join(prefix)
.replace(/^&/, "")
.replace(/%20/g, "+");
}
};
qq.obj2FormData = function(obj, formData, arrayKeyName) {
if (!formData) {
formData = new FormData();
}
qq.each(obj, function(key, val) {
key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
}
else if (qq.isFunction(val)) {
formData.append(key, val());
}
else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function(obj, form) {
var input;
if (!form) {
form = document.createElement("form");
}
qq.obj2FormData(obj, {
append: function(key, val) {
input = document.createElement("input");
input.setAttribute("name", key);
input.setAttribute("value", val);
form.appendChild(input);
}
});
return form;
};
/**
* Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not
* implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js.
*/
qq.parseJson = function(json) {
/*jshint evil: true*/
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
} else {
return eval("(" + json + ")");
}
};
/**
* Retrieve the extension of a file, if it exists.
*
* @param filename
* @returns {string || undefined}
*/
qq.getExtension = function(filename) {
var extIdx = filename.lastIndexOf(".") + 1;
if (extIdx > 0) {
return filename.substr(extIdx, filename.length - extIdx);
}
};
qq.getFilename = function(blobOrFileInput) {
/*jslint regexp: true*/
if (qq.isInput(blobOrFileInput)) {
// get input value and remove path to normalize
return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
}
else if (qq.isFile(blobOrFileInput)) {
if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
return blobOrFileInput.fileName;
}
}
return blobOrFileInput.name;
};
/**
* A generic module which supports object disposing in dispose() method.
* */
qq.DisposeSupport = function() {
var disposers = [];
return {
/** Run all registered disposers */
dispose: function() {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
}
while (disposer);
},
/** Attach event handler and register de-attacher as a disposer */
attach: function() {
var args = arguments;
/*jslint undef:true*/
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
/** Add disposer to the collection */
addDisposer: function(disposeFunction) {
disposers.push(disposeFunction);
}
};
};
}());
/* globals qq */
/**
* Fine Uploader top-level Error container. Inherits from `Error`.
*/
(function() {
"use strict";
qq.Error = function(message) {
this.message = "[Fine Uploader " + qq.version + "] " + message;
};
qq.Error.prototype = new Error();
}());
/*global qq */
qq.version = "5.3.0-11";
/* globals qq */
qq.supportedFeatures = (function() {
"use strict";
var supportsUploading,
supportsUploadingBlobs,
supportsFileDrop,
supportsAjaxFileUploading,
supportsFolderDrop,
supportsChunking,
supportsResume,
supportsUploadViaPaste,
supportsUploadCors,
supportsDeleteFileXdr,
supportsDeleteFileCorsXhr,
supportsDeleteFileCors,
supportsFolderSelection,
supportsImagePreviews,
supportsUploadProgress;
function testSupportsFileInputElement() {
var supported = true,
tempInput;
try {
tempInput = document.createElement("input");
tempInput.type = "file";
qq(tempInput).hide();
if (tempInput.disabled) {
supported = false;
}
}
catch (ex) {
supported = false;
}
return supported;
}
//only way to test for Filesystem API support since webkit does not expose the DataTransfer interface
function isChrome21OrHigher() {
return (qq.chrome() || qq.opera()) &&
navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
}
//only way to test for complete Clipboard API support at this time
function isChrome14OrHigher() {
return (qq.chrome() || qq.opera()) &&
navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
}
//Ensure we can send cross-origin `XMLHttpRequest`s
function isCrossOriginXhrSupported() {
if (window.XMLHttpRequest) {
var xhr = qq.createXhrInstance();
//Commonly accepted test for XHR CORS support.
return xhr.withCredentials !== undefined;
}
return false;
}
//Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8
function isXdrSupported() {
return window.XDomainRequest !== undefined;
}
// CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s,
// or if `XDomainRequest` is an available alternative.
function isCrossOriginAjaxSupported() {
if (isCrossOriginXhrSupported()) {
return true;
}
return isXdrSupported();
}
function isFolderSelectionSupported() {
// We know that folder selection is only supported in Chrome via this proprietary attribute for now
return document.createElement("input").webkitdirectory !== undefined;
}
function isLocalStorageSupported() {
try {
return !!window.localStorage;
}
catch (error) {
// probably caught a security exception, so no localStorage for you
return false;
}
}
function isDragAndDropSupported() {
var span = document.createElement("span");
return ("draggable" in span || ("ondragstart" in span && "ondrop" in span)) &&
!qq.android() && !qq.ios();
}
supportsUploading = testSupportsFileInputElement();
supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();
supportsFolderDrop = supportsFileDrop && isChrome21OrHigher();
supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
supportsDeleteFileXdr = isXdrSupported();
supportsDeleteFileCors = isCrossOriginAjaxSupported();
supportsFolderSelection = isFolderSelectionSupported();
supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
supportsUploadProgress = (function() {
if (supportsAjaxFileUploading) {
return !qq.androidStock() && !qq.iosChrome();
}
return false;
}());
return {
ajaxUploading: supportsAjaxFileUploading,
blobUploading: supportsUploadingBlobs,
canDetermineSize: supportsAjaxFileUploading,
chunking: supportsChunking,
deleteFileCors: supportsDeleteFileCors,
deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported
deleteFileCorsXhr: supportsDeleteFileCorsXhr,
dialogElement: !!window.HTMLDialogElement,
fileDrop: supportsFileDrop,
folderDrop: supportsFolderDrop,
folderSelection: supportsFolderSelection,
imagePreviews: supportsImagePreviews,
imageValidation: supportsImagePreviews,
itemSizeValidation: supportsAjaxFileUploading,
pause: supportsChunking,
progressBar: supportsUploadProgress,
resume: supportsResume,
scaling: supportsImagePreviews && supportsUploadingBlobs,
tiffPreviews: qq.safari(), // Not the best solution, but simple and probably accurate enough (for now)
unlimitedScaledImageSize: !qq.ios(), // false simply indicates that there is some known limit
uploading: supportsUploading,
uploadCors: supportsUploadCors,
uploadCustomHeaders: supportsAjaxFileUploading,
uploadNonMultipart: supportsAjaxFileUploading,
uploadViaPaste: supportsUploadViaPaste
};
}());
/*globals qq*/
// Is the passed object a promise instance?
qq.isGenericPromise = function(maybePromise) {
"use strict";
return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
};
qq.Promise = function() {
"use strict";
var successArgs, failureArgs,
successCallbacks = [],
failureCallbacks = [],
doneCallbacks = [],
state = 0;
qq.extend(this, {
then: function(onSuccess, onFailure) {
if (state === 0) {
if (onSuccess) {
successCallbacks.push(onSuccess);
}
if (onFailure) {
failureCallbacks.push(onFailure);
}
}
else if (state === -1) {
onFailure && onFailure.apply(null, failureArgs);
}
else if (onSuccess) {
onSuccess.apply(null, successArgs);
}
return this;
},
done: function(callback) {
if (state === 0) {
doneCallbacks.push(callback);
}
else {
callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
}
return this;
},
success: function() {
state = 1;
successArgs = arguments;
if (successCallbacks.length) {
qq.each(successCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
return this;
},
failure: function() {
state = -1;
failureArgs = arguments;
if (failureCallbacks.length) {
qq.each(failureCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
return this;
}
});
};
/* globals qq */
/**
* Placeholder for a Blob that will be generated on-demand.
*
* @param referenceBlob Parent of the generated blob
* @param onCreate Function to invoke when the blob must be created. Must be promissory.
* @constructor
*/
qq.BlobProxy = function(referenceBlob, onCreate) {
"use strict";
qq.extend(this, {
referenceBlob: referenceBlob,
create: function() {
return onCreate(referenceBlob);
}
});
};
/*globals qq*/
/**
* This module represents an upload or "Select File(s)" button. It's job is to embed an opaque `<input type="file">`
* element as a child of a provided "container" element. This "container" element (`options.element`) is used to provide
* a custom style for the `<input type="file">` element. The ability to change the style of the container element is also
* provided here by adding CSS classes to the container on hover/focus.
*
* TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be
* available on all supported browsers.
*
* @param o Options to override the default values
*/
qq.UploadButton = function(o) {
"use strict";
var self = this,
disposeSupport = new qq.DisposeSupport(),
options = {
// "Container" element
element: null,
// If true adds `multiple` attribute to `<input type="file">`
multiple: false,
// Corresponds to the `accept` attribute on the associated `<input type="file">`
acceptFiles: null,
// A true value allows folders to be selected, if supported by the UA
folders: false,
// `name` attribute of `<input type="file">`
name: "qqfile",
// Called when the browser invokes the onchange handler on the `<input type="file">`
onChange: function(input) {},
ios8BrowserCrashWorkaround: false,
// **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers
hoverClass: "qq-upload-button-hover",
focusClass: "qq-upload-button-focus"
},
input, buttonId;
// Overrides any of the default option values with any option values passed in during construction.
qq.extend(options, o);
buttonId = qq.getUniqueId();
// Embed an opaque `<input type="file">` element as a child of `options.element`.
function createInput() {
var input = document.createElement("input");
input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
input.setAttribute("title", "file input");
self.setMultiple(options.multiple, input);
if (options.folders && qq.supportedFeatures.folderSelection) {
// selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute
input.setAttribute("webkitdirectory", "");
}
if (options.acceptFiles) {
input.setAttribute("accept", options.acceptFiles);
}
input.setAttribute("type", "file");
input.setAttribute("name", options.name);
qq(input).css({
position: "absolute",
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
right: 0,
top: 0,
fontFamily: "Arial",
// It's especially important to make this an arbitrarily large value
// to ensure the rendered input button in IE takes up the entire
// space of the container element. Otherwise, the left side of the
// button will require a double-click to invoke the file chooser.
// In other browsers, this might cause other issues, so a large font-size
// is only used in IE. There is a bug in IE8 where the opacity style is ignored
// in some cases when the font-size is large. So, this workaround is not applied
// to IE8.
fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
margin: 0,
padding: 0,
cursor: "pointer",
opacity: 0
});
// Setting the file input's height to 100% in IE7 causes
// most of the visible button to be unclickable.
!qq.ie7() && qq(input).css({height: "100%"});
options.element.appendChild(input);
disposeSupport.attach(input, "change", function() {
options.onChange(input);
});
// **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers
disposeSupport.attach(input, "mouseover", function() {
qq(options.element).addClass(options.hoverClass);
});
disposeSupport.attach(input, "mouseout", function() {
qq(options.element).removeClass(options.hoverClass);
});
disposeSupport.attach(input, "focus", function() {
qq(options.element).addClass(options.focusClass);
});
disposeSupport.attach(input, "blur", function() {
qq(options.element).removeClass(options.focusClass);
});
return input;
}
// Make button suitable container for input
qq(options.element).css({
position: "relative",
overflow: "hidden",
// Make sure browse button is in the right side in Internet Explorer
direction: "ltr"
});
// Exposed API
qq.extend(this, {
getInput: function() {
return input;
},
getButtonId: function() {
return buttonId;
},
setMultiple: function(isMultiple, optInput) {
var input = optInput || this.getInput();
// Temporary workaround for bug in in iOS8 UIWebView that causes the browser to crash
// before the file chooser appears if the file input doesn't contain a multiple attribute.
// See #1283.
if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
input.setAttribute("multiple", "");
}
else {
if (isMultiple) {
input.setAttribute("multiple", "");
}
else {
input.removeAttribute("multiple");
}
}
},
setAcceptFiles: function(acceptFiles) {
if (acceptFiles !== options.acceptFiles) {
input.setAttribute("accept", acceptFiles);
}
},
reset: function() {
if (input.parentNode) {
qq(input).remove();
}
qq(options.element).removeClass(options.focusClass);
input = null;
input = createInput();
}
});
input = createInput();
};
qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
/*globals qq */
qq.UploadData = function(uploaderProxy) {
"use strict";
var data = [],
byUuid = {},
byStatus = {},
byProxyGroupId = {},
byBatchId = {};
function getDataByIds(idOrIds) {
if (qq.isArray(idOrIds)) {
var entries = [];
qq.each(idOrIds, function(idx, id) {
entries.push(data[id]);
});
return entries;
}
return data[idOrIds];
}
function getDataByUuids(uuids) {
if (qq.isArray(uuids)) {
var entries = [];
qq.each(uuids, function(idx, uuid) {
entries.push(data[byUuid[uuid]]);
});
return entries;
}
return data[byUuid[uuids]];
}
function getDataByStatus(status) {
var statusResults = [],
statuses = [].concat(status);
qq.each(statuses, function(index, statusEnum) {
var statusResultIndexes = byStatus[statusEnum];
if (statusResultIndexes !== undefined) {
qq.each(statusResultIndexes, function(i, dataIndex) {
statusResults.push(data[dataIndex]);
});
}
});
return statusResults;
}
qq.extend(this, {
/**
* Adds a new file to the data cache for tracking purposes.
*
* @param spec Data that describes this file. Possible properties are:
*
* - uuid: Initial UUID for this file.
* - name: Initial name of this file.
* - size: Size of this file, omit if this cannot be determined
* - status: Initial `qq.status` for this file. Omit for `qq.status.SUBMITTING`.
* - batchId: ID of the batch this file belongs to
* - proxyGroupId: ID of the proxy group associated with this file
*
* @returns {number} Internal ID for this file.
*/
addFile: function(spec) {
var status = spec.status || qq.status.SUBMITTING,
id = data.push({
name: spec.name,
originalName: spec.name,
uuid: spec.uuid,
size: spec.size == null ? -1 : spec.size,
status: status
}) - 1;
if (spec.batchId) {
data[id].batchId = spec.batchId;
if (byBatchId[spec.batchId] === undefined) {
byBatchId[spec.batchId] = [];
}
byBatchId[spec.batchId].push(id);
}
if (spec.proxyGroupId) {
data[id].proxyGroupId = spec.proxyGroupId;
if (byProxyGroupId[spec.proxyGroupId] === undefined) {
byProxyGroupId[spec.proxyGroupId] = [];
}
byProxyGroupId[spec.proxyGroupId].push(id);
}
data[id].id = id;
byUuid[spec.uuid] = id;
if (byStatus[status] === undefined) {
byStatus[status] = [];
}
byStatus[status].push(id);
uploaderProxy.onStatusChange(id, null, status);
return id;
},
retrieve: function(optionalFilter) {
if (qq.isObject(optionalFilter) && data.length) {
if (optionalFilter.id !== undefined) {
return getDataByIds(optionalFilter.id);
}
else if (optionalFilter.uuid !== undefined) {
return getDataByUuids(optionalFilter.uuid);
}
else if (optionalFilter.status) {
return getDataByStatus(optionalFilter.status);
}
}
else {
return qq.extend([], data, true);
}
},
reset: function() {
data = [];
byUuid = {};
byStatus = {};
byBatchId = {};
},
setStatus: function(id, newStatus) {
var oldStatus = data[id].status,
byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
data[id].status = newStatus;
if (byStatus[newStatus] === undefined) {
byStatus[newStatus] = [];
}
byStatus[newStatus].push(id);
uploaderProxy.onStatusChange(id, oldStatus, newStatus);
},
uuidChanged: function(id, newUuid) {
var oldUuid = data[id].uuid;
data[id].uuid = newUuid;
byUuid[newUuid] = id;
delete byUuid[oldUuid];
},
updateName: function(id, newName) {
data[id].name = newName;
},
updateSize: function(id, newSize) {
data[id].size = newSize;
},
// Only applicable if this file has a parent that we may want to reference later.
setParentId: function(targetId, parentId) {
data[targetId].parentId = parentId;
},
getIdsInProxyGroup: function(id) {
var proxyGroupId = data[id].proxyGroupId;
if (proxyGroupId) {
return byProxyGroupId[proxyGroupId];
}
return [];
},
getIdsInBatch: function(id) {
var batchId = data[id].batchId;
return byBatchId[batchId];
}
});
};
qq.status = {
SUBMITTING: "submitting",
SUBMITTED: "submitted",
REJECTED: "rejected",
QUEUED: "queued",
CANCELED: "canceled",
PAUSED: "paused",
UPLOADING: "uploading",
UPLOAD_RETRYING: "retrying upload",
UPLOAD_SUCCESSFUL: "upload successful",
UPLOAD_FAILED: "upload failed",
DELETE_FAILED: "delete failed",
DELETING: "deleting",
DELETED: "deleted"
};
/*globals qq*/
/**
* Defines the public API for FineUploaderBasic mode.
*/
(function() {
"use strict";
qq.basePublicApi = {
// DEPRECATED - TODO REMOVE IN NEXT MAJOR RELEASE (replaced by addFiles)
addBlobs: function(blobDataOrArray, params, endpoint) {
this.addFiles(blobDataOrArray, params, endpoint);
},
addFiles: function(data, params, endpoint) {
this._maybeHandleIos8SafariWorkaround();
var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId,
processBlob = qq.bind(function(blob) {
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName
}, batchId, verifiedFiles);
}, this),
processBlobData = qq.bind(function(blobData) {
this._handleNewFile(blobData, batchId, verifiedFiles);
}, this),
processCanvas = qq.bind(function(canvas) {
var blob = qq.canvasToBlob(canvas);
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName + ".png"
}, batchId, verifiedFiles);
}, this),
processCanvasData = qq.bind(function(canvasData) {
var normalizedQuality = canvasData.quality && canvasData.quality / 100,
blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
this._handleNewFile({
blob: blob,
name: canvasData.name
}, batchId, verifiedFiles);
}, this),
processFileOrInput = qq.bind(function(fileOrInput) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
var files = Array.prototype.slice.call(fileOrInput.files),
self = this;
qq.each(files, function(idx, file) {
self._handleNewFile(file, batchId, verifiedFiles);
});
}
else {
this._handleNewFile(fileOrInput, batchId, verifiedFiles);
}
}, this),
normalizeData = function() {
if (qq.isFileList(data)) {
data = Array.prototype.slice.call(data);
}
data = [].concat(data);
},
self = this,
verifiedFiles = [];
this._currentBatchId = batchId;
if (data) {
normalizeData();
qq.each(data, function(idx, fileContainer) {
if (qq.isFileOrInput(fileContainer)) {
processFileOrInput(fileContainer);
}
else if (qq.isBlob(fileContainer)) {
processBlob(fileContainer);
}
else if (qq.isObject(fileContainer)) {
if (fileContainer.blob && fileContainer.name) {
processBlobData(fileContainer);
}
else if (fileContainer.canvas && fileContainer.name) {
processCanvasData(fileContainer);
}
}
else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
processCanvas(fileContainer);
}
else {
self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
}
});
this.log("Received " + verifiedFiles.length + " files.");
this._prepareItemsForUpload(verifiedFiles, params, endpoint);
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [],
self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
clearStoredFiles: function() {
this._storedIds = [];
},
continueUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (uploadData.status === qq.status.PAUSED) {
this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
this._uploadFile(id);
return true;
}
else {
this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
}
return false;
},
deleteFile: function(id) {
return this._onSubmitDelete(id);
},
// TODO document?
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
// Generate a variable size thumbnail on an img or canvas,
// returning a promise that is fulfilled when the attempt completes.
// Thumbnail can either be based off of a URL for an image returned
// by the server in the upload response, or the associated `Blob`.
drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer) {
var promiseToReturn = new qq.Promise(),
fileOrUrl, options;
if (this._imageGenerator) {
fileOrUrl = this._thumbnailUrls[fileId];
options = {
scale: maxSize > 0,
maxSize: maxSize > 0 ? maxSize : null
};
// If client-side preview generation is possible
// and we are not specifically looking for the image URl returned by the server...
if (!fromServer && qq.supportedFeatures.imagePreviews) {
fileOrUrl = this.getFile(fileId);
}
/* jshint eqeqeq:false,eqnull:true */
if (fileOrUrl == null) {
promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
}
else {
this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
function success(modifiedContainer) {
promiseToReturn.success(modifiedContainer);
},
function failure(container, reason) {
promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
}
);
}
}
else {
promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
}
return promiseToReturn;
},
getButton: function(fileId) {
return this._getButton(this._buttonIdsForFileIds[fileId]);
},
getEndpoint: function(fileId) {
return this._endpointStore.get(fileId);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId) || null;
},
getInProgress: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED
]
}).length;
},
getName: function(id) {
return this._uploadData.retrieve({id: id}).name;
},
// Parent ID for a specific file, or null if this is the parent, or if it has no parent.
getParentId: function(id) {
var uploadDataEntry = this.getUploads({id: id}),
parentId = null;
if (uploadDataEntry) {
if (uploadDataEntry.parentId !== undefined) {
parentId = uploadDataEntry.parentId;
}
}
return parentId;
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._uploadData.retrieve({id: id}).size;
},
getNetUploads: function() {
return this._netUploaded;
},
getRemainingAllowedItems: function() {
var allowedItems = this._currentItemLimit;
if (allowedItems > 0) {
return allowedItems - this._netUploadedOrQueued;
}
return null;
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
getUuid: function(id) {
return this._uploadData.retrieve({id: id}).uuid;
},
log: function(str, level) {
if (this._options.debug && (!level || level === "info")) {
qq.log("[Fine Uploader " + qq.version + "] " + str);
}
else if (level && level !== "info") {
qq.log("[Fine Uploader " + qq.version + "] " + str, level);
}
},
pauseUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
// Pause only really makes sense if the file is uploading or retrying
if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) {
if (this._handler.pause(id)) {
this._uploadData.setStatus(id, qq.status.PAUSED);
return true;
}
else {
this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
}
}
else {
this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
}
return false;
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
qq.each(this._buttons, function(idx, button) {
button.reset();
});
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
this._buttonIdsForFileIds = [];
this._pasteHandler && this._pasteHandler.reset();
this._options.session.refreshOnReset && this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._totalProgress && this._totalProgress.reset();
},
retry: function(id) {
return this._manualRetry(id);
},
scaleImage: function(id, specs) {
var self = this;
return qq.Scaler.prototype.scaleImage(id, specs, {
log: qq.bind(self.log, self),
getFile: qq.bind(self.getFile, self),
uploadData: self._uploadData
});
},
setCustomHeaders: function(headers, id) {
this._customHeadersStore.set(headers, id);
},
setDeleteFileCustomHeaders: function(headers, id) {
this._deleteFileCustomHeadersStore.set(headers, id);
},
setDeleteFileEndpoint: function(endpoint, id) {
this._deleteFileEndpointStore.set(endpoint, id);
},
setDeleteFileParams: function(params, id) {
this._deleteFileParamsStore.set(params, id);
},
// Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button
setEndpoint: function(endpoint, id) {
this._endpointStore.set(endpoint, id);
},
setForm: function(elementOrId) {
this._updateFormSupportAndParams(elementOrId);
},
setItemLimit: function(newItemLimit) {
this._currentItemLimit = newItemLimit;
},
setName: function(id, newName) {
this._uploadData.updateName(id, newName);
},
setParams: function(params, id) {
this._paramsStore.set(params, id);
},
setUuid: function(id, newUuid) {
return this._uploadData.uuidChanged(id, newUuid);
},
uploadStoredFiles: function() {
if (this._storedIds.length === 0) {
this._itemError("noFilesError");
}
else {
this._uploadStoredFiles();
}
}
};
/**
* Defines the private (internal) API for FineUploaderBasic mode.
*/
qq.basePrivateApi = {
// Updates internal state with a file record (not backed by a live file). Returns the assigned ID.
_addCannedFile: function(sessionData) {
var id = this._uploadData.addFile({
uuid: sessionData.uuid,
name: sessionData.name,
size: sessionData.size,
status: qq.status.UPLOAD_SUCCESSFUL
});
sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id);
if (sessionData.thumbnailUrl) {
this._thumbnailUrls[id] = sessionData.thumbnailUrl;
}
this._netUploaded++;
this._netUploadedOrQueued++;
return id;
},
_annotateWithButtonId: function(file, associatedInput) {
if (qq.isFile(file)) {
file.qqButtonId = this._getButtonId(associatedInput);
}
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequester({
method: this._options.deleteFile.method.toUpperCase(),
maxConnections: this._options.maxConnections,
uuidParamName: this._options.request.uuidName,
customHeaders: this._deleteFileCustomHeadersStore,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
cors: this._options.cors,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: qq.bind(self.log, self),
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createStore: function(initialValue, _readOnlyValues_) {
var store = {},
catchall = initialValue,
perIdReadOnlyValues = {},
readOnlyValues = _readOnlyValues_,
copy = function(orig) {
if (qq.isObject(orig)) {
return qq.extend({}, orig);
}
return orig;
},
getReadOnlyValues = function() {
if (qq.isFunction(readOnlyValues)) {
return readOnlyValues();
}
return readOnlyValues;
},
includeReadOnlyValues = function(id, existing) {
if (readOnlyValues && qq.isObject(existing)) {
qq.extend(existing, getReadOnlyValues());
}
if (perIdReadOnlyValues[id]) {
qq.extend(existing, perIdReadOnlyValues[id]);
}
};
return {
set: function(val, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
store = {};
catchall = copy(val);
}
else {
store[id] = copy(val);
}
},
get: function(id) {
var values;
/*jshint eqeqeq: true, eqnull: true*/
if (id != null && store[id]) {
values = store[id];
}
else {
values = copy(catchall);
}
includeReadOnlyValues(id, values);
return copy(values);
},
addReadOnly: function(id, values) {
// Only applicable to Object stores
if (qq.isObject(store)) {
// If null ID, apply readonly values to all files
if (id === null) {
if (qq.isFunction(values)) {
readOnlyValues = values;
}
else {
readOnlyValues = readOnlyValues || {};
qq.extend(readOnlyValues, values);
}
}
else {
perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
qq.extend(perIdReadOnlyValues[id], values);
}
}
},
remove: function(fileId) {
return delete store[fileId];
},
reset: function() {
store = {};
perIdReadOnlyValues = {};
catchall = initialValue;
}
};
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._onUploadStatusChange(id, oldStatus, newStatus);
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
self._maybeAllComplete(id, newStatus);
if (self._totalProgress) {
setTimeout(function() {
self._totalProgress.onStatusChange(id, oldStatus, newStatus);
}, 0);
}
}
});
},
/**
* Generate a tracked upload button.
*
* @param spec Object containing a required `element` property
* along with optional `multiple`, `accept`, and `folders`.
* @returns {qq.UploadButton}
* @private
*/
_createUploadButton: function(spec) {
var self = this,
acceptFiles = spec.accept || this._options.validation.acceptFiles,
allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions,
button;
function allowMultiple() {
if (qq.supportedFeatures.ajaxUploading) {
// Workaround for bug in iOS7+ (see #1039)
if (self._options.workarounds.iosEmptyVideos &&
qq.ios() &&
!qq.ios6() &&
self._isAllowedExtension(allowedExtensions, ".mov")) {
return false;
}
if (spec.multiple === undefined) {
return self._options.multiple;
}
return spec.multiple;
}
return false;
}
button = new qq.UploadButton({
element: spec.element,
folders: spec.folders,
name: this._options.request.inputName,
multiple: allowMultiple(),
acceptFiles: acceptFiles,
onChange: function(input) {
self._onInputChange(input);
},
hoverClass: this._options.classes.buttonHover,
focusClass: this._options.classes.buttonFocus,
ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash
});
this._disposeSupport.addDisposer(function() {
button.dispose();
});
self._buttons.push(button);
return button;
},
_createUploadHandler: function(additionalOptions, namespace) {
var self = this,
lastOnProgress = {},
options = {
debug: this._options.debug,
maxConnections: this._options.maxConnections,
cors: this._options.cors,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: qq.bind(self.log, self),
preventRetryParam: this._options.retry.preventRetryResponseProperty,
onProgress: function(id, name, loaded, total) {
if (loaded < 0 || total < 0) {
return;
}
if (lastOnProgress[id]) {
if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
}
else {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
lastOnProgress[id] = {loaded: loaded, total: total};
},
onComplete: function(id, name, result, xhr) {
delete lastOnProgress[id];
var status = self.getUploads({id: id}).status,
retVal;
// This is to deal with some observed cases where the XHR readyStateChange handler is
// invoked by the browser multiple times for the same XHR instance with the same state
// readyState value. Higher level: don't invoke complete-related code if we've already
// done this.
if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
return;
}
retVal = self._onComplete(id, name, result, xhr);
// If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback
// until the promise has been fulfilled.
if (retVal instanceof qq.Promise) {
retVal.done(function() {
self._options.callbacks.onComplete(id, name, result, xhr);
});
}
else {
self._options.callbacks.onComplete(id, name, result, xhr);
}
},
onCancel: function(id, name, cancelFinalizationEffort) {
var promise = new qq.Promise();
self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onFailure: promise.failure,
onSuccess: function() {
cancelFinalizationEffort.then(function() {
self._onCancel(id, name);
});
promise.success();
},
identifier: id
});
return promise;
},
onUploadPrep: qq.bind(this._onUploadPrep, this),
onUpload: function(id, name) {
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData) {
self._onUploadChunk(id, chunkData);
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onUploadChunkSuccess: function(id, chunkData, result, xhr) {
self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
return self._onAutoRetry.apply(self, arguments);
},
onUuidChanged: function(id, newUuid) {
self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
self.setUuid(id, newUuid);
},
getName: qq.bind(self.getName, self),
getUuid: qq.bind(self.getUuid, self),
getSize: qq.bind(self.getSize, self),
setSize: qq.bind(self._setSize, self),
getDataByUuid: function(uuid) {
return self.getUploads({uuid: uuid});
},
isQueued: function(id) {
var status = self.getUploads({id: id}).status;
return status === qq.status.QUEUED ||
status === qq.status.SUBMITTED ||
status === qq.status.UPLOAD_RETRYING ||
status === qq.status.PAUSED;
},
getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
getIdsInBatch: self._uploadData.getIdsInBatch
};
qq.each(this._options.request, function(prop, val) {
options[prop] = val;
});
options.customHeaders = this._customHeadersStore;
if (additionalOptions) {
qq.each(additionalOptions, function(key, val) {
options[key] = val;
});
}
return new qq.UploadHandlerController(options, namespace);
},
_fileOrBlobRejected: function(id) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.REJECTED);
},
_formatSize: function(bytes) {
var i = -1;
do {
bytes = bytes / 1000;
i++;
} while (bytes > 999);
return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i];
},
// Creates an internal object that tracks various properties of each extra button,
// and then actually creates the extra button.
_generateExtraButtonSpecs: function() {
var self = this;
this._extraButtonSpecs = {};
qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
var multiple = extraButtonOptionEntry.multiple,
validation = qq.extend({}, self._options.validation, true),
extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
if (multiple === undefined) {
multiple = self._options.multiple;
}
if (extraButtonSpec.validation) {
qq.extend(validation, extraButtonOptionEntry.validation, true);
}
qq.extend(extraButtonSpec, {
multiple: multiple,
validation: validation
}, true);
self._initExtraButton(extraButtonSpec);
});
},
_getButton: function(buttonId) {
var extraButtonsSpec = this._extraButtonSpecs[buttonId];
if (extraButtonsSpec) {
return extraButtonsSpec.element;
}
else if (buttonId === this._defaultButtonId) {
return this._options.button;
}
},
/**
* Gets the internally used tracking ID for a button.
*
* @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element
* @returns {*} The button's ID, or undefined if no ID is recoverable
* @private
*/
_getButtonId: function(buttonOrFileInputOrFile) {
var inputs, fileInput,
fileBlobOrInput = buttonOrFileInputOrFile;
// We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later)
if (fileBlobOrInput instanceof qq.BlobProxy) {
fileBlobOrInput = fileBlobOrInput.referenceBlob;
}
// If the item is a `Blob` it will never be associated with a button or drop zone.
if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
if (qq.isFile(fileBlobOrInput)) {
return fileBlobOrInput.qqButtonId;
}
else if (fileBlobOrInput.tagName.toLowerCase() === "input" &&
fileBlobOrInput.type.toLowerCase() === "file") {
return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
inputs = fileBlobOrInput.getElementsByTagName("input");
qq.each(inputs, function(idx, input) {
if (input.getAttribute("type") === "file") {
fileInput = input;
return false;
}
});
if (fileInput) {
return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
}
},
_getNotFinished: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED,
qq.status.SUBMITTING,
qq.status.SUBMITTED,
qq.status.PAUSED
]
}).length;
},
// Get the validation options for this button. Could be the default validation option
// or a specific one assigned to this particular button.
_getValidationBase: function(buttonId) {
var extraButtonSpec = this._extraButtonSpecs[buttonId];
return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
},
_getValidationDescriptor: function(fileWrapper) {
if (fileWrapper.file instanceof qq.BlobProxy) {
return {
name: qq.getFilename(fileWrapper.file.referenceBlob),
size: fileWrapper.file.referenceBlob.size
};
}
return {
name: this.getUploads({id: fileWrapper.id}).name,
size: this.getUploads({id: fileWrapper.id}).size
};
},
_getValidationDescriptors: function(fileWrappers) {
var self = this,
fileDescriptors = [];
qq.each(fileWrappers, function(idx, fileWrapper) {
fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
});
return fileDescriptors;
},
// Allows camera access on either the default or an extra button for iOS devices.
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
var acceptIosCamera = "image/*;capture=camera",
button = this._options.camera.button,
buttonId = button ? this._getButtonId(button) : this._defaultButtonId,
optionRoot = this._options;
// If we are not targeting the default button, it is an "extra" button
if (buttonId && buttonId !== this._defaultButtonId) {
optionRoot = this._extraButtonSpecs[buttonId];
}
// Camera access won't work in iOS if the `multiple` attribute is present on the file input
optionRoot.multiple = false;
// update the options
if (optionRoot.validation.acceptFiles === null) {
optionRoot.validation.acceptFiles = acceptIosCamera;
}
else {
optionRoot.validation.acceptFiles += "," + acceptIosCamera;
}
// update the already-created button
qq.each(this._buttons, function(idx, button) {
if (button.getButtonId() === buttonId) {
button.setMultiple(optionRoot.multiple);
button.setAcceptFiles(optionRoot.acceptFiles);
return false;
}
});
}
},
_handleCheckedCallback: function(details) {
var self = this,
callbackRetVal = details.callback();
if (qq.isGenericPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(
function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
},
function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
}
else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {
details.onSuccess(callbackRetVal);
}
else {
if (details.onFailure) {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
details.onFailure();
}
else {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
}
}
return callbackRetVal;
},
// Updates internal state when a new file has been received, and adds it along with its ID to a passed array.
_handleNewFile: function(file, batchId, newFileWrapperList) {
var self = this,
uuid = qq.getUniqueId(),
size = -1,
name = qq.getFilename(file),
actualFile = file.blob || file,
handler = this._customNewFileHandler ?
this._customNewFileHandler :
qq.bind(self._handleNewFileGeneric, self);
if (!qq.isInput(actualFile) && actualFile.size >= 0) {
size = actualFile.size;
}
handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
uploadData: self._uploadData,
paramsStore: self._paramsStore,
addFileToHandler: function(id, file) {
self._handler.add(id, file);
self._netUploadedOrQueued++;
self._trackButton(id);
}
});
},
_handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
var id = this._uploadData.addFile({uuid: uuid, name: name, size: size, batchId: batchId});
this._handler.add(id, file);
this._trackButton(id);
this._netUploadedOrQueued++;
fileList.push({id: id, file: file});
},
_handlePasteSuccess: function(blob, extSuppliedName) {
var extension = blob.type.split("/")[1],
name = extSuppliedName;
/*jshint eqeqeq: true, eqnull: true*/
if (name == null) {
name = this._options.paste.defaultName;
}
name += "." + extension;
this.addFiles({
name: name,
blob: blob
});
},
// Creates an extra button element
_initExtraButton: function(spec) {
var button = this._createUploadButton({
element: spec.element,
multiple: spec.multiple,
accept: spec.validation.acceptFiles,
folders: spec.folders,
allowedExtensions: spec.validation.allowedExtensions
});
this._extraButtonSpecs[button.getButtonId()] = spec;
},
_initFormSupportAndParams: function() {
this._formSupport = qq.FormSupport && new qq.FormSupport(
this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)
);
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore = this._createStore(
this._options.request.params, this._formSupport.getFormInputsAsObject
);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this._options.request.endpoint = this._formSupport.newEndpoint;
}
}
else {
this._paramsStore = this._createStore(this._options.request.params);
}
},
_isDeletePossible: function() {
if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
return false;
}
if (this._options.cors.expected) {
if (qq.supportedFeatures.deleteFileCorsXhr) {
return true;
}
if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
return true;
}
return false;
}
return true;
},
_isAllowedExtension: function(allowed, fileName) {
var valid = false;
if (!allowed.length) {
return true;
}
qq.each(allowed, function(idx, allowedExt) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExt)) {
/*jshint eqeqeq: true, eqnull: true*/
var extRegex = new RegExp("\\." + allowedExt + "$", "i");
if (fileName.match(extRegex) != null) {
valid = true;
return false;
}
}
});
return valid;
},
/**
* Constructs and returns a message that describes an item/file error. Also calls `onError` callback.
*
* @param code REQUIRED - a code that corresponds to a stock message describing this type of error
* @param maybeNameOrNames names of the items that have failed, if applicable
* @param item `File`, `Blob`, or `<input type="file">`
* @private
*/
_itemError: function(code, maybeNameOrNames, item) {
var message = this._options.messages[code],
allowedExtensions = [],
names = [].concat(maybeNameOrNames),
name = names[0],
buttonId = this._getButtonId(item),
validationBase = this._getValidationBase(buttonId),
extensionsForMessage, placeholderMatch;
function r(name, replacement) { message = message.replace(name, replacement); }
qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExtension)) {
allowedExtensions.push(allowedExtension);
}
});
extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
r("{file}", this._options.formatFileName(name));
r("{extensions}", extensionsForMessage);
r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
placeholderMatch = message.match(/(\{\w+\})/g);
if (placeholderMatch !== null) {
qq.each(placeholderMatch, function(idx, placeholder) {
r(placeholder, names[idx]);
});
}
this._options.callbacks.onError(null, name, message, undefined);
return message;
},
/**
* Conditionally orders a manual retry of a failed upload.
*
* @param id File ID of the failed upload
* @param callback Optional callback to invoke if a retry is prudent.
* In lieu of asking the upload handler to retry.
* @returns {boolean} true if a manual retry will occur
* @private
*/
_manualRetry: function(id, callback) {
if (this._onBeforeManualRetry(id)) {
this._netUploadedOrQueued++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
}
else {
this._handler.retry(id);
}
return true;
}
},
_maybeAllComplete: function(id, status) {
var self = this,
notFinished = this._getNotFinished();
if (status === qq.status.UPLOAD_SUCCESSFUL) {
this._succeededSinceLastAllComplete.push(id);
}
else if (status === qq.status.UPLOAD_FAILED) {
this._failedSinceLastAllComplete.push(id);
}
if (notFinished === 0 &&
(this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
// Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete
setTimeout(function() {
self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
}, 0);
}
},
_maybeHandleIos8SafariWorkaround: function() {
var self = this;
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
setTimeout(function() {
window.alert(self._options.messages.unsupportedBrowserIos8Safari);
}, 0);
throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
}
},
_maybeParseAndSendUploadError: function(id, name, response, xhr) {
// Assuming no one will actually set the response code to something other than 200
// and still set 'success' to true...
if (!response.success) {
if (xhr && xhr.status !== 200 && !response.error) {
this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
}
else {
var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
this._options.callbacks.onError(id, name, errorReason, xhr);
}
}
},
_maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
var self = this;
if (items.length > index) {
if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
//use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks
setTimeout(function() {
var validationDescriptor = self._getValidationDescriptor(items[index]),
buttonId = self._getButtonId(items[index].file),
button = self._getButton(buttonId);
self._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
});
}, 0);
}
else if (!validItem) {
for (; index < items.length; index++) {
self._fileOrBlobRejected(items[index].id);
}
}
}
},
_onAllComplete: function(successful, failed) {
this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
},
/**
* Attempt to automatically retry a failed upload.
*
* @param id The file ID of the failed upload
* @param name The name of the file associated with the failed upload
* @param responseJSON Response from the server, parsed into a javascript object
* @param xhr Ajax transport used to send the failed request
* @param callback Optional callback to be invoked if a retry is prudent.
* Invoked in lieu of asking the upload handler to retry.
* @returns {boolean} true if an auto-retry will occur
* @private
*/
_onAutoRetry: function(id, name, responseJSON, xhr, callback) {
var self = this;
self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
if (self._shouldAutoRetry(id, name, responseJSON)) {
self._maybeParseAndSendUploadError.apply(self, arguments);
self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
self._onBeforeAutoRetry(id, name);
self._retryTimeouts[id] = setTimeout(function() {
self.log("Retrying " + name + "...");
self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
}
else {
self._handler.retry(id);
}
}, self._options.retry.autoAttemptDelay * 1000);
return true;
}
},
_onBeforeAutoRetry: function(id, name) {
this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
var itemLimit = this._currentItemLimit,
fileName;
if (this._preventRetries[id]) {
this.log("Retries are forbidden for id " + id, "warn");
return false;
}
else if (this._handler.isValid(id)) {
fileName = this.getName(id);
if (this._options.callbacks.onManualRetry(id, fileName) === false) {
return false;
}
if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
this._itemError("retryFailTooManyItems");
return false;
}
this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
return true;
}
else {
this.log("'" + id + "' is not a valid file ID", "error");
return false;
}
},
_onCancel: function(id, name) {
this._netUploadedOrQueued--;
clearTimeout(this._retryTimeouts[id]);
var storedItemIndex = qq.indexOf(this._storedIds, id);
if (!this._options.autoUpload && storedItemIndex >= 0) {
this._storedIds.splice(storedItemIndex, 1);
}
this._uploadData.setStatus(id, qq.status.CANCELED);
},
_onComplete: function(id, name, result, xhr) {
if (!result.success) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
if (result[this._options.retry.preventRetryResponseProperty] === true) {
this._preventRetries[id] = true;
}
}
else {
if (result.thumbnailUrl) {
this._thumbnailUrls[id] = result.thumbnailUrl;
}
this._netUploaded++;
this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
}
this._maybeParseAndSendUploadError(id, name, result, xhr);
return result.success ? true : false;
},
_onDelete: function(id) {
this._uploadData.setStatus(id, qq.status.DELETING);
},
_onDeleteComplete: function(id, xhrOrXdr, isError) {
var name = this.getName(id);
if (isError) {
this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
this.log("Delete request for '" + name + "' has failed.", "error");
// For error reporing, we only have accesss to the response status if this is not
// an `XDomainRequest`.
if (xhrOrXdr.withCredentials === undefined) {
this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
}
else {
this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
}
}
else {
this._netUploadedOrQueued--;
this._netUploaded--;
this._handler.expunge(id);
this._uploadData.setStatus(id, qq.status.DELETED);
this.log("Delete request for '" + name + "' has succeeded.");
}
},
_onInputChange: function(input) {
var fileIndex;
if (qq.supportedFeatures.ajaxUploading) {
for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
this._annotateWithButtonId(input.files[fileIndex], input);
}
this.addFiles(input.files);
}
// Android 2.3.x will fire `onchange` even if no file has been selected
else if (input.value.length > 0) {
this.addFiles(input);
}
qq.each(this._buttons, function(idx, button) {
button.reset();
});
},
_onProgress: function(id, name, loaded, total) {
this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
},
_onSubmit: function(id, name) {
//nothing to do yet in core uploader
},
_onSubmitCallbackSuccess: function(id, name) {
this._onSubmit.apply(this, arguments);
this._uploadData.setStatus(id, qq.status.SUBMITTED);
this._onSubmitted.apply(this, arguments);
if (this._options.autoUpload) {
this._options.callbacks.onSubmitted.apply(this, arguments);
this._uploadFile(id);
}
else {
this._storeForLater(id);
this._options.callbacks.onSubmitted.apply(this, arguments);
}
},
_onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
var uuid = this.getUuid(id),
adjustedOnSuccessCallback;
if (onSuccessCallback) {
adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
}
if (this._isDeletePossible()) {
this._handleCheckedCallback({
name: "onSubmitDelete",
callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
onSuccess: adjustedOnSuccessCallback ||
qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
identifier: id
});
return true;
}
else {
this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " +
"due to CORS on a user agent that does not support pre-flighting.", "warn");
return false;
}
},
_onSubmitted: function(id) {
//nothing to do in the base uploader
},
_onTotalProgress: function(loaded, total) {
this._options.callbacks.onTotalProgress(loaded, total);
},
_onUploadPrep: function(id) {
// nothing to do in the core uploader for now
},
_onUpload: function(id, name) {
this._uploadData.setStatus(id, qq.status.UPLOADING);
},
_onUploadChunk: function(id, chunkData) {
//nothing to do in the base uploader
},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
// Make sure a "queued" retry attempt is canceled if the upload has been paused
if (newStatus === qq.status.PAUSED) {
clearTimeout(this._retryTimeouts[id]);
}
},
_onValidateBatchCallbackFailure: function(fileWrappers) {
var self = this;
qq.each(fileWrappers, function(idx, fileWrapper) {
self._fileOrBlobRejected(fileWrapper.id);
});
},
_onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
var errorMessage,
itemLimit = this._currentItemLimit,
proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
if (items.length > 0) {
this._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
});
}
else {
this._itemError("noFilesError");
}
}
else {
this._onValidateBatchCallbackFailure(items);
errorMessage = this._options.messages.tooManyItemsError
.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued)
.replace(/\{itemLimit\}/g, itemLimit);
this._batchError(errorMessage);
}
},
_onValidateCallbackFailure: function(items, index, params, endpoint) {
var nextIndex = index + 1;
this._fileOrBlobRejected(items[index].id, items[index].file.name);
this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
},
_onValidateCallbackSuccess: function(items, index, params, endpoint) {
var self = this,
nextIndex = index + 1,
validationDescriptor = this._getValidationDescriptor(items[index]);
this._validateFileOrBlobData(items[index], validationDescriptor)
.then(
function() {
self._upload(items[index].id, params, endpoint);
self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
},
function() {
self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
}
);
},
_prepareItemsForUpload: function(items, params, endpoint) {
if (items.length === 0) {
this._itemError("noFilesError");
return;
}
var validationDescriptors = this._getValidationDescriptors(items),
buttonId = this._getButtonId(items[0].file),
button = this._getButton(buttonId);
this._handleCheckedCallback({
name: "onValidateBatch",
callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
identifier: "batch validation"
});
},
_preventLeaveInProgress: function() {
var self = this;
this._disposeSupport.attach(window, "beforeunload", function(e) {
if (self.getInProgress()) {
e = e || window.event;
// for ie, ff
e.returnValue = self._options.messages.onLeave;
// for webkit
return self._options.messages.onLeave;
}
});
},
// Attempts to refresh session data only if the `qq.Session` module exists
// and a session endpoint has been specified. The `onSessionRequestComplete`
// callback will be invoked once the refresh is complete.
_refreshSessionData: function() {
var self = this,
options = this._options.session;
/* jshint eqnull:true */
if (qq.Session && this._options.session.endpoint != null) {
if (!this._session) {
qq.extend(options, this._options.cors);
options.log = qq.bind(this.log, this);
options.addFileRecord = qq.bind(this._addCannedFile, this);
this._session = new qq.Session(options);
}
setTimeout(function() {
self._session.refresh().then(function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
}, function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
});
}, 0);
}
},
_setSize: function(id, newSize) {
this._uploadData.updateSize(id, newSize);
this._totalProgress && this._totalProgress.onNewSize(id);
},
_shouldAutoRetry: function(id, name, responseJSON) {
var uploadData = this._uploadData.retrieve({id: id});
/*jshint laxbreak: true */
if (!this._preventRetries[id]
&& this._options.retry.enableAuto
&& uploadData.status !== qq.status.PAUSED) {
if (this._autoRetries[id] === undefined) {
this._autoRetries[id] = 0;
}
if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
this._autoRetries[id] += 1;
return true;
}
}
return false;
},
_storeForLater: function(id) {
this._storedIds.push(id);
},
// Maps a file with the button that was used to select it.
_trackButton: function(id) {
var buttonId;
if (qq.supportedFeatures.ajaxUploading) {
buttonId = this._handler.getFile(id).qqButtonId;
}
else {
buttonId = this._getButtonId(this._handler.getInput(id));
}
if (buttonId) {
this._buttonIdsForFileIds[id] = buttonId;
}
},
_updateFormSupportAndParams: function(formElementOrId) {
this._options.form.element = formElementOrId;
this._formSupport = qq.FormSupport && new qq.FormSupport(
this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)
);
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this.setEndpoint(this._formSupport.newEndpoint);
}
}
},
_upload: function(id, params, endpoint) {
var name = this.getName(id);
if (params) {
this.setParams(params, id);
}
if (endpoint) {
this.setEndpoint(endpoint, id);
}
this._handleCheckedCallback({
name: "onSubmit",
callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
identifier: id
});
},
_uploadFile: function(id) {
if (!this._handler.upload(id)) {
this._uploadData.setStatus(id, qq.status.QUEUED);
}
},
_uploadStoredFiles: function() {
var idToUpload, stillSubmitting,
self = this;
while (this._storedIds.length) {
idToUpload = this._storedIds.shift();
this._uploadFile(idToUpload);
}
// If we are still waiting for some files to clear validation, attempt to upload these again in a bit
stillSubmitting = this.getUploads({status: qq.status.SUBMITTING}).length;
if (stillSubmitting) {
qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly.");
setTimeout(function() {
self._uploadStoredFiles();
}, 1000);
}
},
/**
* Performs some internal validation checks on an item, defined in the `validation` option.
*
* @param fileWrapper Wrapper containing a `file` along with an `id`
* @param validationDescriptor Normalized information about the item (`size`, `name`).
* @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file
* @private
*/
_validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
var self = this,
file = (function() {
if (fileWrapper.file instanceof qq.BlobProxy) {
return fileWrapper.file.referenceBlob;
}
return fileWrapper.file;
}()),
name = validationDescriptor.name,
size = validationDescriptor.size,
buttonId = this._getButtonId(fileWrapper.file),
validationBase = this._getValidationBase(buttonId),
validityChecker = new qq.Promise();
validityChecker.then(
function() {},
function() {
self._fileOrBlobRejected(fileWrapper.id, name);
});
if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
this._itemError("typeError", name, file);
return validityChecker.failure();
}
if (size === 0) {
this._itemError("emptyError", name, file);
return validityChecker.failure();
}
if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
this._itemError("sizeError", name, file);
return validityChecker.failure();
}
if (size > 0 && size < validationBase.minSizeLimit) {
this._itemError("minSizeError", name, file);
return validityChecker.failure();
}
if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(
validityChecker.success,
function(errorCode) {
self._itemError(errorCode + "ImageError", name, file);
validityChecker.failure();
}
);
}
else {
validityChecker.success();
}
return validityChecker;
},
_wrapCallbacks: function() {
var self, safeCallback, prop;
self = this;
safeCallback = function(name, callback, args) {
var errorMsg;
try {
return callback.apply(self, args);
}
catch (exception) {
errorMsg = exception.message || exception.toString();
self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
}
};
/* jshint forin: false, loopfunc: true */
for (prop in this._options.callbacks) {
(function() {
var callbackName, callbackFunc;
callbackName = prop;
callbackFunc = self._options.callbacks[callbackName];
self._options.callbacks[callbackName] = function() {
return safeCallback(callbackName, callbackFunc, arguments);
};
}());
}
}
};
}());
/*globals qq*/
(function() {
"use strict";
qq.FineUploaderBasic = function(o) {
var self = this;
// These options define FineUploaderBasic mode.
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
customHeaders: {},
endpoint: "/server/upload",
filenameParam: "qqfilename",
forceMultipart: true,
inputName: "qqfile",
method: "POST",
params: {},
paramsInBody: true,
totalFileSizeName: "qqtotalfilesize",
uuidName: "qquuid"
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null,
image: {
maxHeight: 0,
maxWidth: 0,
minHeight: 0,
minWidth: 0
}
},
callbacks: {
onSubmit: function(id, name) {},
onSubmitted: function(id, name) {},
onComplete: function(id, name, responseJSON, maybeXhr) {},
onAllComplete: function(successful, failed) {},
onCancel: function(id, name) {},
onUpload: function(id, name) {},
onUploadChunk: function(id, name, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
onResume: function(id, fileName, chunkData) {},
onProgress: function(id, name, loaded, total) {},
onTotalProgress: function(loaded, total) {},
onError: function(id, name, reason, maybeXhrOrXdr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {},
onSessionRequestComplete: function(response, success, xhrOrXdr) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
maxHeightImageError: "Image is too tall.",
maxWidthImageError: "Image is too wide.",
minHeightImageError: "Image is not tall enough.",
minWidthImageError: "Image is not wide enough.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: "preventRetry"
},
classes: {
buttonHover: "qq-upload-button-hover",
buttonFocus: "qq-upload-button-focus"
},
chunking: {
enabled: false,
concurrent: {
enabled: false
},
mandatory: false,
paramNames: {
partIndex: "qqpartindex",
partByteOffset: "qqpartbyteoffset",
chunkSize: "qqchunksize",
totalFileSize: "qqtotalfilesize",
totalParts: "qqtotalparts"
},
partSize: 2000000,
// only relevant for traditional endpoints, only required when concurrent.enabled === true
success: {
endpoint: null
}
},
resume: {
enabled: false,
recordsExpireIn: 7, //days
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"]
},
deleteFile: {
enabled: false,
method: "DELETE",
endpoint: "/server/upload",
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false,
allowXdr: false
},
blobs: {
defaultName: "misc_data"
},
paste: {
targetElement: null,
defaultName: "pasted_image"
},
camera: {
ios: false,
// if ios is true: button is null means target the default button, otherwise target the button specified
button: null
},
// This refers to additional upload buttons to be handled by Fine Uploader.
// Each element is an object, containing `element` as the only required
// property. The `element` must be a container that will ultimately
// contain an invisible `<input type="file">` created by Fine Uploader.
// Optional properties of each object include `multiple`, `validation`,
// and `folders`.
extraButtons: [],
// Depends on the session module. Used to query the server for an initial file list
// during initialization and optionally after a `reset`.
session: {
endpoint: null,
params: {},
customHeaders: {},
refreshOnReset: true
},
// Send parameters associated with an existing form along with the files
form: {
// Element ID, HTMLElement, or null
element: "qq-form",
// Overrides the base `autoUpload`, unless `element` is null.
autoUpload: false,
// true = upload files on form submission (and squelch submit event)
interceptSubmit: true
},
// scale images client side, upload a new file for each scaled version
scaling: {
// send the original file as well
sendOriginal: true,
// fox orientation for scaled images
orient: true,
// If null, scaled image type will match reference image type. This value will be referred to
// for any size record that does not specific a type.
defaultType: null,
defaultQuality: 80,
failureText: "Failed to scale",
includeExif: false,
// metadata about each requested scaled version
sizes: []
},
workarounds: {
iosEmptyVideos: true,
ios8SafariUploads: true,
ios8BrowserCrash: false
}
};
// Replace any default options with user defined ones
qq.extend(this._options, o, true);
this._buttons = [];
this._extraButtonSpecs = {};
this._buttonIdsForFileIds = [];
this._wrapCallbacks();
this._disposeSupport = new qq.DisposeSupport();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData = this._createUploadDataTracker();
this._initFormSupportAndParams();
this._customHeadersStore = this._createStore(this._options.request.customHeaders);
this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
this._endpointStore = this._createStore(this._options.request.endpoint);
this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
this._handler = this._createUploadHandler();
this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
if (this._options.button) {
this._defaultButtonId = this._createUploadButton({element: this._options.button}).getButtonId();
}
this._generateExtraButtonSpecs();
this._handleCameraAccess();
if (this._options.paste.targetElement) {
if (qq.PasteSupport) {
this._pasteHandler = this._createPasteHandler();
}
else {
this.log("Paste support module not found", "error");
}
}
this._preventLeaveInProgress();
this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._scaler = (qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this))) || {};
if (this._scaler.enabled) {
this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
}
if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
this._totalProgress = new qq.TotalProgress(
qq.bind(this._onTotalProgress, this),
function(id) {
var entry = self._uploadData.retrieve({id: id});
return (entry && entry.size) || 0;
}
);
}
this._currentItemLimit = this._options.validation.itemLimit;
};
// Define the private & public API methods.
qq.FineUploaderBasic.prototype = qq.basePublicApi;
qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
}());
/*globals qq, XDomainRequest*/
/** Generic class for sending non-upload ajax requests and handling the associated responses **/
qq.AjaxRequester = function(o) {
"use strict";
var log, shouldParamsBeInQueryString,
queue = [],
requestData = {},
options = {
acceptHeader: null,
validMethods: ["PATCH", "POST", "PUT"],
method: "POST",
contentType: "application/x-www-form-urlencoded",
maxConnections: 3,
customHeaders: {},
endpointStore: {},
paramsStore: {},
mandatedParams: {},
allowXRequestedWithAndCacheControl: true,
successfulResponseCodes: {
DELETE: [200, 202, 204],
PATCH: [200, 201, 202, 203, 204],
POST: [200, 201, 202, 203, 204],
PUT: [200, 201, 202, 203, 204],
GET: [200]
},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onSend: function(id) {},
onComplete: function(id, xhrOrXdr, isError) {},
onProgress: null
};
qq.extend(options, o);
log = options.log;
if (qq.indexOf(options.validMethods, options.method) < 0) {
throw new Error("'" + options.method + "' is not a supported method for this type of request!");
}
// [Simple methods](http://www.w3.org/TR/cors/#simple-method)
// are defined by the W3C in the CORS spec as a list of methods that, in part,
// make a CORS request eligible to be exempt from preflighting.
function isSimpleMethod() {
return qq.indexOf(["GET", "POST", "HEAD"], options.method) >= 0;
}
// [Simple headers](http://www.w3.org/TR/cors/#simple-header)
// are defined by the W3C in the CORS spec as a list of headers that, in part,
// make a CORS request eligible to be exempt from preflighting.
function containsNonSimpleHeaders(headers) {
var containsNonSimple = false;
qq.each(containsNonSimple, function(idx, header) {
if (qq.indexOf(["Accept", "Accept-Language", "Content-Language", "Content-Type"], header) < 0) {
containsNonSimple = true;
return false;
}
});
return containsNonSimple;
}
function isXdr(xhr) {
//The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS.
return options.cors.expected && xhr.withCredentials === undefined;
}
// Returns either a new `XMLHttpRequest` or `XDomainRequest` instance.
function getCorsAjaxTransport() {
var xhrOrXdr;
if (window.XMLHttpRequest || window.ActiveXObject) {
xhrOrXdr = qq.createXhrInstance();
if (xhrOrXdr.withCredentials === undefined) {
xhrOrXdr = new XDomainRequest();
}
}
return xhrOrXdr;
}
// Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`.
function getXhrOrXdr(id, suppliedXhr) {
var xhrOrXdr = requestData[id].xhr;
if (!xhrOrXdr) {
if (suppliedXhr) {
xhrOrXdr = suppliedXhr;
}
else {
if (options.cors.expected) {
xhrOrXdr = getCorsAjaxTransport();
}
else {
xhrOrXdr = qq.createXhrInstance();
}
}
requestData[id].xhr = xhrOrXdr;
}
return xhrOrXdr;
}
// Removes element from queue, sends next request
function dequeue(id) {
var i = qq.indexOf(queue, id),
max = options.maxConnections,
nextId;
delete requestData[id];
queue.splice(i, 1);
if (queue.length >= max && i < max) {
nextId = queue[max - 1];
sendRequest(nextId);
}
}
function onComplete(id, xdrError) {
var xhr = getXhrOrXdr(id),
method = options.method,
isError = xdrError === true;
dequeue(id);
if (isError) {
log(method + " request for " + id + " has failed", "error");
}
else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
isError = true;
log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
}
options.onComplete(id, xhr, isError);
}
function getParams(id) {
var onDemandParams = requestData[id].additionalParams,
mandatedParams = options.mandatedParams,
params;
if (options.paramsStore.get) {
params = options.paramsStore.get(id);
}
if (onDemandParams) {
qq.each(onDemandParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
if (mandatedParams) {
qq.each(mandatedParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
return params;
}
function sendRequest(id, optXhr) {
var xhr = getXhrOrXdr(id, optXhr),
method = options.method,
params = getParams(id),
payload = requestData[id].payload,
url;
options.onSend(id);
url = createUrl(id, params);
// XDR and XHR status detection APIs differ a bit.
if (isXdr(xhr)) {
xhr.onload = getXdrLoadHandler(id);
xhr.onerror = getXdrErrorHandler(id);
}
else {
xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
}
registerForUploadProgress(id);
// The last parameter is assumed to be ignored if we are actually using `XDomainRequest`.
xhr.open(method, url, true);
// Instruct the transport to send cookies along with the CORS request,
// unless we are using `XDomainRequest`, which is not capable of this.
if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
xhr.withCredentials = true;
}
setHeaders(id);
log("Sending " + method + " request for " + id);
if (payload) {
xhr.send(payload);
}
else if (shouldParamsBeInQueryString || !params) {
xhr.send();
}
else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
xhr.send(qq.obj2url(params, ""));
}
else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
xhr.send(JSON.stringify(params));
}
else {
xhr.send(params);
}
return xhr;
}
function createUrl(id, params) {
var endpoint = options.endpointStore.get(id),
addToPath = requestData[id].addToPath;
/*jshint -W116,-W041 */
if (addToPath != undefined) {
endpoint += "/" + addToPath;
}
if (shouldParamsBeInQueryString && params) {
return qq.obj2url(params, endpoint);
}
else {
return endpoint;
}
}
// Invoked by the UA to indicate a number of possible states that describe
// a live `XMLHttpRequest` transport.
function getXhrReadyStateChangeHandler(id) {
return function() {
if (getXhrOrXdr(id).readyState === 4) {
onComplete(id);
}
};
}
function registerForUploadProgress(id) {
var onProgress = options.onProgress;
if (onProgress) {
getXhrOrXdr(id).upload.onprogress = function(e) {
if (e.lengthComputable) {
onProgress(id, e.loaded, e.total);
}
};
}
}
// This will be called by IE to indicate **success** for an associated
// `XDomainRequest` transported request.
function getXdrLoadHandler(id) {
return function() {
onComplete(id);
};
}
// This will be called by IE to indicate **failure** for an associated
// `XDomainRequest` transported request.
function getXdrErrorHandler(id) {
return function() {
onComplete(id, true);
};
}
function setHeaders(id) {
var xhr = getXhrOrXdr(id),
customHeaders = options.customHeaders,
onDemandHeaders = requestData[id].additionalHeaders || {},
method = options.method,
allHeaders = {};
// If XDomainRequest is being used, we can't set headers, so just ignore this block.
if (!isXdr(xhr)) {
options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
// Only attempt to add X-Requested-With & Cache-Control if permitted
if (options.allowXRequestedWithAndCacheControl) {
// Do not add X-Requested-With & Cache-Control if this is a cross-origin request
// OR the cross-origin request contains a non-simple method or header.
// This is done to ensure a preflight is not triggered exclusively based on the
// addition of these 2 non-simple headers.
if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
}
}
if (options.contentType && (method === "POST" || method === "PUT")) {
xhr.setRequestHeader("Content-Type", options.contentType);
}
qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
qq.extend(allHeaders, onDemandHeaders);
qq.each(allHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
}
function isResponseSuccessful(responseCode) {
return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
}
function prepareToSend(id, optXhr, addToPath, additionalParams, additionalHeaders, payload) {
requestData[id] = {
addToPath: addToPath,
additionalParams: additionalParams,
additionalHeaders: additionalHeaders,
payload: payload
};
var len = queue.push(id);
// if too many active connections, wait...
if (len <= options.maxConnections) {
return sendRequest(id, optXhr);
}
}
shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
qq.extend(this, {
// Start the process of sending the request. The ID refers to the file associated with the request.
initTransport: function(id) {
var path, params, headers, payload, cacheBuster;
return {
// Optionally specify the end of the endpoint path for the request.
withPath: function(appendToPath) {
path = appendToPath;
return this;
},
// Optionally specify additional parameters to send along with the request.
// These will be added to the query string for GET/DELETE requests or the payload
// for POST/PUT requests. The Content-Type of the request will be used to determine
// how these parameters should be formatted as well.
withParams: function(additionalParams) {
params = additionalParams;
return this;
},
// Optionally specify additional headers to send along with the request.
withHeaders: function(additionalHeaders) {
headers = additionalHeaders;
return this;
},
// Optionally specify a payload/body for the request.
withPayload: function(thePayload) {
payload = thePayload;
return this;
},
// Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE)
withCacheBuster: function() {
cacheBuster = true;
return this;
},
// Send the constructed request.
send: function(optXhr) {
if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) {
params.qqtimestamp = new Date().getTime();
}
return prepareToSend(id, optXhr, path, params, headers, payload);
}
};
},
canceled: function(id) {
dequeue(id);
}
});
};
/* globals qq */
/**
* Common upload handler functions.
*
* @constructor
*/
qq.UploadHandler = function(spec) {
"use strict";
var proxy = spec.proxy,
fileState = {},
onCancel = proxy.onCancel,
getName = proxy.getName;
qq.extend(this, {
add: function(id, fileItem) {
fileState[id] = fileItem;
fileState[id].temp = {};
},
cancel: function(id) {
var self = this,
cancelFinalizationEffort = new qq.Promise(),
onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
onCancelRetVal.then(function() {
if (self.isValid(id)) {
fileState[id].canceled = true;
self.expunge(id);
}
cancelFinalizationEffort.success();
});
},
expunge: function(id) {
delete fileState[id];
},
getThirdPartyFileId: function(id) {
return fileState[id].key;
},
isValid: function(id) {
return fileState[id] !== undefined;
},
reset: function() {
fileState = {};
},
_getFileState: function(id) {
return fileState[id];
},
_setThirdPartyFileId: function(id, thirdPartyFileId) {
fileState[id].key = thirdPartyFileId;
},
_wasCanceled: function(id) {
return !!fileState[id].canceled;
}
});
};
/*globals qq*/
/**
* Base upload handler module. Controls more specific handlers.
*
* @param o Options. Passed along to the specific handler submodule as well.
* @param namespace [optional] Namespace for the specific handler.
*/
qq.UploadHandlerController = function(o, namespace) {
"use strict";
var controller = this,
chunkingPossible = false,
concurrentChunkingPossible = false,
chunking, preventRetryResponse, log, handler,
options = {
paramsStore: {},
maxConnections: 3, // maximum number of concurrent uploads
chunking: {
enabled: false,
multiple: {
enabled: false
}
},
log: function(str, level) {},
onProgress: function(id, fileName, loaded, total) {},
onComplete: function(id, fileName, response, xhr) {},
onCancel: function(id, fileName) {},
onUploadPrep: function(id) {}, // Called if non-trivial operations will be performed before onUpload
onUpload: function(id, fileName) {},
onUploadChunk: function(id, fileName, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
onAutoRetry: function(id, fileName, response, xhr) {},
onResume: function(id, fileName, chunkData) {},
onUuidChanged: function(id, newUuid) {},
getName: function(id) {},
setSize: function(id, newSize) {},
isQueued: function(id) {},
getIdsInProxyGroup: function(id) {},
getIdsInBatch: function(id) {}
},
chunked = {
// Called when each chunk has uploaded successfully
done: function(id, chunkIdx, response, xhr) {
var chunkData = handler._getChunkData(id, chunkIdx);
handler._getFileState(id).attemptingResume = false;
delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
handler._getFileState(id).loaded += chunkData.size;
options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
},
// Called when all chunks have been successfully uploaded and we want to ask the handler to perform any
// logic associated with closing out the file, such as combining the chunks.
finalize: function(id) {
var size = options.getSize(id),
name = options.getName(id);
log("All chunks have been uploaded for " + id + " - finalizing....");
handler.finalizeChunks(id).then(
function(response, xhr) {
log("Finalize successful for " + id);
var normaizedResponse = upload.normalizeResponse(response, true);
options.onProgress(id, name, size, size);
handler._maybeDeletePersistedChunkData(id);
upload.cleanup(id, normaizedResponse, xhr);
},
function(response, xhr) {
var normaizedResponse = upload.normalizeResponse(response, false);
log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
if (normaizedResponse.reset) {
chunked.reset(id);
}
if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
upload.cleanup(id, normaizedResponse, xhr);
}
}
);
},
hasMoreParts: function(id) {
return !!handler._getFileState(id).chunking.remaining.length;
},
nextPart: function(id) {
var nextIdx = handler._getFileState(id).chunking.remaining.shift();
if (nextIdx >= handler._getTotalChunks(id)) {
nextIdx = null;
}
return nextIdx;
},
reset: function(id) {
log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
handler._maybeDeletePersistedChunkData(id);
handler.reevaluateChunking(id);
handler._getFileState(id).loaded = 0;
},
sendNext: function(id) {
var size = options.getSize(id),
name = options.getName(id),
chunkIdx = chunked.nextPart(id),
chunkData = handler._getChunkData(id, chunkIdx),
resuming = handler._getFileState(id).attemptingResume,
inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
if (handler._getFileState(id).loaded == null) {
handler._getFileState(id).loaded = 0;
}
// Don't follow-through with the resume attempt if the integrator returns false from onResume
if (resuming && options.onResume(id, name, chunkData) === false) {
chunked.reset(id);
chunkIdx = chunked.nextPart(id);
chunkData = handler._getChunkData(id, chunkIdx);
resuming = false;
}
// If all chunks have already uploaded successfully, we must be re-attempting the finalize step.
if (chunkIdx == null && inProgressChunks.length === 0) {
chunked.finalize(id);
}
// Send the next chunk
else {
log("Sending chunked upload request for item " + id + ": bytes " + (chunkData.start + 1) + "-" + chunkData.end + " of " + size);
options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
inProgressChunks.push(chunkIdx);
handler._getFileState(id).chunking.inProgress = inProgressChunks;
if (concurrentChunkingPossible) {
connectionManager.open(id, chunkIdx);
}
if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
chunked.sendNext(id);
}
handler.uploadChunk(id, chunkIdx, resuming).then(
// upload chunk success
function success(response, xhr) {
log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var inProgressChunks = handler._getFileState(id).chunking.inProgress || [],
responseToReport = upload.normalizeResponse(response, true),
inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
chunked.done(id, chunkIdx, responseToReport, xhr);
if (inProgressChunkIdx >= 0) {
inProgressChunks.splice(inProgressChunkIdx, 1);
}
handler._maybePersistChunkedState(id);
if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
chunked.finalize(id);
}
else if (chunked.hasMoreParts(id)) {
chunked.sendNext(id);
}
},
// upload chunk failure
function failure(response, xhr) {
log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var responseToReport = upload.normalizeResponse(response, false),
inProgressIdx;
if (responseToReport.reset) {
chunked.reset(id);
}
else {
inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
if (inProgressIdx >= 0) {
handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
}
}
// We may have aborted all other in-progress chunks for this file due to a failure.
// If so, ignore the failures associated with those aborts.
if (!handler._getFileState(id).temp.ignoreFailure) {
// If this chunk has failed, we want to ignore all other failures of currently in-progress
// chunks since they will be explicitly aborted
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = true;
qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
ckXhr.abort();
});
// We must indicate that all aborted chunks are no longer in progress
handler.moveInProgressToRemaining(id);
// Free up any connections used by these chunks, but don't allow any
// other files to take up the connections (until we have exhausted all auto-retries)
connectionManager.free(id, true);
}
if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
// If one chunk fails, abort all of the others to avoid odd race conditions that occur
// if a chunk succeeds immediately after one fails before we have determined if the upload
// is a failure or not.
upload.cleanup(id, responseToReport, xhr);
}
}
}
)
.done(function() {
handler.clearXhr(id, chunkIdx);
}) ;
}
}
},
connectionManager = {
_open: [],
_openChunks: {},
_waiting: [],
available: function() {
var max = options.maxConnections,
openChunkEntriesCount = 0,
openChunksCount = 0;
qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
openChunkEntriesCount++;
openChunksCount += openChunkIndexes.length;
});
return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
},
/**
* Removes element from queue, starts upload of next
*/
free: function(id, dontAllowNext) {
var allowNext = !dontAllowNext,
waitingIndex = qq.indexOf(connectionManager._waiting, id),
connectionsIndex = qq.indexOf(connectionManager._open, id),
nextId;
delete connectionManager._openChunks[id];
if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
log("Generated blob upload has ended for " + id + ", disposing generated blob.");
delete handler._getFileState(id).file;
}
// If this file was not consuming a connection, it was just waiting, so remove it from the waiting array
if (waitingIndex >= 0) {
connectionManager._waiting.splice(waitingIndex, 1);
}
// If this file was consuming a connection, allow the next file to be uploaded
else if (allowNext && connectionsIndex >= 0) {
connectionManager._open.splice(connectionsIndex, 1);
nextId = connectionManager._waiting.shift();
if (nextId >= 0) {
connectionManager._open.push(nextId);
upload.start(nextId);
}
}
},
getWaitingOrConnected: function() {
var waitingOrConnected = [];
// Chunked files may have multiple connections open per chunk (if concurrent chunking is enabled)
// We need to grab the file ID of any file that has at least one chunk consuming a connection.
qq.each(connectionManager._openChunks, function(fileId, chunks) {
if (chunks && chunks.length) {
waitingOrConnected.push(parseInt(fileId));
}
});
// For non-chunked files, only one connection will be consumed per file.
// This is where we aggregate those file IDs.
qq.each(connectionManager._open, function(idx, fileId) {
if (!connectionManager._openChunks[fileId]) {
waitingOrConnected.push(parseInt(fileId));
}
});
// There may be files waiting for a connection.
waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
return waitingOrConnected;
},
isUsingConnection: function(id) {
return qq.indexOf(connectionManager._open, id) >= 0;
},
open: function(id, chunkIdx) {
if (chunkIdx == null) {
connectionManager._waiting.push(id);
}
if (connectionManager.available()) {
if (chunkIdx == null) {
connectionManager._waiting.pop();
connectionManager._open.push(id);
}
else {
(function() {
var openChunksEntry = connectionManager._openChunks[id] || [];
openChunksEntry.push(chunkIdx);
connectionManager._openChunks[id] = openChunksEntry;
}());
}
return true;
}
return false;
},
reset: function() {
connectionManager._waiting = [];
connectionManager._open = [];
}
},
simple = {
send: function(id, name) {
handler._getFileState(id).loaded = 0;
log("Sending simple upload request for " + id);
handler.uploadFile(id).then(
function(response, optXhr) {
log("Simple upload request succeeded for " + id);
var responseToReport = upload.normalizeResponse(response, true),
size = options.getSize(id);
options.onProgress(id, name, size, size);
upload.maybeNewUuid(id, responseToReport);
upload.cleanup(id, responseToReport, optXhr);
},
function(response, optXhr) {
log("Simple upload request failed for " + id);
var responseToReport = upload.normalizeResponse(response, false);
if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
upload.cleanup(id, responseToReport, optXhr);
}
}
);
}
},
upload = {
cancel: function(id) {
log("Cancelling " + id);
options.paramsStore.remove(id);
connectionManager.free(id);
},
cleanup: function(id, response, optXhr) {
var name = options.getName(id);
options.onComplete(id, name, response, optXhr);
if (handler._getFileState(id)) {
handler._clearXhrs && handler._clearXhrs(id);
}
connectionManager.free(id);
},
// Returns a qq.BlobProxy, or an actual File/Blob if no proxy is involved, or undefined
// if none of these are available for the ID
getProxyOrBlob: function(id) {
return (handler.getProxy && handler.getProxy(id)) ||
(handler.getFile && handler.getFile(id));
},
initHandler: function() {
var handlerType = namespace ? qq[namespace] : qq.traditional,
handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
handler = new handlerType[handlerModuleSubtype + "UploadHandler"](
options,
{
getDataByUuid: options.getDataByUuid,
getName: options.getName,
getSize: options.getSize,
getUuid: options.getUuid,
log: log,
onCancel: options.onCancel,
onProgress: options.onProgress,
onUuidChanged: options.onUuidChanged
}
);
if (handler._removeExpiredChunkingRecords) {
handler._removeExpiredChunkingRecords();
}
},
isDeferredEligibleForUpload: function(id) {
return options.isQueued(id);
},
// For Blobs that are part of a group of generated images, along with a reference image,
// this will ensure the blobs in the group are uploaded in the order they were triggered,
// even if some async processing must be completed on one or more Blobs first.
maybeDefer: function(id, blob) {
// If we don't have a file/blob yet & no file/blob exists for this item, request it,
// and then submit the upload to the specific handler once the blob is available.
// ASSUMPTION: This condition will only ever be true if XHR uploading is supported.
if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
// Blob creation may take some time, so the caller may want to update the
// UI to indicate that an operation is in progress, even before the actual
// upload begins and an onUpload callback is invoked.
options.onUploadPrep(id);
log("Attempting to generate a blob on-demand for " + id);
blob.create().then(function(generatedBlob) {
log("Generated an on-demand blob for " + id);
// Update record associated with this file by providing the generated Blob
handler.updateBlob(id, generatedBlob);
// Propagate the size for this generated Blob
options.setSize(id, generatedBlob.size);
// Order handler to recalculate chunking possibility, if applicable
handler.reevaluateChunking(id);
upload.maybeSendDeferredFiles(id);
},
// Blob could not be generated. Fail the upload & attempt to prevent retries. Also bubble error message.
function(errorMessage) {
var errorResponse = {};
if (errorMessage) {
errorResponse.error = errorMessage;
}
log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
upload.maybeSendDeferredFiles(id);
connectionManager.free(id);
});
}
else {
return upload.maybeSendDeferredFiles(id);
}
return false;
},
// Upload any grouped blobs, in the proper order, that are ready to be uploaded
maybeSendDeferredFiles: function(id) {
var idsInGroup = options.getIdsInProxyGroup(id),
uploadedThisId = false;
if (idsInGroup && idsInGroup.length) {
log("Maybe ready to upload proxy group file " + id);
qq.each(idsInGroup, function(idx, idInGroup) {
if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
uploadedThisId = idInGroup === id;
upload.now(idInGroup);
}
else if (upload.isDeferredEligibleForUpload(idInGroup)) {
return false;
}
});
}
else {
uploadedThisId = true;
upload.now(id);
}
return uploadedThisId;
},
maybeNewUuid: function(id, response) {
if (response.newUuid !== undefined) {
options.onUuidChanged(id, response.newUuid);
}
},
// The response coming from handler implementations may be in various formats.
// Instead of hoping a promise nested 5 levels deep will always return an object
// as its first param, let's just normalize the response here.
normalizeResponse: function(originalResponse, successful) {
var response = originalResponse;
// The passed "response" param may not be a response at all.
// It could be a string, detailing the error, for example.
if (!qq.isObject(originalResponse)) {
response = {};
if (qq.isString(originalResponse) && !successful) {
response.error = originalResponse;
}
}
response.success = successful;
return response;
},
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
options.onUpload(id, name);
if (chunkingPossible && handler._shouldChunkThisFile(id)) {
chunked.sendNext(id);
}
else {
simple.send(id, name);
}
},
start: function(id) {
var blobToUpload = upload.getProxyOrBlob(id);
if (blobToUpload) {
return upload.maybeDefer(id, blobToUpload);
}
else {
upload.now(id);
return true;
}
}
};
qq.extend(this, {
/**
* Adds file or file input to the queue
**/
add: function(id, file) {
handler.add.apply(this, arguments);
},
/**
* Sends the file identified by id
*/
upload: function(id) {
if (connectionManager.open(id)) {
return upload.start(id);
}
return false;
},
retry: function(id) {
// On retry, if concurrent chunking has been enabled, we may have aborted all other in-progress chunks
// for a file when encountering a failed chunk upload. We then signaled the controller to ignore
// all failures associated with these aborts. We are now retrying, so we don't want to ignore
// any more failures at this point.
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = false;
}
// If we are attempting to retry a file that is already consuming a connection, this is likely an auto-retry.
// Just go ahead and ask the handler to upload again.
if (connectionManager.isUsingConnection(id)) {
return upload.start(id);
}
// If we are attempting to retry a file that is not currently consuming a connection,
// this is likely a manual retry attempt. We will need to ensure a connection is available
// before the retry commences.
else {
return controller.upload(id);
}
},
/**
* Cancels file upload by id
*/
cancel: function(id) {
var cancelRetVal = handler.cancel(id);
if (qq.isGenericPromise(cancelRetVal)) {
cancelRetVal.then(function() {
upload.cancel(id);
});
}
else if (cancelRetVal !== false) {
upload.cancel(id);
}
},
/**
* Cancels all queued or in-progress uploads
*/
cancelAll: function() {
var waitingOrConnected = connectionManager.getWaitingOrConnected(),
i;
// ensure files are cancelled in reverse order which they were added
// to avoid a flash of time where a queued file begins to upload before it is canceled
if (waitingOrConnected.length) {
for (i = waitingOrConnected.length - 1; i >= 0; i--) {
controller.cancel(waitingOrConnected[i]);
}
}
connectionManager.reset();
},
// Returns a File, Blob, or the Blob/File for the reference/parent file if the targeted blob is a proxy.
// Undefined if no file record is available.
getFile: function(id) {
if (handler.getProxy && handler.getProxy(id)) {
return handler.getProxy(id).referenceBlob;
}
return handler.getFile && handler.getFile(id);
},
// Returns true if the Blob associated with the ID is related to a proxy s
isProxied: function(id) {
return !!(handler.getProxy && handler.getProxy(id));
},
getInput: function(id) {
if (handler.getInput) {
return handler.getInput(id);
}
},
reset: function() {
log("Resetting upload handler");
controller.cancelAll();
connectionManager.reset();
handler.reset();
},
expunge: function(id) {
if (controller.isValid(id)) {
return handler.expunge(id);
}
},
/**
* Determine if the file exists.
*/
isValid: function(id) {
return handler.isValid(id);
},
getResumableFilesData: function() {
if (handler.getResumableFilesData) {
return handler.getResumableFilesData();
}
return [];
},
/**
* This may or may not be implemented, depending on the handler. For handlers where a third-party ID is
* available (such as the "key" for Amazon S3), this will return that value. Otherwise, the return value
* will be undefined.
*
* @param id Internal file ID
* @returns {*} Some identifier used by a 3rd-party service involved in the upload process
*/
getThirdPartyFileId: function(id) {
if (controller.isValid(id)) {
return handler.getThirdPartyFileId(id);
}
},
/**
* Attempts to pause the associated upload if the specific handler supports this and the file is "valid".
* @param id ID of the upload/file to pause
* @returns {boolean} true if the upload was paused
*/
pause: function(id) {
if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
connectionManager.free(id);
handler.moveInProgressToRemaining(id);
return true;
}
return false;
},
// True if the file is eligible for pause/resume.
isResumable: function(id) {
return !!handler.isResumable && handler.isResumable(id);
}
});
qq.extend(options, o);
log = options.log;
chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
preventRetryResponse = (function() {
var response = {};
response[options.preventRetryParam] = true;
return response;
}());
upload.initHandler();
};
/* globals qq */
/**
* Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden
* in some cases by specific form upload handlers.
*
* @constructor
*/
qq.FormUploadHandler = function(spec) {
"use strict";
var options = spec.options,
handler = this,
proxy = spec.proxy,
formHandlerInstanceId = qq.getUniqueId(),
onloadCallbacks = {},
detachLoadEvents = {},
postMessageCallbackTimers = {},
isCors = options.isCors,
inputName = options.inputName,
getUuid = proxy.getUuid,
log = proxy.log,
corsMessageReceiver = new qq.WindowReceiveMessage({log: log});
/**
* Remove any trace of the file from the handler.
*
* @param id ID of the associated file
*/
function expungeFile(id) {
delete detachLoadEvents[id];
// If we are dealing with CORS, we might still be waiting for a response from a loaded iframe.
// In that case, terminate the timer waiting for a message from the loaded iframe
// and stop listening for any more messages coming from this iframe.
if (isCors) {
clearTimeout(postMessageCallbackTimers[id]);
delete postMessageCallbackTimers[id];
corsMessageReceiver.stopReceivingMessages(id);
}
var iframe = document.getElementById(handler._getIframeName(id));
if (iframe) {
// To cancel request set src to something else. We use src="javascript:false;"
// because it doesn't trigger ie6 prompt on https
/* jshint scripturl:true */
iframe.setAttribute("src", "javascript:false;");
qq(iframe).remove();
}
}
/**
* @param iframeName `document`-unique Name of the associated iframe
* @returns {*} ID of the associated file
*/
function getFileIdForIframeName(iframeName) {
return iframeName.split("_")[0];
}
/**
* Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe
* to the current `document`. Note that the iframe is hidden from view.
*
* @param name Name of the iframe.
* @returns {HTMLIFrameElement} The created iframe
*/
function initIframeForUpload(name) {
var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />");
iframe.setAttribute("id", name);
iframe.style.display = "none";
document.body.appendChild(iframe);
return iframe;
}
/**
* If we are in CORS mode, we must listen for messages (containing the server response) from the associated
* iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions.
*
* @param iframe Listen for messages on this iframe.
* @param callback Invoke this callback with the message from the iframe.
*/
function registerPostMessageCallback(iframe, callback) {
var iframeName = iframe.id,
fileId = getFileIdForIframeName(iframeName),
uuid = getUuid(fileId);
onloadCallbacks[uuid] = callback;
// When the iframe has loaded (after the server responds to an upload request)
// declare the attempt a failure if we don't receive a valid message shortly after the response comes in.
detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
if (handler.getInput(fileId)) {
log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
postMessageCallbackTimers[iframeName] = setTimeout(function() {
var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
log(errorMessage, "error");
callback({
error: errorMessage
});
}, 1000);
}
});
// Listen for messages coming from this iframe. When a message has been received, cancel the timer
// that declares the upload a failure if a message is not received within a reasonable amount of time.
corsMessageReceiver.receiveMessage(iframeName, function(message) {
log("Received the following window message: '" + message + "'");
var fileId = getFileIdForIframeName(iframeName),
response = handler._parseJsonResponse(message),
uuid = response.uuid,
onloadCallback;
if (uuid && onloadCallbacks[uuid]) {
log("Handling response for iframe name " + iframeName);
clearTimeout(postMessageCallbackTimers[iframeName]);
delete postMessageCallbackTimers[iframeName];
handler._detachLoadEvent(iframeName);
onloadCallback = onloadCallbacks[uuid];
delete onloadCallbacks[uuid];
corsMessageReceiver.stopReceivingMessages(iframeName);
onloadCallback(response);
}
else if (!uuid) {
log("'" + message + "' does not contain a UUID - ignoring.");
}
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
/**
* Adds File or Blob to the queue
**/
add: function(id, fileInput) {
super_.add(id, {input: fileInput});
fileInput.setAttribute("name", inputName);
// remove file input from DOM
if (fileInput.parentNode) {
qq(fileInput).remove();
}
},
expunge: function(id) {
expungeFile(id);
super_.expunge(id);
},
isValid: function(id) {
return super_.isValid(id) &&
handler._getFileState(id).input !== undefined;
}
};
});
qq.extend(this, {
getInput: function(id) {
return handler._getFileState(id).input;
},
/**
* This function either delegates to a more specific message handler if CORS is involved,
* or simply registers a callback when the iframe has been loaded that invokes the passed callback
* after determining if the content of the iframe is accessible.
*
* @param iframe Associated iframe
* @param callback Callback to invoke after we have determined if the iframe content is accessible.
*/
_attachLoadEvent: function(iframe, callback) {
/*jslint eqeq: true*/
var responseDescriptor;
if (isCors) {
registerPostMessageCallback(iframe, callback);
}
else {
detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
log("Received response for " + iframe.id);
// when we remove iframe from dom
// the request stops, but in IE load
// event fires
if (!iframe.parentNode) {
return;
}
try {
// fixing Opera 10.53
if (iframe.contentDocument &&
iframe.contentDocument.body &&
iframe.contentDocument.body.innerHTML == "false") {
// In Opera event is fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
// when we upload file with iframe
return;
}
}
catch (error) {
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
responseDescriptor = {success: false};
}
callback(responseDescriptor);
});
}
},
/**
* Creates an iframe with a specific document-unique name.
*
* @param id ID of the associated file
* @returns {HTMLIFrameElement}
*/
_createIframe: function(id) {
var iframeName = handler._getIframeName(id);
return initIframeForUpload(iframeName);
},
/**
* Called when we are no longer interested in being notified when an iframe has loaded.
*
* @param id Associated file ID
*/
_detachLoadEvent: function(id) {
if (detachLoadEvents[id] !== undefined) {
detachLoadEvents[id]();
delete detachLoadEvents[id];
}
},
/**
* @param fileId ID of the associated file
* @returns {string} The `document`-unique name of the iframe
*/
_getIframeName: function(fileId) {
return fileId + "_" + formHandlerInstanceId;
},
/**
* Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted.
* The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note
* that the form is hidden from view.
*
* @param spec An object containing various properties to be used when constructing the form. Required properties are
* currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`.
* @returns {HTMLFormElement} The created form
*/
_initFormForUpload: function(spec) {
var method = spec.method,
endpoint = spec.endpoint,
params = spec.params,
paramsInBody = spec.paramsInBody,
targetName = spec.targetName,
form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"),
url = endpoint;
if (paramsInBody) {
qq.obj2Inputs(params, form);
}
else {
url = qq.obj2url(params, endpoint);
}
form.setAttribute("action", url);
form.setAttribute("target", targetName);
form.style.display = "none";
document.body.appendChild(form);
return form;
},
/**
* @param innerHtmlOrMessage JSON message
* @returns {*} The parsed response, or an empty object if the response could not be parsed
*/
_parseJsonResponse: function(innerHtmlOrMessage) {
var response = {};
try {
response = qq.parseJson(innerHtmlOrMessage);
}
catch (error) {
log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
}
return response;
}
});
};
/* globals qq */
/**
* Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific
* XHR upload handlers.
*
* @constructor
*/
qq.XhrUploadHandler = function(spec) {
"use strict";
var handler = this,
namespace = spec.options.namespace,
proxy = spec.proxy,
chunking = spec.options.chunking,
resume = spec.options.resume,
chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking,
resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume,
getName = proxy.getName,
getSize = proxy.getSize,
getUuid = proxy.getUuid,
getEndpoint = proxy.getEndpoint,
getDataByUuid = proxy.getDataByUuid,
onUuidChanged = proxy.onUuidChanged,
onProgress = proxy.onProgress,
log = proxy.log;
function abort(id) {
qq.each(handler._getXhrs(id), function(xhrId, xhr) {
var ajaxRequester = handler._getAjaxRequester(id, xhrId);
xhr.onreadystatechange = null;
xhr.upload.onprogress = null;
xhr.abort();
ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
/**
* Adds File or Blob to the queue
**/
add: function(id, blobOrProxy) {
if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
super_.add(id, {file: blobOrProxy});
}
else if (blobOrProxy instanceof qq.BlobProxy) {
super_.add(id, {proxy: blobOrProxy});
}
else {
throw new Error("Passed obj is not a File, Blob, or proxy");
}
handler._initTempState(id);
resumeEnabled && handler._maybePrepareForResume(id);
},
expunge: function(id) {
abort(id);
handler._maybeDeletePersistedChunkData(id);
handler._clearXhrs(id);
super_.expunge(id);
}
};
});
qq.extend(this, {
// Clear the cached chunk `Blob` after we are done with it, just in case the `Blob` bytes are stored in memory.
clearCachedChunk: function(id, chunkIdx) {
delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
},
clearXhr: function(id, chunkIdx) {
var tempState = handler._getFileState(id).temp;
if (tempState.xhrs) {
delete tempState.xhrs[chunkIdx];
}
if (tempState.ajaxRequesters) {
delete tempState.ajaxRequesters[chunkIdx];
}
},
// Called when all chunks have been successfully uploaded. Expected promissory return type.
// This defines the default behavior if nothing further is required when all chunks have been uploaded.
finalizeChunks: function(id, responseParser) {
var lastChunkIdx = handler._getTotalChunks(id) - 1,
xhr = handler._getXhr(id, lastChunkIdx);
if (responseParser) {
return new qq.Promise().success(responseParser(xhr), xhr);
}
return new qq.Promise().success({}, xhr);
},
getFile: function(id) {
return handler.isValid(id) && handler._getFileState(id).file;
},
getProxy: function(id) {
return handler.isValid(id) && handler._getFileState(id).proxy;
},
/**
* @returns {Array} Array of objects containing properties useful to integrators
* when it is important to determine which files are potentially resumable.
*/
getResumableFilesData: function() {
var resumableFilesData = [];
handler._iterateResumeRecords(function(key, uploadData) {
handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
var data = {
name: uploadData.name,
remaining: uploadData.chunking.remaining,
size: uploadData.size,
uuid: uploadData.uuid
};
if (uploadData.key) {
data.key = uploadData.key;
}
resumableFilesData.push(data);
});
return resumableFilesData;
},
isResumable: function(id) {
return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
},
moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress,
remaining = optRemaining || handler._getFileState(id).chunking.remaining;
if (inProgress) {
inProgress.reverse();
qq.each(inProgress, function(idx, chunkIdx) {
remaining.unshift(chunkIdx);
});
inProgress.length = 0;
}
},
pause: function(id) {
if (handler.isValid(id)) {
log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
handler._getFileState(id).paused = true;
abort(id);
return true;
}
},
reevaluateChunking: function(id) {
if (chunking && handler.isValid(id)) {
var state = handler._getFileState(id),
totalChunks,
i;
delete state.chunking;
state.chunking = {};
totalChunks = handler._getTotalChunks(id);
if (totalChunks > 1 || chunking.mandatory) {
state.chunking.enabled = true;
state.chunking.parts = totalChunks;
state.chunking.remaining = [];
for (i = 0; i < totalChunks; i++) {
state.chunking.remaining.push(i);
}
handler._initTempState(id);
}
else {
state.chunking.enabled = false;
}
}
},
updateBlob: function(id, newBlob) {
if (handler.isValid(id)) {
handler._getFileState(id).file = newBlob;
}
},
_clearXhrs: function(id) {
var tempState = handler._getFileState(id).temp;
qq.each(tempState.ajaxRequesters, function(chunkId) {
delete tempState.ajaxRequesters[chunkId];
});
qq.each(tempState.xhrs, function(chunkId) {
delete tempState.xhrs[chunkId];
});
},
/**
* Creates an XHR instance for this file and stores it in the fileState.
*
* @param id File ID
* @param optChunkIdx The chunk index associated with this XHR, if applicable
* @returns {XMLHttpRequest}
*/
_createXhr: function(id, optChunkIdx) {
return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
},
_getAjaxRequester: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
},
_getChunkData: function(id, chunkIndex) {
var chunkSize = chunking.partSize,
fileSize = getSize(id),
fileOrBlob = handler.getFile(id),
startBytes = chunkSize * chunkIndex,
endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize,
totalChunks = handler._getTotalChunks(id),
cachedChunks = this._getFileState(id).temp.cachedChunks,
// To work around a Webkit GC bug, we must keep each chunk `Blob` in scope until we are done with it.
// See https://github.com/Widen/fine-uploader/issues/937#issuecomment-41418760
blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
cachedChunks[chunkIndex] = blob;
return {
part: chunkIndex,
start: startBytes,
end: endBytes,
count: totalChunks,
blob: blob,
size: endBytes - startBytes
};
},
_getChunkDataForCallback: function(chunkData) {
return {
partIndex: chunkData.part,
startByte: chunkData.start + 1,
endByte: chunkData.end,
totalParts: chunkData.count
};
},
/**
* @param id File ID
* @returns {string} Identifier for this item that may appear in the browser's local storage
*/
_getLocalStorageId: function(id) {
var formatVersion = "5.0",
name = getName(id),
size = getSize(id),
chunkSize = chunking.partSize,
endpoint = getEndpoint(id);
return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
},
_getMimeType: function(id) {
return handler.getFile(id).type;
},
_getPersistableData: function(id) {
return handler._getFileState(id).chunking;
},
/**
* @param id ID of the associated file
* @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA
*/
_getTotalChunks: function(id) {
if (chunking) {
var fileSize = getSize(id),
chunkSize = chunking.partSize;
return Math.ceil(fileSize / chunkSize);
}
},
_getXhr: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.xhrs[chunkIdx];
},
_getXhrs: function(id) {
return handler._getFileState(id).temp.xhrs;
},
// Iterates through all XHR handler-created resume records (in local storage),
// invoking the passed callback and passing in the key and value of each local storage record.
_iterateResumeRecords: function(callback) {
if (resumeEnabled) {
qq.each(localStorage, function(key, item) {
if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
var uploadData = JSON.parse(item);
callback(key, uploadData);
}
});
}
},
_initTempState: function(id) {
handler._getFileState(id).temp = {
ajaxRequesters: {},
chunkProgress: {},
xhrs: {},
cachedChunks: {}
};
},
_markNotResumable: function(id) {
handler._getFileState(id).notResumable = true;
},
// Removes a chunked upload record from local storage, if possible.
// Returns true if the item was removed, false otherwise.
_maybeDeletePersistedChunkData: function(id) {
var localStorageId;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
if (localStorageId && localStorage.getItem(localStorageId)) {
localStorage.removeItem(localStorageId);
return true;
}
}
return false;
},
// If this is a resumable upload, grab the relevant data from storage and items in memory that track this upload
// so we can pick up from where we left off.
_maybePrepareForResume: function(id) {
var state = handler._getFileState(id),
localStorageId, persistedData;
// Resume is enabled and possible and this is the first time we've tried to upload this file in this session,
// so prepare for a resume attempt.
if (resumeEnabled && state.key === undefined) {
localStorageId = handler._getLocalStorageId(id);
persistedData = localStorage.getItem(localStorageId);
// If we found this item in local storage, maybe we should resume it.
if (persistedData) {
persistedData = JSON.parse(persistedData);
// If we found a resume record but we have already handled this file in this session,
// don't try to resume it & ensure we don't persist future check data
if (getDataByUuid(persistedData.uuid)) {
handler._markNotResumable(id);
}
else {
log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
onUuidChanged(id, persistedData.uuid);
state.key = persistedData.key;
state.chunking = persistedData.chunking;
state.loaded = persistedData.loaded;
state.attemptingResume = true;
handler.moveInProgressToRemaining(id);
}
}
}
},
// Persist any data needed to resume this upload in a new session.
_maybePersistChunkedState: function(id) {
var state = handler._getFileState(id),
localStorageId, persistedData;
// If local storage isn't supported by the browser, or if resume isn't enabled or possible, give up
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
persistedData = {
name: getName(id),
size: getSize(id),
uuid: getUuid(id),
key: state.key,
chunking: state.chunking,
loaded: state.loaded,
lastUpdated: Date.now()
};
try {
localStorage.setItem(localStorageId, JSON.stringify(persistedData));
}
catch (error) {
log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn");
}
}
},
_registerProgressHandler: function(id, chunkIdx, chunkSize) {
var xhr = handler._getXhr(id, chunkIdx),
name = getName(id),
progressCalculator = {
simple: function(loaded, total) {
var fileSize = getSize(id);
if (loaded === total) {
onProgress(id, name, fileSize, fileSize);
}
else {
onProgress(id, name, (loaded >= fileSize ? fileSize - 1 : loaded), fileSize);
}
},
chunked: function(loaded, total) {
var chunkProgress = handler._getFileState(id).temp.chunkProgress,
totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded,
loadedForRequest = loaded,
totalForRequest = total,
totalFileSize = getSize(id),
estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize),
totalLoadedForFile = totalSuccessfullyLoadedForFile;
chunkProgress[chunkIdx] = estActualChunkLoaded;
qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
totalLoadedForFile += chunkLoaded;
});
onProgress(id, name, totalLoadedForFile, totalFileSize);
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
/* jshint eqnull: true */
var type = chunkSize == null ? "simple" : "chunked";
progressCalculator[type](e.loaded, e.total);
}
};
},
/**
* Registers an XHR transport instance created elsewhere.
*
* @param id ID of the associated file
* @param optChunkIdx The chunk index associated with this XHR, if applicable
* @param xhr XMLHttpRequest object instance
* @param optAjaxRequester `qq.AjaxRequester` associated with this request, if applicable.
* @returns {XMLHttpRequest}
*/
_registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
var xhrsId = optChunkIdx == null ? -1 : optChunkIdx,
tempState = handler._getFileState(id).temp;
tempState.xhrs = tempState.xhrs || {};
tempState.ajaxRequesters = tempState.ajaxRequesters || {};
tempState.xhrs[xhrsId] = xhr;
if (optAjaxRequester) {
tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
}
return xhr;
},
// Deletes any local storage records that are "expired".
_removeExpiredChunkingRecords: function() {
var expirationDays = resume.recordsExpireIn;
handler._iterateResumeRecords(function(key, uploadData) {
var expirationDate = new Date(uploadData.lastUpdated);
// transform updated date into expiration date
expirationDate.setDate(expirationDate.getDate() + expirationDays);
if (expirationDate.getTime() <= Date.now()) {
log("Removing expired resume record with key " + key);
localStorage.removeItem(key);
}
});
},
/**
* Determine if the associated file should be chunked.
*
* @param id ID of the associated file
* @returns {*} true if chunking is enabled, possible, and the file can be split into more than 1 part
*/
_shouldChunkThisFile: function(id) {
var state = handler._getFileState(id);
if (!state.chunking) {
handler.reevaluateChunking(id);
}
return state.chunking.enabled;
}
});
};
/*globals qq */
/*jshint -W117 */
qq.WindowReceiveMessage = function(o) {
"use strict";
var options = {
log: function(message, level) {}
},
callbackWrapperDetachers = {};
qq.extend(options, o);
qq.extend(this, {
receiveMessage: function(id, callback) {
var onMessageCallbackWrapper = function(event) {
callback(event.data);
};
if (window.postMessage) {
callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
}
else {
log("iframe message passing not supported in this browser!", "error");
}
},
stopReceivingMessages: function(id) {
if (window.postMessage) {
var detacher = callbackWrapperDetachers[id];
if (detacher) {
detacher();
}
}
}
});
};
/*globals qq */
/**
* Defines the public API for FineUploader mode.
*/
(function() {
"use strict";
qq.uiPublicApi = {
clearStoredFiles: function() {
this._parent.prototype.clearStoredFiles.apply(this, arguments);
this._templating.clearFiles();
},
addExtraDropzone: function(element) {
this._dnd && this._dnd.setupExtraDropzone(element);
},
removeExtraDropzone: function(element) {
if (this._dnd) {
return this._dnd.removeDropzone(element);
}
},
getItemByFileId: function(id) {
if (!this._templating.isHiddenForever(id)) {
return this._templating.getFileContainer(id);
}
},
reset: function() {
this._parent.prototype.reset.apply(this, arguments);
this._templating.reset();
if (!this._options.button && this._templating.getButton()) {
this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId();
}
if (this._dnd) {
this._dnd.dispose();
this._dnd = this._setupDragAndDrop();
}
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
this._setupClickAndEditEventHandlers();
},
setName: function(id, newName) {
var formattedFilename = this._options.formatFileName(newName);
this._parent.prototype.setName.apply(this, arguments);
this._templating.updateFilename(id, formattedFilename);
},
pauseUpload: function(id) {
var paused = this._parent.prototype.pauseUpload.apply(this, arguments);
paused && this._templating.uploadPaused(id);
return paused;
},
continueUpload: function(id) {
var continued = this._parent.prototype.continueUpload.apply(this, arguments);
continued && this._templating.uploadContinued(id);
return continued;
},
getId: function(fileContainerOrChildEl) {
return this._templating.getFileId(fileContainerOrChildEl);
},
getDropTarget: function(fileId) {
var file = this.getFile(fileId);
return file.qqDropTarget;
}
};
/**
* Defines the private (internal) API for FineUploader mode.
*/
qq.uiPrivateApi = {
_getButton: function(buttonId) {
var button = this._parent.prototype._getButton.apply(this, arguments);
if (!button) {
if (buttonId === this._defaultButtonId) {
button = this._templating.getButton();
}
}
return button;
},
_removeFileItem: function(fileId) {
this._templating.removeFile(fileId);
},
_setupClickAndEditEventHandlers: function() {
this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent();
// A better approach would be to check specifically for focusin event support by querying the DOM API,
// but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing.
this._focusinEventSupported = !qq.firefox();
if (this._isEditFilenameEnabled())
{
this._filenameClickHandler = this._bindFilenameClickEvent();
this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent();
this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent();
}
},
_setupDragAndDrop: function() {
var self = this,
dropZoneElements = this._options.dragAndDrop.extraDropzones,
templating = this._templating,
defaultDropZone = templating.getDropZone();
defaultDropZone && dropZoneElements.push(defaultDropZone);
return new qq.DragAndDrop({
dropZoneElements: dropZoneElements,
allowMultipleItems: this._options.multiple,
classes: {
dropActive: this._options.classes.dropActive
},
callbacks: {
processingDroppedFiles: function() {
templating.showDropProcessing();
},
processingDroppedFilesComplete: function(files, targetEl) {
templating.hideDropProcessing();
qq.each(files, function(idx, file) {
file.qqDropTarget = targetEl;
});
if (files.length) {
self.addFiles(files, null, null);
}
},
dropError: function(code, errorData) {
self._itemError(code, errorData);
},
dropLog: function(message, level) {
self.log(message, level);
}
}
});
},
_bindFileButtonsClickEvent: function() {
var self = this;
return new qq.FileButtonsClickHandler({
templating: this._templating,
log: function(message, lvl) {
self.log(message, lvl);
},
onDeleteFile: function(fileId) {
self.deleteFile(fileId);
},
onCancel: function(fileId) {
self.cancel(fileId);
},
onRetry: function(fileId) {
qq(self._templating.getFileContainer(fileId)).removeClass(self._classes.retryable);
self._templating.hideRetry(fileId);
self.retry(fileId);
},
onPause: function(fileId) {
self.pauseUpload(fileId);
},
onContinue: function(fileId) {
self.continueUpload(fileId);
},
onGetName: function(fileId) {
return self.getName(fileId);
}
});
},
_isEditFilenameEnabled: function() {
/*jshint -W014 */
return this._templating.isEditFilenamePossible()
&& !this._options.autoUpload
&& qq.FilenameClickHandler
&& qq.FilenameInputFocusHandler
&& qq.FilenameInputFocusHandler;
},
_filenameEditHandler: function() {
var self = this,
templating = this._templating;
return {
templating: templating,
log: function(message, lvl) {
self.log(message, lvl);
},
onGetUploadStatus: function(fileId) {
return self.getUploads({id: fileId}).status;
},
onGetName: function(fileId) {
return self.getName(fileId);
},
onSetName: function(id, newName) {
self.setName(id, newName);
},
onEditingStatusChange: function(id, isEditing) {
var qqInput = qq(templating.getEditInput(id)),
qqFileContainer = qq(templating.getFileContainer(id));
if (isEditing) {
qqInput.addClass("qq-editing");
templating.hideFilename(id);
templating.hideEditIcon(id);
}
else {
qqInput.removeClass("qq-editing");
templating.showFilename(id);
templating.showEditIcon(id);
}
// Force IE8 and older to repaint
qqFileContainer.addClass("qq-temp").removeClass("qq-temp");
}
};
},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
this._parent.prototype._onUploadStatusChange.apply(this, arguments);
if (this._isEditFilenameEnabled()) {
// Status for a file exists before it has been added to the DOM, so we must be careful here.
if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) {
this._templating.markFilenameEditable(id);
this._templating.hideEditIcon(id);
}
}
if (newStatus === qq.status.UPLOAD_RETRYING) {
this._templating.setStatusText(id);
qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying);
}
else if (newStatus === qq.status.UPLOAD_FAILED) {
this._templating.hidePause(id);
}
},
_bindFilenameInputFocusInEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameInputFocusInHandler(spec);
},
_bindFilenameInputFocusEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameInputFocusHandler(spec);
},
_bindFilenameClickEvent: function() {
var spec = qq.extend({}, this._filenameEditHandler());
return new qq.FilenameClickHandler(spec);
},
_storeForLater: function(id) {
this._parent.prototype._storeForLater.apply(this, arguments);
this._templating.hideSpinner(id);
},
_onAllComplete: function(successful, failed) {
this._parent.prototype._onAllComplete.apply(this, arguments);
this._templating.resetTotalProgress();
},
_onSubmit: function(id, name) {
var file = this.getFile(id);
if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) {
this._paramsStore.addReadOnly(id, {
qqpath: file.qqPath
});
}
this._parent.prototype._onSubmit.apply(this, arguments);
this._addToList(id, name);
},
// The file item has been added to the DOM.
_onSubmitted: function(id) {
// If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon
if (this._isEditFilenameEnabled()) {
this._templating.markFilenameEditable(id);
this._templating.showEditIcon(id);
// If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input
if (!this._focusinEventSupported) {
this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id));
}
}
},
// Update the progress bar & percentage as the file is uploaded
_onProgress: function(id, name, loaded, total) {
this._parent.prototype._onProgress.apply(this, arguments);
this._templating.updateProgress(id, loaded, total);
if (Math.round(loaded / total * 100) === 100) {
this._templating.hideCancel(id);
this._templating.hidePause(id);
this._templating.hideProgress(id);
this._templating.setStatusText(id, this._options.text.waitingForResponse);
// If ~last byte was sent, display total file size
this._displayFileSize(id);
}
else {
// If still uploading, display percentage - total size is actually the total request(s) size
this._displayFileSize(id, loaded, total);
}
},
_onTotalProgress: function(loaded, total) {
this._parent.prototype._onTotalProgress.apply(this, arguments);
this._templating.updateTotalProgress(loaded, total);
},
_onComplete: function(id, name, result, xhr) {
var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments),
templating = this._templating,
fileContainer = templating.getFileContainer(id),
self = this;
function completeUpload(result) {
// If this file is not represented in the templating module, perhaps it was hidden intentionally.
// If so, don't perform any UI-related tasks related to this file.
if (!fileContainer) {
return;
}
templating.setStatusText(id);
qq(fileContainer).removeClass(self._classes.retrying);
templating.hideProgress(id);
if (self.getUploads({id: id}).status !== qq.status.UPLOAD_FAILED) {
templating.hideCancel(id);
}
templating.hideSpinner(id);
if (result.success) {
self._markFileAsSuccessful(id);
}
else {
qq(fileContainer).addClass(self._classes.fail);
templating.showCancel(id);
if (templating.isRetryPossible() && !self._preventRetries[id]) {
qq(fileContainer).addClass(self._classes.retryable);
templating.showRetry(id);
}
self._controlFailureTextDisplay(id, result);
}
}
// The parent may need to perform some async operation before we can accurately determine the status of the upload.
if (parentRetVal instanceof qq.Promise) {
parentRetVal.done(function(newResult) {
completeUpload(newResult);
});
}
else {
completeUpload(result);
}
return parentRetVal;
},
_markFileAsSuccessful: function(id) {
var templating = this._templating;
if (this._isDeletePossible()) {
templating.showDeleteButton(id);
}
qq(templating.getFileContainer(id)).addClass(this._classes.success);
this._maybeUpdateThumbnail(id);
},
_onUploadPrep: function(id) {
this._parent.prototype._onUploadPrep.apply(this, arguments);
this._templating.showSpinner(id);
},
_onUpload: function(id, name) {
var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments);
this._templating.showSpinner(id);
return parentRetVal;
},
_onUploadChunk: function(id, chunkData) {
this._parent.prototype._onUploadChunk.apply(this, arguments);
// Only display the pause button if we have finished uploading at least one chunk
// & this file can be resumed
if (chunkData.partIndex > 0 && this._handler.isResumable(id)) {
this._templating.allowPause(id);
}
},
_onCancel: function(id, name) {
this._parent.prototype._onCancel.apply(this, arguments);
this._removeFileItem(id);
if (this._getNotFinished() === 0) {
this._templating.resetTotalProgress();
}
},
_onBeforeAutoRetry: function(id) {
var retryNumForDisplay, maxAuto, retryNote;
this._parent.prototype._onBeforeAutoRetry.apply(this, arguments);
this._showCancelLink(id);
if (this._options.retry.showAutoRetryNote) {
retryNumForDisplay = this._autoRetries[id];
maxAuto = this._options.retry.maxAutoAttempts;
retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay);
retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto);
this._templating.setStatusText(id, retryNote);
qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying);
}
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) {
this._templating.resetProgress(id);
qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail);
this._templating.setStatusText(id);
this._templating.showSpinner(id);
this._showCancelLink(id);
return true;
}
else {
qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable);
this._templating.showRetry(id);
return false;
}
},
_onSubmitDelete: function(id) {
var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this);
this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback);
},
_onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) {
if (this._options.deleteFile.forceConfirm) {
this._showDeleteConfirm.apply(this, arguments);
}
else {
this._sendDeleteRequest.apply(this, arguments);
}
},
_onDeleteComplete: function(id, xhr, isError) {
this._parent.prototype._onDeleteComplete.apply(this, arguments);
this._templating.hideSpinner(id);
if (isError) {
this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText);
this._templating.showDeleteButton(id);
}
else {
this._removeFileItem(id);
}
},
_sendDeleteRequest: function(id, uuid, additionalMandatedParams) {
this._templating.hideDeleteButton(id);
this._templating.showSpinner(id);
this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText);
this._deleteHandler.sendDelete.apply(this, arguments);
},
_showDeleteConfirm: function(id, uuid, mandatedParams) {
/*jshint -W004 */
var fileName = this.getName(id),
confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName),
uuid = this.getUuid(id),
deleteRequestArgs = arguments,
self = this,
retVal;
retVal = this._options.showConfirm(confirmMessage);
if (qq.isGenericPromise(retVal)) {
retVal.then(function() {
self._sendDeleteRequest.apply(self, deleteRequestArgs);
});
}
else if (retVal !== false) {
self._sendDeleteRequest.apply(self, deleteRequestArgs);
}
},
_addToList: function(id, name, canned) {
var prependData,
prependIndex = 0,
dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled,
record;
if (this._options.display.prependFiles) {
if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {
prependIndex = this._filesInBatchAddedToUi - 1;
}
prependData = {
index: prependIndex
};
}
if (!canned) {
if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {
this._templating.disableCancel();
}
// Cancel all existing (previous) files and clear the list if this file is not part of
// a scaled file group that has already been accepted, or if this file is not part of
// a scaled file group at all.
if (!this._options.multiple) {
record = this.getUploads({id: id});
this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId;
if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) {
this._handler.cancelAll();
this._clearList();
this._handledProxyGroup = null;
}
}
}
this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay);
if (canned) {
this._thumbnailUrls[id] && this._templating.updateThumbnail(id, this._thumbnailUrls[id], true);
}
else {
this._templating.generatePreview(id, this.getFile(id));
}
this._filesInBatchAddedToUi += 1;
if (canned ||
(this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) {
this._displayFileSize(id);
}
},
_clearList: function() {
this._templating.clearFiles();
this.clearStoredFiles();
},
_displayFileSize: function(id, loadedSize, totalSize) {
var size = this.getSize(id),
sizeForDisplay = this._formatSize(size);
if (size >= 0) {
if (loadedSize !== undefined && totalSize !== undefined) {
sizeForDisplay = this._formatProgress(loadedSize, totalSize);
}
this._templating.updateSize(id, sizeForDisplay);
}
},
_formatProgress: function(uploadedSize, totalSize) {
var message = this._options.text.formatProgress;
function r(name, replacement) { message = message.replace(name, replacement); }
r("{percent}", Math.round(uploadedSize / totalSize * 100));
r("{total_size}", this._formatSize(totalSize));
return message;
},
_controlFailureTextDisplay: function(id, response) {
var mode, responseProperty, failureReason;
mode = this._options.failedUploadTextDisplay.mode;
responseProperty = this._options.failedUploadTextDisplay.responseProperty;
if (mode === "custom") {
failureReason = response[responseProperty];
if (!failureReason) {
failureReason = this._options.text.failUpload;
}
this._templating.setStatusText(id, failureReason);
if (this._options.failedUploadTextDisplay.enableTooltip) {
this._showTooltip(id, failureReason);
}
}
else if (mode === "default") {
this._templating.setStatusText(id, this._options.text.failUpload);
}
else if (mode !== "none") {
this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn");
}
},
_showTooltip: function(id, text) {
this._templating.getFileContainer(id).title = text;
},
_showCancelLink: function(id) {
if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
this._templating.showCancel(id);
}
},
_itemError: function(code, name, item) {
var message = this._parent.prototype._itemError.apply(this, arguments);
this._options.showMessage(message);
},
_batchError: function(message) {
this._parent.prototype._batchError.apply(this, arguments);
this._options.showMessage(message);
},
_setupPastePrompt: function() {
var self = this;
this._options.callbacks.onPasteReceived = function() {
var message = self._options.paste.namePromptMessage,
defaultVal = self._options.paste.defaultName;
return self._options.showPrompt(message, defaultVal);
};
},
_fileOrBlobRejected: function(id, name) {
this._totalFilesInBatch -= 1;
this._parent.prototype._fileOrBlobRejected.apply(this, arguments);
},
_prepareItemsForUpload: function(items, params, endpoint) {
this._totalFilesInBatch = items.length;
this._filesInBatchAddedToUi = 0;
this._parent.prototype._prepareItemsForUpload.apply(this, arguments);
},
_maybeUpdateThumbnail: function(fileId) {
var thumbnailUrl = this._thumbnailUrls[fileId],
fileStatus = this.getUploads({id: fileId}).status;
if (fileStatus !== qq.status.DELETED &&
(thumbnailUrl ||
this._options.thumbnails.placeholders.waitUntilResponse ||
!qq.supportedFeatures.imagePreviews)) {
// This will replace the "waiting" placeholder with a "preview not available" placeholder
// if called with a null thumbnailUrl.
this._templating.updateThumbnail(fileId, thumbnailUrl);
}
},
_addCannedFile: function(sessionData) {
var id = this._parent.prototype._addCannedFile.apply(this, arguments);
this._addToList(id, this.getName(id), true);
this._templating.hideSpinner(id);
this._templating.hideCancel(id);
this._markFileAsSuccessful(id);
return id;
},
_setSize: function(id, newSize) {
this._parent.prototype._setSize.apply(this, arguments);
this._templating.updateSize(id, this._formatSize(newSize));
}
};
}());
/*globals qq */
/**
* This defines FineUploader mode, which is a default UI w/ drag & drop uploading.
*/
qq.FineUploader = function(o, namespace) {
"use strict";
var self = this;
// By default this should inherit instance data from FineUploaderBasic, but this can be overridden
// if the (internal) caller defines a different parent. The parent is also used by
// the private and public API functions that need to delegate to a parent function.
this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic;
this._parent.apply(this, arguments);
// Options provided by FineUploader mode
qq.extend(this._options, {
element: null,
button: null,
listElement: null,
dragAndDrop: {
extraDropzones: [],
reportDirectoryPaths: false
},
text: {
formatProgress: "{percent}% of {total_size}",
failUpload: "Upload failed",
waitingForResponse: "Processing...",
paused: "Paused"
},
template: "qq-template",
classes: {
retrying: "qq-upload-retrying",
retryable: "qq-upload-retryable",
success: "qq-upload-success",
fail: "qq-upload-fail",
editable: "qq-editable",
hide: "qq-hide",
dropActive: "qq-upload-drop-area-active"
},
failedUploadTextDisplay: {
mode: "default", //default, custom, or none
responseProperty: "error",
enableTooltip: true
},
messages: {
tooManyFilesError: "You may only drop one file",
unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind."
},
retry: {
showAutoRetryNote: true,
autoRetryNote: "Retrying {retryNum}/{maxAuto}..."
},
deleteFile: {
forceConfirm: false,
confirmMessage: "Are you sure you want to delete {filename}?",
deletingStatusText: "Deleting...",
deletingFailedText: "Delete failed"
},
display: {
fileSizeOnSubmit: false,
prependFiles: false
},
paste: {
promptForName: false,
namePromptMessage: "Please name this image"
},
thumbnails: {
maxCount: 0,
placeholders: {
waitUntilResponse: false,
notAvailablePath: null,
waitingPath: null
},
timeBetweenThumbs: 750
},
scaling: {
hideScaled: false
},
showMessage: function(message) {
if (self._templating.hasDialog("alert")) {
return self._templating.showDialog("alert", message);
}
else {
setTimeout(function() {
window.alert(message);
}, 0);
}
},
showConfirm: function(message) {
if (self._templating.hasDialog("confirm")) {
return self._templating.showDialog("confirm", message);
}
else {
return window.confirm(message);
}
},
showPrompt: function(message, defaultValue) {
if (self._templating.hasDialog("prompt")) {
return self._templating.showDialog("prompt", message, defaultValue);
}
else {
return window.prompt(message, defaultValue);
}
}
}, true);
// Replace any default options with user defined ones
qq.extend(this._options, o, true);
this._templating = new qq.Templating({
log: qq.bind(this.log, this),
templateIdOrEl: this._options.template,
containerEl: this._options.element,
fileContainerEl: this._options.listElement,
button: this._options.button,
imageGenerator: this._imageGenerator,
classes: {
hide: this._options.classes.hide,
editable: this._options.classes.editable
},
limits: {
maxThumbs: this._options.thumbnails.maxCount,
timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs
},
placeholders: {
waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse,
thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath,
waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath
},
text: this._options.text
});
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari);
}
else if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) {
this._templating.renderFailure(this._options.messages.unsupportedBrowser);
}
else {
this._wrapCallbacks();
this._templating.render();
this._classes = this._options.classes;
if (!this._options.button && this._templating.getButton()) {
this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId();
}
this._setupClickAndEditEventHandlers();
if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) {
this._dnd = this._setupDragAndDrop();
}
if (this._options.paste.targetElement && this._options.paste.promptForName) {
if (qq.PasteSupport) {
this._setupPastePrompt();
}
else {
this.log("Paste support module not found.", "error");
}
}
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
}
};
// Inherit the base public & private API methods
qq.extend(qq.FineUploader.prototype, qq.basePublicApi);
qq.extend(qq.FineUploader.prototype, qq.basePrivateApi);
// Add the FineUploader/default UI public & private UI methods, which may override some base methods.
qq.extend(qq.FineUploader.prototype, qq.uiPublicApi);
qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi);
/* globals qq */
/* jshint -W065 */
/**
* Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least
* a limited amount of control over the template elements after they are added to the DOM.
* Wherever possible, this module asserts total control over template elements present in the DOM.
*
* @param spec Specification object used to control various templating behaviors
* @constructor
*/
qq.Templating = function(spec) {
"use strict";
var FILE_ID_ATTR = "qq-file-id",
FILE_CLASS_PREFIX = "qq-file-id-",
THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size",
THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale",
// This variable is duplicated in the DnD module since it can function as a standalone as well
HIDE_DROPZONE_ATTR = "qq-hide-dropzone",
DROPZPONE_TEXT_ATTR = "qq-drop-area-text",
IN_PROGRESS_CLASS = "qq-in-progress",
HIDDEN_FOREVER_CLASS = "qq-hidden-forever",
isCancelDisabled = false,
generatedThumbnails = 0,
thumbnailQueueMonitorRunning = false,
thumbGenerationQueue = [],
thumbnailMaxSize = -1,
options = {
log: null,
limits: {
maxThumbs: 0,
timeBetweenThumbs: 750
},
templateIdOrEl: "qq-template",
containerEl: null,
fileContainerEl: null,
button: null,
imageGenerator: null,
classes: {
hide: "qq-hide",
editable: "qq-editable"
},
placeholders: {
waitUntilUpdate: false,
thumbnailNotAvailable: null,
waitingForThumbnail: null
},
text: {
paused: "Paused"
}
},
selectorClasses = {
button: "qq-upload-button-selector",
alertDialog: "qq-alert-dialog-selector",
dialogCancelButton: "qq-cancel-button-selector",
confirmDialog: "qq-confirm-dialog-selector",
dialogMessage: "qq-dialog-message-selector",
dialogOkButton: "qq-ok-button-selector",
promptDialog: "qq-prompt-dialog-selector",
uploader: "qq-uploader-selector",
drop: "qq-upload-drop-area-selector",
list: "qq-upload-list-selector",
progressBarContainer: "qq-progress-bar-container-selector",
progressBar: "qq-progress-bar-selector",
totalProgressBarContainer: "qq-total-progress-bar-container-selector",
totalProgressBar: "qq-total-progress-bar-selector",
file: "qq-upload-file-selector",
spinner: "qq-upload-spinner-selector",
size: "qq-upload-size-selector",
cancel: "qq-upload-cancel-selector",
pause: "qq-upload-pause-selector",
continueButton: "qq-upload-continue-selector",
deleteButton: "qq-upload-delete-selector",
retry: "qq-upload-retry-selector",
statusText: "qq-upload-status-text-selector",
editFilenameInput: "qq-edit-filename-selector",
editNameIcon: "qq-edit-filename-icon-selector",
dropText: "qq-upload-drop-area-text-selector",
dropProcessing: "qq-drop-processing-selector",
dropProcessingSpinner: "qq-drop-processing-spinner-selector",
thumbnail: "qq-thumbnail-selector"
},
previewGeneration = {},
cachedThumbnailNotAvailableImg = new qq.Promise(),
cachedWaitingForThumbnailImg = new qq.Promise(),
log,
isEditElementsExist,
isRetryElementExist,
templateHtml,
container,
fileList,
showThumbnails,
serverScale,
// During initialization of the templating module we should cache any
// placeholder images so we can quickly swap them into the file list on demand.
// Any placeholder images that cannot be loaded/found are simply ignored.
cacheThumbnailPlaceholders = function() {
var notAvailableUrl = options.placeholders.thumbnailNotAvailable,
waitingUrl = options.placeholders.waitingForThumbnail,
spec = {
maxSize: thumbnailMaxSize,
scale: serverScale
};
if (showThumbnails) {
if (notAvailableUrl) {
options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(
function(updatedImg) {
cachedThumbnailNotAvailableImg.success(updatedImg);
},
function() {
cachedThumbnailNotAvailableImg.failure();
log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error");
}
);
}
else {
cachedThumbnailNotAvailableImg.failure();
}
if (waitingUrl) {
options.imageGenerator.generate(waitingUrl, new Image(), spec).then(
function(updatedImg) {
cachedWaitingForThumbnailImg.success(updatedImg);
},
function() {
cachedWaitingForThumbnailImg.failure();
log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error");
}
);
}
else {
cachedWaitingForThumbnailImg.failure();
}
}
},
// Displays a "waiting for thumbnail" type placeholder image
// iff we were able to load it during initialization of the templating module.
displayWaitingImg = function(thumbnail) {
var waitingImgPlacement = new qq.Promise();
cachedWaitingForThumbnailImg.then(function(img) {
maybeScalePlaceholderViaCss(img, thumbnail);
/* jshint eqnull:true */
if (!thumbnail.src) {
thumbnail.src = img.src;
thumbnail.onload = function() {
thumbnail.onload = null;
show(thumbnail);
waitingImgPlacement.success();
};
}
else {
waitingImgPlacement.success();
}
}, function() {
// In some browsers (such as IE9 and older) an img w/out a src attribute
// are displayed as "broken" images, so we should just hide the img tag
// if we aren't going to display the "waiting" placeholder.
hide(thumbnail);
waitingImgPlacement.success();
});
return waitingImgPlacement;
},
generateNewPreview = function(id, blob, spec) {
var thumbnail = getThumbnail(id);
log("Generating new thumbnail for " + id);
blob.qqThumbnailId = id;
return options.imageGenerator.generate(blob, thumbnail, spec).then(
function() {
generatedThumbnails++;
show(thumbnail);
previewGeneration[id].success();
},
function() {
previewGeneration[id].failure();
// Display the "not available" placeholder img only if we are
// not expecting a thumbnail at a later point, such as in a server response.
if (!options.placeholders.waitUntilUpdate) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
}
});
},
generateNextQueuedPreview = function() {
if (thumbGenerationQueue.length) {
thumbnailQueueMonitorRunning = true;
var queuedThumbRequest = thumbGenerationQueue.shift();
if (queuedThumbRequest.update) {
processUpdateQueuedPreviewRequest(queuedThumbRequest);
}
else {
processNewQueuedPreviewRequest(queuedThumbRequest);
}
}
else {
thumbnailQueueMonitorRunning = false;
}
},
getCancel = function(id) {
return getTemplateEl(getFile(id), selectorClasses.cancel);
},
getContinue = function(id) {
return getTemplateEl(getFile(id), selectorClasses.continueButton);
},
getDialog = function(type) {
return getTemplateEl(container, selectorClasses[type + "Dialog"]);
},
getDelete = function(id) {
return getTemplateEl(getFile(id), selectorClasses.deleteButton);
},
getDropProcessing = function() {
return getTemplateEl(container, selectorClasses.dropProcessing);
},
getEditIcon = function(id) {
return getTemplateEl(getFile(id), selectorClasses.editNameIcon);
},
getFile = function(id) {
return qq(fileList).getByClass(FILE_CLASS_PREFIX + id)[0];
},
getFilename = function(id) {
return getTemplateEl(getFile(id), selectorClasses.file);
},
getPause = function(id) {
return getTemplateEl(getFile(id), selectorClasses.pause);
},
getProgress = function(id) {
/* jshint eqnull:true */
// Total progress bar
if (id == null) {
return getTemplateEl(container, selectorClasses.totalProgressBarContainer) ||
getTemplateEl(container, selectorClasses.totalProgressBar);
}
// Per-file progress bar
return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) ||
getTemplateEl(getFile(id), selectorClasses.progressBar);
},
getRetry = function(id) {
return getTemplateEl(getFile(id), selectorClasses.retry);
},
getSize = function(id) {
return getTemplateEl(getFile(id), selectorClasses.size);
},
getSpinner = function(id) {
return getTemplateEl(getFile(id), selectorClasses.spinner);
},
getTemplateEl = function(context, cssClass) {
return context && qq(context).getByClass(cssClass)[0];
},
getThumbnail = function(id) {
return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail);
},
hide = function(el) {
el && qq(el).addClass(options.classes.hide);
},
// Ensures a placeholder image does not exceed any max size specified
// via `style` attribute properties iff <canvas> was not used to scale
// the placeholder AND the target <img> doesn't already have these `style` attribute properties set.
maybeScalePlaceholderViaCss = function(placeholder, thumbnail) {
var maxWidth = placeholder.style.maxWidth,
maxHeight = placeholder.style.maxHeight;
if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) {
qq(thumbnail).css({
maxWidth: maxWidth,
maxHeight: maxHeight
});
}
},
// Displays a "thumbnail not available" type placeholder image
// iff we were able to load this placeholder during initialization
// of the templating module or after preview generation has failed.
maybeSetDisplayNotAvailableImg = function(id, thumbnail) {
var previewing = previewGeneration[id] || new qq.Promise().failure(),
notAvailableImgPlacement = new qq.Promise();
cachedThumbnailNotAvailableImg.then(function(img) {
previewing.then(
function() {
notAvailableImgPlacement.success();
},
function() {
maybeScalePlaceholderViaCss(img, thumbnail);
thumbnail.onload = function() {
thumbnail.onload = null;
notAvailableImgPlacement.success();
};
thumbnail.src = img.src;
show(thumbnail);
}
);
});
return notAvailableImgPlacement;
},
/**
* Grabs the HTML from the script tag holding the template markup. This function will also adjust
* some internally-tracked state variables based on the contents of the template.
* The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported)
* are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed.
*
* @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates
*/
parseAndGetTemplate = function() {
var scriptEl,
scriptHtml,
fileListNode,
tempTemplateEl,
fileListHtml,
defaultButton,
dropArea,
thumbnail,
dropProcessing,
dropTextEl,
uploaderEl;
log("Parsing template");
/*jshint -W116*/
if (options.templateIdOrEl == null) {
throw new Error("You MUST specify either a template element or ID!");
}
// Grab the contents of the script tag holding the template.
if (qq.isString(options.templateIdOrEl)) {
scriptEl = document.getElementById(options.templateIdOrEl);
if (scriptEl === null) {
throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl));
}
scriptHtml = scriptEl.innerHTML;
}
else {
if (options.templateIdOrEl.innerHTML === undefined) {
throw new Error("You have specified an invalid value for the template option! " +
"It must be an ID or an Element.");
}
scriptHtml = options.templateIdOrEl.innerHTML;
}
scriptHtml = qq.trimStr(scriptHtml);
tempTemplateEl = document.createElement("div");
tempTemplateEl.appendChild(qq.toElement(scriptHtml));
uploaderEl = qq(tempTemplateEl).getByClass(selectorClasses.uploader)[0];
// Don't include the default template button in the DOM
// if an alternate button container has been specified.
if (options.button) {
defaultButton = qq(tempTemplateEl).getByClass(selectorClasses.button)[0];
if (defaultButton) {
qq(defaultButton).remove();
}
}
// Omit the drop processing element from the DOM if DnD is not supported by the UA,
// or the drag and drop module is not found.
// NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD
// to support layouts where the drop zone is also a container for visible elements,
// such as the file list.
if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) {
dropProcessing = qq(tempTemplateEl).getByClass(selectorClasses.dropProcessing)[0];
if (dropProcessing) {
qq(dropProcessing).remove();
}
}
dropArea = qq(tempTemplateEl).getByClass(selectorClasses.drop)[0];
// If DnD is not available then remove
// it from the DOM as well.
if (dropArea && !qq.DragAndDrop) {
log("DnD module unavailable.", "info");
qq(dropArea).remove();
}
if (!qq.supportedFeatures.fileDrop) {
// don't display any "drop files to upload" background text
uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) {
// If there is a drop area defined in the template, and the current UA doesn't support DnD,
// and the drop area is marked as "hide before enter", ensure it is hidden as the DnD module
// will not do this (since we will not be loading the DnD module)
qq(dropArea).css({
display: "none"
});
}
}
else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) {
dropTextEl = qq(dropArea).getByClass(selectorClasses.dropText)[0];
dropTextEl && qq(dropTextEl).remove();
}
// Ensure the `showThumbnails` flag is only set if the thumbnail element
// is present in the template AND the current UA is capable of generating client-side previews.
thumbnail = qq(tempTemplateEl).getByClass(selectorClasses.thumbnail)[0];
if (!showThumbnails) {
thumbnail && qq(thumbnail).remove();
}
else if (thumbnail) {
thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR));
// Only enforce max size if the attr value is non-zero
thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null;
serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR);
}
showThumbnails = showThumbnails && thumbnail;
isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0;
isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0;
fileListNode = qq(tempTemplateEl).getByClass(selectorClasses.list)[0];
/*jshint -W116*/
if (fileListNode == null) {
throw new Error("Could not find the file list container in the template!");
}
fileListHtml = fileListNode.innerHTML;
fileListNode.innerHTML = "";
// We must call `createElement` in IE8 in order to target and hide any <dialog> via CSS
if (tempTemplateEl.getElementsByTagName("DIALOG").length) {
document.createElement("dialog");
}
log("Template parsing complete");
return {
template: qq.trimStr(tempTemplateEl.innerHTML),
fileTemplate: qq.trimStr(fileListHtml)
};
},
prependFile = function(el, index) {
var parentEl = fileList,
beforeEl = parentEl.firstChild;
if (index > 0) {
beforeEl = qq(parentEl).children()[index].nextSibling;
}
parentEl.insertBefore(el, beforeEl);
},
processNewQueuedPreviewRequest = function(queuedThumbRequest) {
var id = queuedThumbRequest.id,
optFileOrBlob = queuedThumbRequest.optFileOrBlob,
relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId,
thumbnail = getThumbnail(id),
spec = {
maxSize: thumbnailMaxSize,
scale: true,
orient: true
};
if (qq.supportedFeatures.imagePreviews) {
if (thumbnail) {
if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
else {
displayWaitingImg(thumbnail).done(function() {
previewGeneration[id] = new qq.Promise();
previewGeneration[id].done(function() {
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
});
/* jshint eqnull: true */
// If we've already generated an <img> for this file, use the one that exists,
// don't waste resources generating a new one.
if (relatedThumbnailId != null) {
useCachedPreview(id, relatedThumbnailId);
}
else {
generateNewPreview(id, optFileOrBlob, spec);
}
});
}
}
// File element in template may have been removed, so move on to next item in queue
else {
generateNextQueuedPreview();
}
}
else if (thumbnail) {
displayWaitingImg(thumbnail);
generateNextQueuedPreview();
}
},
processUpdateQueuedPreviewRequest = function(queuedThumbRequest) {
var id = queuedThumbRequest.id,
thumbnailUrl = queuedThumbRequest.thumbnailUrl,
showWaitingImg = queuedThumbRequest.showWaitingImg,
thumbnail = getThumbnail(id),
spec = {
maxSize: thumbnailMaxSize,
scale: serverScale
};
if (thumbnail) {
if (thumbnailUrl) {
if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
else {
if (showWaitingImg) {
displayWaitingImg(thumbnail);
}
return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(
function() {
show(thumbnail);
generatedThumbnails++;
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
},
function() {
maybeSetDisplayNotAvailableImg(id, thumbnail);
setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
}
);
}
}
else {
maybeSetDisplayNotAvailableImg(id, thumbnail);
generateNextQueuedPreview();
}
}
},
setProgressBarWidth = function(id, percent) {
var bar = getProgress(id),
/* jshint eqnull:true */
progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar;
if (bar && !qq(bar).hasClass(progressBarSelector)) {
bar = qq(bar).getByClass(progressBarSelector)[0];
}
if (bar) {
qq(bar).css({width: percent + "%"});
bar.setAttribute("aria-valuenow", percent);
}
},
show = function(el) {
el && qq(el).removeClass(options.classes.hide);
},
useCachedPreview = function(targetThumbnailId, cachedThumbnailId) {
var targetThumnail = getThumbnail(targetThumbnailId),
cachedThumbnail = getThumbnail(cachedThumbnailId);
log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId));
// Generation of the related thumbnail may still be in progress, so, wait until it is done.
previewGeneration[cachedThumbnailId].then(function() {
generatedThumbnails++;
previewGeneration[targetThumbnailId].success();
log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId));
targetThumnail.src = cachedThumbnail.src;
show(targetThumnail);
},
function() {
previewGeneration[targetThumbnailId].failure();
if (!options.placeholders.waitUntilUpdate) {
maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumnail);
}
});
};
qq.extend(options, spec);
log = options.log;
// No need to worry about conserving CPU or memory on older browsers,
// since there is no ability to preview, and thumbnail display is primitive and quick.
if (!qq.supportedFeatures.imagePreviews) {
options.limits.timeBetweenThumbs = 0;
options.limits.maxThumbs = 0;
}
container = options.containerEl;
showThumbnails = options.imageGenerator !== undefined;
templateHtml = parseAndGetTemplate();
cacheThumbnailPlaceholders();
qq.extend(this, {
render: function() {
log("Rendering template in DOM.");
generatedThumbnails = 0;
container.innerHTML = templateHtml.template;
hide(getDropProcessing());
this.hideTotalProgress();
fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list);
log("Template rendering complete");
},
renderFailure: function(message) {
var cantRenderEl = qq.toElement(message);
container.innerHTML = "";
container.appendChild(cantRenderEl);
},
reset: function() {
this.render();
},
clearFiles: function() {
fileList.innerHTML = "";
},
disableCancel: function() {
isCancelDisabled = true;
},
addFile: function(id, name, prependInfo, hideForever) {
var fileEl = qq.toElement(templateHtml.fileTemplate),
fileNameEl = getTemplateEl(fileEl, selectorClasses.file),
uploaderEl = getTemplateEl(container, selectorClasses.uploader),
thumb;
qq(fileEl).addClass(FILE_CLASS_PREFIX + id);
uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
if (fileNameEl) {
qq(fileNameEl).setText(name);
fileNameEl.setAttribute("title", name);
}
fileEl.setAttribute(FILE_ID_ATTR, id);
if (prependInfo) {
prependFile(fileEl, prependInfo.index);
}
else {
fileList.appendChild(fileEl);
}
if (hideForever) {
fileEl.style.display = "none";
qq(fileEl).addClass(HIDDEN_FOREVER_CLASS);
}
else {
hide(getProgress(id));
hide(getSize(id));
hide(getDelete(id));
hide(getRetry(id));
hide(getPause(id));
hide(getContinue(id));
if (isCancelDisabled) {
this.hideCancel(id);
}
thumb = getThumbnail(id);
if (thumb && !thumb.src) {
cachedWaitingForThumbnailImg.then(function(waitingImg) {
thumb.src = waitingImg.src;
if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) {
qq(thumb).css({
maxHeight: waitingImg.style.maxHeight,
maxWidth: waitingImg.style.maxWidth
});
}
show(thumb);
});
}
}
},
removeFile: function(id) {
qq(getFile(id)).remove();
},
getFileId: function(el) {
var currentNode = el;
if (currentNode) {
/*jshint -W116*/
while (currentNode.getAttribute(FILE_ID_ATTR) == null) {
currentNode = currentNode.parentNode;
}
return parseInt(currentNode.getAttribute(FILE_ID_ATTR));
}
},
getFileList: function() {
return fileList;
},
markFilenameEditable: function(id) {
var filename = getFilename(id);
filename && qq(filename).addClass(options.classes.editable);
},
updateFilename: function(id, name) {
var filenameEl = getFilename(id);
if (filenameEl) {
qq(filenameEl).setText(name);
filenameEl.setAttribute("title", name);
}
},
hideFilename: function(id) {
hide(getFilename(id));
},
showFilename: function(id) {
show(getFilename(id));
},
isFileName: function(el) {
return qq(el).hasClass(selectorClasses.file);
},
getButton: function() {
return options.button || getTemplateEl(container, selectorClasses.button);
},
hideDropProcessing: function() {
hide(getDropProcessing());
},
showDropProcessing: function() {
show(getDropProcessing());
},
getDropZone: function() {
return getTemplateEl(container, selectorClasses.drop);
},
isEditFilenamePossible: function() {
return isEditElementsExist;
},
hideRetry: function(id) {
hide(getRetry(id));
},
isRetryPossible: function() {
return isRetryElementExist;
},
showRetry: function(id) {
show(getRetry(id));
},
getFileContainer: function(id) {
return getFile(id);
},
showEditIcon: function(id) {
var icon = getEditIcon(id);
icon && qq(icon).addClass(options.classes.editable);
},
isHiddenForever: function(id) {
return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS);
},
hideEditIcon: function(id) {
var icon = getEditIcon(id);
icon && qq(icon).removeClass(options.classes.editable);
},
isEditIcon: function(el) {
return qq(el).hasClass(selectorClasses.editNameIcon, true);
},
getEditInput: function(id) {
return getTemplateEl(getFile(id), selectorClasses.editFilenameInput);
},
isEditInput: function(el) {
return qq(el).hasClass(selectorClasses.editFilenameInput, true);
},
updateProgress: function(id, loaded, total) {
var bar = getProgress(id),
percent;
if (bar && total > 0) {
percent = Math.round(loaded / total * 100);
if (percent === 100) {
hide(bar);
}
else {
show(bar);
}
setProgressBarWidth(id, percent);
}
},
updateTotalProgress: function(loaded, total) {
this.updateProgress(null, loaded, total);
},
hideProgress: function(id) {
var bar = getProgress(id);
bar && hide(bar);
},
hideTotalProgress: function() {
this.hideProgress();
},
resetProgress: function(id) {
setProgressBarWidth(id, 0);
this.hideTotalProgress(id);
},
resetTotalProgress: function() {
this.resetProgress();
},
showCancel: function(id) {
if (!isCancelDisabled) {
var cancel = getCancel(id);
cancel && qq(cancel).removeClass(options.classes.hide);
}
},
hideCancel: function(id) {
hide(getCancel(id));
},
isCancel: function(el) {
return qq(el).hasClass(selectorClasses.cancel, true);
},
allowPause: function(id) {
show(getPause(id));
hide(getContinue(id));
},
uploadPaused: function(id) {
this.setStatusText(id, options.text.paused);
this.allowContinueButton(id);
hide(getSpinner(id));
},
hidePause: function(id) {
hide(getPause(id));
},
isPause: function(el) {
return qq(el).hasClass(selectorClasses.pause, true);
},
isContinueButton: function(el) {
return qq(el).hasClass(selectorClasses.continueButton, true);
},
allowContinueButton: function(id) {
show(getContinue(id));
hide(getPause(id));
},
uploadContinued: function(id) {
this.setStatusText(id, "");
this.allowPause(id);
show(getSpinner(id));
},
showDeleteButton: function(id) {
show(getDelete(id));
},
hideDeleteButton: function(id) {
hide(getDelete(id));
},
isDeleteButton: function(el) {
return qq(el).hasClass(selectorClasses.deleteButton, true);
},
isRetry: function(el) {
return qq(el).hasClass(selectorClasses.retry, true);
},
updateSize: function(id, text) {
var size = getSize(id);
if (size) {
show(size);
qq(size).setText(text);
}
},
setStatusText: function(id, text) {
var textEl = getTemplateEl(getFile(id), selectorClasses.statusText);
if (textEl) {
/*jshint -W116*/
if (text == null) {
qq(textEl).clearText();
}
else {
qq(textEl).setText(text);
}
}
},
hideSpinner: function(id) {
qq(getFile(id)).removeClass(IN_PROGRESS_CLASS);
hide(getSpinner(id));
},
showSpinner: function(id) {
qq(getFile(id)).addClass(IN_PROGRESS_CLASS);
show(getSpinner(id));
},
generatePreview: function(id, optFileOrBlob) {
if (!this.isHiddenForever(id)) {
thumbGenerationQueue.push({id: id, optFileOrBlob: optFileOrBlob});
!thumbnailQueueMonitorRunning && generateNextQueuedPreview();
}
},
updateThumbnail: function(id, thumbnailUrl, showWaitingImg) {
if (!this.isHiddenForever(id)) {
thumbGenerationQueue.push({update: true, id: id, thumbnailUrl: thumbnailUrl, showWaitingImg: showWaitingImg});
!thumbnailQueueMonitorRunning && generateNextQueuedPreview();
}
},
hasDialog: function(type) {
return qq.supportedFeatures.dialogElement && !!getDialog(type);
},
showDialog: function(type, message, defaultValue) {
var dialog = getDialog(type),
messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage),
inputEl = dialog.getElementsByTagName("INPUT")[0],
cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton),
okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton),
promise = new qq.Promise(),
closeHandler = function() {
cancelBtn.removeEventListener("click", cancelClickHandler);
okBtn && okBtn.removeEventListener("click", okClickHandler);
promise.failure();
},
cancelClickHandler = function() {
cancelBtn.removeEventListener("click", cancelClickHandler);
dialog.close();
},
okClickHandler = function() {
dialog.removeEventListener("close", closeHandler);
okBtn.removeEventListener("click", okClickHandler);
dialog.close();
promise.success(inputEl && inputEl.value);
};
dialog.addEventListener("close", closeHandler);
cancelBtn.addEventListener("click", cancelClickHandler);
okBtn && okBtn.addEventListener("click", okClickHandler);
if (inputEl) {
inputEl.value = defaultValue;
}
messageEl.textContent = message;
dialog.showModal();
return promise;
}
});
};
/*globals qq */
qq.s3 = qq.s3 || {};
qq.s3.util = qq.s3.util || (function() {
"use strict";
return {
AWS_PARAM_PREFIX: "x-amz-meta-",
SESSION_TOKEN_PARAM_NAME: "x-amz-security-token",
REDUCED_REDUNDANCY_PARAM_NAME: "x-amz-storage-class",
REDUCED_REDUNDANCY_PARAM_VALUE: "REDUCED_REDUNDANCY",
SERVER_SIDE_ENCRYPTION_PARAM_NAME: "x-amz-server-side-encryption",
SERVER_SIDE_ENCRYPTION_PARAM_VALUE: "AES256",
/**
* This allows for the region to be specified in the bucket's endpoint URL, or not.
*
* Examples of some valid endpoints are:
* http://foo.s3.amazonaws.com
* https://foo.s3.amazonaws.com
* http://foo.s3-ap-northeast-1.amazonaws.com
* foo.s3.amazonaws.com
* http://foo.bar.com
* http://s3.amazonaws.com/foo.bar.com
* ...etc
*
* @param endpoint The bucket's URL.
* @returns {String || undefined} The bucket name, or undefined if the URL cannot be parsed.
*/
getBucket: function(endpoint) {
var patterns = [
//bucket in domain
/^(?:https?:\/\/)?([a-z0-9.\-_]+)\.s3(?:-[a-z0-9\-]+)?\.amazonaws\.com/i,
//bucket in path
/^(?:https?:\/\/)?s3(?:-[a-z0-9\-]+)?\.amazonaws\.com\/([a-z0-9.\-_]+)/i,
//custom domain
/^(?:https?:\/\/)?([a-z0-9.\-_]+)/i
],
bucket;
qq.each(patterns, function(idx, pattern) {
var match = pattern.exec(endpoint);
if (match) {
bucket = match[1];
return false;
}
});
return bucket;
},
/**
* Create a policy document to be signed and sent along with the S3 upload request.
*
* @param spec Object with properties use to construct the policy document.
* @returns {Object} Policy doc.
*/
getPolicy: function(spec) {
var policy = {},
conditions = [],
bucket = spec.bucket,
key = spec.key,
acl = spec.acl,
type = spec.type,
expirationDate = new Date(),
expectedStatus = spec.expectedStatus,
sessionToken = spec.sessionToken,
params = spec.params,
successRedirectUrl = qq.s3.util.getSuccessRedirectAbsoluteUrl(spec.successRedirectUrl),
minFileSize = spec.minFileSize,
maxFileSize = spec.maxFileSize,
reducedRedundancy = spec.reducedRedundancy,
serverSideEncryption = spec.serverSideEncryption;
policy.expiration = qq.s3.util.getPolicyExpirationDate(expirationDate);
conditions.push({acl: acl});
conditions.push({bucket: bucket});
if (type) {
conditions.push({"Content-Type": type});
}
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
if (expectedStatus) {
conditions.push({success_action_status: expectedStatus.toString()});
}
if (successRedirectUrl) {
conditions.push({success_action_redirect: successRedirectUrl});
}
// jscs:enable
if (reducedRedundancy) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (sessionToken) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
if (serverSideEncryption) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
conditions.push({key: key});
// user metadata
qq.each(params, function(name, val) {
var awsParamName = qq.s3.util.AWS_PARAM_PREFIX + name,
param = {};
param[awsParamName] = encodeURIComponent(val);
conditions.push(param);
});
policy.conditions = conditions;
qq.s3.util.enforceSizeLimits(policy, minFileSize, maxFileSize);
return policy;
},
/**
* Update a previously constructed policy document with updated credentials. Currently, this only requires we
* update the session token. This is only relevant if requests are being signed client-side.
*
* @param policy Live policy document
* @param newSessionToken Updated session token.
*/
refreshPolicyCredentials: function(policy, newSessionToken) {
var sessionTokenFound = false;
qq.each(policy.conditions, function(oldCondIdx, oldCondObj) {
qq.each(oldCondObj, function(oldCondName, oldCondVal) {
if (oldCondName === qq.s3.util.SESSION_TOKEN_PARAM_NAME) {
oldCondObj[oldCondName] = newSessionToken;
sessionTokenFound = true;
}
});
});
if (!sessionTokenFound) {
policy.conditions.push({});
policy.conditions[policy.conditions.length - 1][qq.s3.util.SESSION_TOKEN_PARAM_NAME] = newSessionToken;
}
},
/**
* Generates all parameters to be passed along with the S3 upload request. This includes invoking a callback
* that is expected to asynchronously retrieve a signature for the policy document. Note that the server
* signing the request should reject a "tainted" policy document that includes unexpected values, since it is
* still possible for a malicious user to tamper with these values during policy document generation, b
* before it is sent to the server for signing.
*
* @param spec Object with properties: `params`, `type`, `key`, `accessKey`, `acl`, `expectedStatus`, `successRedirectUrl`,
* `reducedRedundancy`, serverSideEncryption, and `log()`, along with any options associated with `qq.s3.util.getPolicy()`.
* @returns {qq.Promise} Promise that will be fulfilled once all parameters have been determined.
*/
generateAwsParams: function(spec, signPolicyCallback) {
var awsParams = {},
customParams = spec.params,
promise = new qq.Promise(),
policyJson = qq.s3.util.getPolicy(spec),
sessionToken = spec.sessionToken,
type = spec.type,
key = spec.key,
accessKey = spec.accessKey,
acl = spec.acl,
expectedStatus = spec.expectedStatus,
successRedirectUrl = qq.s3.util.getSuccessRedirectAbsoluteUrl(spec.successRedirectUrl),
reducedRedundancy = spec.reducedRedundancy,
serverSideEncryption = spec.serverSideEncryption,
log = spec.log;
awsParams.key = key;
awsParams.AWSAccessKeyId = accessKey;
if (type) {
awsParams["Content-Type"] = type;
}
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
if (expectedStatus) {
awsParams.success_action_status = expectedStatus;
}
if (successRedirectUrl) {
awsParams.success_action_redirect = successRedirectUrl;
}
// jscs:enable
if (reducedRedundancy) {
awsParams[qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (serverSideEncryption) {
awsParams[qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
if (sessionToken) {
awsParams[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
awsParams.acl = acl;
// Custom (user-supplied) params must be prefixed with the value of `qq.s3.util.AWS_PARAM_PREFIX`.
// Custom param values will be URI encoded as well.
qq.each(customParams, function(name, val) {
var awsParamName = qq.s3.util.AWS_PARAM_PREFIX + name;
awsParams[awsParamName] = encodeURIComponent(val);
});
// Invoke a promissory callback that should provide us with a base64-encoded policy doc and an
// HMAC signature for the policy doc.
signPolicyCallback(policyJson).then(
function(policyAndSignature, updatedAccessKey, updatedSessionToken) {
awsParams.policy = policyAndSignature.policy;
awsParams.signature = policyAndSignature.signature;
if (updatedAccessKey) {
awsParams.AWSAccessKeyId = updatedAccessKey;
}
if (updatedSessionToken) {
awsParams[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = updatedSessionToken;
}
promise.success(awsParams);
},
function(errorMessage) {
errorMessage = errorMessage || "Can't continue further with request to S3 as we did not receive " +
"a valid signature and policy from the server.";
log("Policy signing failed. " + errorMessage, "error");
promise.failure(errorMessage);
}
);
return promise;
},
/**
* Add a condition to an existing S3 upload request policy document used to ensure AWS enforces any size
* restrictions placed on files server-side. This is important to do, in case users mess with the client-side
* checks already in place.
*
* @param policy Policy document as an `Object`, with a `conditions` property already attached
* @param minSize Minimum acceptable size, in bytes
* @param maxSize Maximum acceptable size, in bytes (0 = unlimited)
*/
enforceSizeLimits: function(policy, minSize, maxSize) {
var adjustedMinSize = minSize < 0 ? 0 : minSize,
// Adjust a maxSize of 0 to the largest possible integer, since we must specify a high and a low in the request
adjustedMaxSize = maxSize <= 0 ? 9007199254740992 : maxSize;
if (minSize > 0 || maxSize > 0) {
policy.conditions.push(["content-length-range", adjustedMinSize.toString(), adjustedMaxSize.toString()]);
}
},
getPolicyExpirationDate: function(date) {
/*jshint -W014 */
// Is this going to be a problem if we encounter this moments before 2 AM just before daylight savings time ends?
date.setMinutes(date.getMinutes() + 5);
if (Date.prototype.toISOString) {
return date.toISOString();
}
else {
var pad = function(number) {
var r = String(number);
if (r.length === 1) {
r = "0" + r;
}
return r;
};
return date.getUTCFullYear()
+ "-" + pad(date.getUTCMonth() + 1)
+ "-" + pad(date.getUTCDate())
+ "T" + pad(date.getUTCHours())
+ ":" + pad(date.getUTCMinutes())
+ ":" + pad(date.getUTCSeconds())
+ "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
+ "Z";
}
},
/**
* Looks at a response from S3 contained in an iframe and parses the query string in an attempt to identify
* the associated resource.
*
* @param iframe Iframe containing response
* @returns {{bucket: *, key: *, etag: *}}
*/
parseIframeResponse: function(iframe) {
var doc = iframe.contentDocument || iframe.contentWindow.document,
queryString = doc.location.search,
match = /bucket=(.+)&key=(.+)&etag=(.+)/.exec(queryString);
if (match) {
return {
bucket: match[1],
key: match[2],
etag: match[3].replace(/%22/g, "")
};
}
},
/**
* @param successRedirectUrl Relative or absolute location of success redirect page
* @returns {*|string} undefined if the parameter is undefined, otherwise the absolute location of the success redirect page
*/
getSuccessRedirectAbsoluteUrl: function(successRedirectUrl) {
if (successRedirectUrl) {
var targetAnchorContainer = document.createElement("div"),
targetAnchor;
if (qq.ie7()) {
// Note that we must make use of `innerHTML` for IE7 only instead of simply creating an anchor via
// `document.createElement('a')` and setting the `href` attribute. The latter approach does not allow us to
// obtain an absolute URL in IE7 if the `endpoint` is a relative URL.
targetAnchorContainer.innerHTML = "<a href='" + successRedirectUrl + "'></a>";
targetAnchor = targetAnchorContainer.firstChild;
return targetAnchor.href;
}
else {
// IE8 and IE9 do not seem to derive an absolute URL from a relative URL using the `innerHTML`
// approach above, so we'll just create an anchor this way and set it's `href` attribute.
// Due to yet another quirk in IE8 and IE9, we have to set the `href` equal to itself
// in order to ensure relative URLs will be properly parsed.
targetAnchor = document.createElement("a");
targetAnchor.href = successRedirectUrl;
targetAnchor.href = targetAnchor.href;
return targetAnchor.href;
}
}
},
// AWS employs a strict interpretation of [RFC 3986](http://tools.ietf.org/html/rfc3986#page-12).
// So, we must ensure all reserved characters listed in the spec are percent-encoded,
// and spaces are replaced with "+".
encodeQueryStringParam: function(param) {
var percentEncoded = encodeURIComponent(param);
// %-encode characters not handled by `encodeURIComponent` (to follow RFC 3986)
percentEncoded = percentEncoded.replace(/[!'()]/g, escape);
// %-encode characters not handled by `escape` (to follow RFC 3986)
percentEncoded = percentEncoded.replace(/\*/g, "%2A");
// replace percent-encoded spaces with a "+"
return percentEncoded.replace(/%20/g, "+");
}
};
}());
/*globals qq*/
/**
* Defines the public API for non-traditional FineUploaderBasic mode.
*/
(function() {
"use strict";
qq.nonTraditionalBasePublicApi = {
setUploadSuccessParams: function(params, id) {
this._uploadSuccessParamsStore.set(params, id);
},
setUploadSuccessEndpoint: function(endpoint, id) {
this._uploadSuccessEndpointStore.set(endpoint, id);
}
};
qq.nonTraditionalBasePrivateApi = {
/**
* When the upload has completed, if it is successful, send a request to the `successEndpoint` (if defined).
* This will hold up the call to the `onComplete` callback until we have determined success of the upload
* according to the local server, if a `successEndpoint` has been defined by the integrator.
*
* @param id ID of the completed upload
* @param name Name of the associated item
* @param result Object created from the server's parsed JSON response.
* @param xhr Associated XmlHttpRequest, if this was used to send the request.
* @returns {boolean || qq.Promise} true/false if success can be determined immediately, otherwise a `qq.Promise`
* if we need to ask the server.
* @private
*/
_onComplete: function(id, name, result, xhr) {
var success = result.success ? true : false,
self = this,
onCompleteArgs = arguments,
successEndpoint = this._uploadSuccessEndpointStore.get(id),
successCustomHeaders = this._options.uploadSuccess.customHeaders,
successMethod = this._options.uploadSuccess.method,
cors = this._options.cors,
promise = new qq.Promise(),
uploadSuccessParams = this._uploadSuccessParamsStore.get(id),
fileParams = this._paramsStore.get(id),
// If we are waiting for confirmation from the local server, and have received it,
// include properties from the local server response in the `response` parameter
// sent to the `onComplete` callback, delegate to the parent `_onComplete`, and
// fulfill the associated promise.
onSuccessFromServer = function(successRequestResult) {
delete self._failedSuccessRequestCallbacks[id];
qq.extend(result, successRequestResult);
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.success(successRequestResult);
},
// If the upload success request fails, attempt to re-send the success request (via the core retry code).
// The entire upload may be restarted if the server returns a "reset" property with a value of true as well.
onFailureFromServer = function(successRequestResult) {
var callback = submitSuccessRequest;
qq.extend(result, successRequestResult);
if (result && result.reset) {
callback = null;
}
if (!callback) {
delete self._failedSuccessRequestCallbacks[id];
}
else {
self._failedSuccessRequestCallbacks[id] = callback;
}
if (!self._onAutoRetry(id, name, result, xhr, callback)) {
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.failure(successRequestResult);
}
},
submitSuccessRequest,
successAjaxRequester;
// Ask the local server if the file sent is ok.
if (success && successEndpoint) {
successAjaxRequester = new qq.UploadSuccessAjaxRequester({
endpoint: successEndpoint,
method: successMethod,
customHeaders: successCustomHeaders,
cors: cors,
log: qq.bind(this.log, this)
});
// combine custom params and default params
qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true);
// include any params associated with the file
fileParams && qq.extend(uploadSuccessParams, fileParams, true);
submitSuccessRequest = qq.bind(function() {
successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams)
.then(onSuccessFromServer, onFailureFromServer);
}, self);
submitSuccessRequest();
return promise;
}
// If we are not asking the local server about the file, just delegate to the parent `_onComplete`.
return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments);
},
// If the failure occurred on an upload success request (and a reset was not ordered), try to resend that instead.
_manualRetry: function(id) {
var successRequestCallback = this._failedSuccessRequestCallbacks[id];
return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback);
}
};
}());
/*globals qq */
/**
* This defines FineUploaderBasic mode w/ support for uploading to S3, which provides all the basic
* functionality of Fine Uploader Basic as well as code to handle uploads directly to S3.
* Some inherited options and API methods have a special meaning in the context of the S3 uploader.
*/
(function() {
"use strict";
qq.s3.FineUploaderBasic = function(o) {
var options = {
request: {
// public key (required for server-side signing, ignored if `credentials` have been provided)
accessKey: null
},
objectProperties: {
acl: "private",
// string or a function which may be promissory
bucket: qq.bind(function(id) {
return qq.s3.util.getBucket(this.getEndpoint(id));
}, this),
// 'uuid', 'filename', or a function which may be promissory
key: "uuid",
reducedRedundancy: false,
serverSideEncryption: false
},
credentials: {
// Public key (required).
accessKey: null,
// Private key (required).
secretKey: null,
// Expiration date for the credentials (required). May be an ISO string or a `Date`.
expiration: null,
// Temporary credentials session token.
// Only required for temporary credentials obtained via AssumeRoleWithWebIdentity.
sessionToken: null
},
// optional/ignored if `credentials` is provided
signature: {
endpoint: null,
customHeaders: {}
},
uploadSuccess: {
endpoint: null,
method: "POST",
// In addition to the default params sent by Fine Uploader
params: {},
customHeaders: {}
},
// required if non-File-API browsers, such as IE9 and older, are used
iframeSupport: {
localBlankPagePath: null
},
chunking: {
// minimum part size is 5 MiB when uploading to S3
partSize: 5242880
},
cors: {
allowXdr: true
},
callbacks: {
onCredentialsExpired: function() {}
}
};
// Replace any default options with user defined ones
qq.extend(options, o, true);
if (!this.setCredentials(options.credentials, true)) {
this._currentCredentials.accessKey = options.request.accessKey;
}
this._aclStore = this._createStore(options.objectProperties.acl);
// Call base module
qq.FineUploaderBasic.call(this, options);
this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params);
this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint);
// This will hold callbacks for failed uploadSuccess requests that will be invoked on retry.
// Indexed by file ID.
this._failedSuccessRequestCallbacks = {};
// Holds S3 keys for file representations constructed from a session request.
this._cannedKeys = {};
// Holds S3 buckets for file representations constructed from a session request.
this._cannedBuckets = {};
this._buckets = {};
};
// Inherit basic public & private API methods.
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.basePublicApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.basePrivateApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi);
// Define public & private API methods for this module.
qq.extend(qq.s3.FineUploaderBasic.prototype, {
getBucket: function(id) {
if (this._cannedBuckets[id] == null) {
return this._buckets[id];
}
return this._cannedBuckets[id];
},
/**
* @param id File ID
* @returns {*} Key name associated w/ the file, if one exists
*/
getKey: function(id) {
/* jshint eqnull:true */
if (this._cannedKeys[id] == null) {
return this._handler.getThirdPartyFileId(id);
}
return this._cannedKeys[id];
},
/**
* Override the parent's reset function to cleanup various S3-related items.
*/
reset: function() {
qq.FineUploaderBasic.prototype.reset.call(this);
this._failedSuccessRequestCallbacks = [];
this._buckets = {};
},
setCredentials: function(credentials, ignoreEmpty) {
if (credentials && credentials.secretKey) {
if (!credentials.accessKey) {
throw new qq.Error("Invalid credentials: no accessKey");
}
else if (!credentials.expiration) {
throw new qq.Error("Invalid credentials: no expiration");
}
else {
this._currentCredentials = qq.extend({}, credentials);
// Ensure expiration is a `Date`. If initially a string, assuming it is in ISO format.
if (qq.isString(credentials.expiration)) {
this._currentCredentials.expiration = new Date(credentials.expiration);
}
}
return true;
}
else if (!ignoreEmpty) {
throw new qq.Error("Invalid credentials parameter!");
}
else {
this._currentCredentials = {};
}
},
setAcl: function(acl, id) {
this._aclStore.set(acl, id);
},
/**
* Ensures the parent's upload handler creator passes any additional S3-specific options to the handler as well
* as information required to instantiate the specific handler based on the current browser's capabilities.
*
* @returns {qq.UploadHandlerController}
* @private
*/
_createUploadHandler: function() {
var self = this,
additionalOptions = {
aclStore: this._aclStore,
getBucket: qq.bind(this._determineBucket, this),
getKeyName: qq.bind(this._determineKeyName, this),
iframeSupport: this._options.iframeSupport,
objectProperties: this._options.objectProperties,
signature: this._options.signature,
// pass size limit validation values to include in the request so AWS enforces this server-side
validation: {
minSizeLimit: this._options.validation.minSizeLimit,
maxSizeLimit: this._options.validation.sizeLimit
}
};
// We assume HTTP if it is missing from the start of the endpoint string.
qq.override(this._endpointStore, function(super_) {
return {
get: function(id) {
var endpoint = super_.get(id);
if (endpoint.indexOf("http") < 0) {
return "http://" + endpoint;
}
return endpoint;
}
};
});
// Param names should be lower case to avoid signature mismatches
qq.override(this._paramsStore, function(super_) {
return {
get: function(id) {
var oldParams = super_.get(id),
modifiedParams = {};
qq.each(oldParams, function(name, val) {
modifiedParams[name.toLowerCase()] = qq.isFunction(val) ? val() : val;
});
return modifiedParams;
}
};
});
additionalOptions.signature.credentialsProvider = {
get: function() {
return self._currentCredentials;
},
onExpired: function() {
var updateCredentials = new qq.Promise(),
callbackRetVal = self._options.callbacks.onCredentialsExpired();
if (qq.isGenericPromise(callbackRetVal)) {
callbackRetVal.then(function(credentials) {
try {
self.setCredentials(credentials);
updateCredentials.success();
}
catch (error) {
self.log("Invalid credentials returned from onCredentialsExpired callback! (" + error.message + ")", "error");
updateCredentials.failure("onCredentialsExpired did not return valid credentials.");
}
}, function(errorMsg) {
self.log("onCredentialsExpired callback indicated failure! (" + errorMsg + ")", "error");
updateCredentials.failure("onCredentialsExpired callback failed.");
});
}
else {
self.log("onCredentialsExpired callback did not return a promise!", "error");
updateCredentials.failure("Unexpected return value for onCredentialsExpired.");
}
return updateCredentials;
}
};
return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, additionalOptions, "s3");
},
_determineBucket: function(id) {
var maybeBucket = this._options.objectProperties.bucket,
promise = new qq.Promise(),
self = this;
if (qq.isFunction(maybeBucket)) {
maybeBucket = maybeBucket(id);
if (qq.isGenericPromise(maybeBucket)) {
promise = maybeBucket;
}
else {
promise.success(maybeBucket);
}
}
else if (qq.isString(maybeBucket)) {
promise.success(maybeBucket);
}
promise.then(
function success(bucket) {
self._buckets[id] = bucket;
},
function failure(errorMsg) {
qq.log("Problem determining bucket for ID " + id + " (" + errorMsg + ")", "error");
}
);
return promise;
},
/**
* Determine the file's key name and passes it to the caller via a promissory callback. This also may
* delegate to an integrator-defined function that determines the file's key name on demand,
* which also may be promissory.
*
* @param id ID of the file
* @param filename Name of the file
* @returns {qq.Promise} A promise that will be fulfilled when the key name has been determined (and will be passed to the caller via the success callback).
* @private
*/
_determineKeyName: function(id, filename) {
/*jshint -W015*/
var promise = new qq.Promise(),
keynameLogic = this._options.objectProperties.key,
extension = qq.getExtension(filename),
onGetKeynameFailure = promise.failure,
onGetKeynameSuccess = function(keyname, extension) {
var keynameToUse = keyname;
if (extension !== undefined) {
keynameToUse += "." + extension;
}
promise.success(keynameToUse);
};
switch (keynameLogic) {
case "uuid":
onGetKeynameSuccess(this.getUuid(id), extension);
break;
case "filename":
onGetKeynameSuccess(filename);
break;
default:
if (qq.isFunction(keynameLogic)) {
this._handleKeynameFunction(keynameLogic, id, onGetKeynameSuccess, onGetKeynameFailure);
}
else {
this.log(keynameLogic + " is not a valid value for the s3.keyname option!", "error");
onGetKeynameFailure();
}
}
return promise;
},
/**
* Called by the internal onUpload handler if the integrator has supplied a function to determine
* the file's key name. The integrator's function may be promissory. We also need to fulfill
* the promise contract associated with the caller as well.
*
* @param keynameFunc Integrator-supplied function that must be executed to determine the key name. May be promissory.
* @param id ID of the associated file
* @param successCallback Invoke this if key name retrieval is successful, passing in the key name.
* @param failureCallback Invoke this if key name retrieval was unsuccessful.
* @private
*/
_handleKeynameFunction: function(keynameFunc, id, successCallback, failureCallback) {
var self = this,
onSuccess = function(keyname) {
successCallback(keyname);
},
onFailure = function(reason) {
self.log(qq.format("Failed to retrieve key name for {}. Reason: {}", id, reason || "null"), "error");
failureCallback(reason);
},
keyname = keynameFunc.call(this, id);
if (qq.isGenericPromise(keyname)) {
keyname.then(onSuccess, onFailure);
}
/*jshint -W116*/
else if (keyname == null) {
onFailure();
}
else {
onSuccess(keyname);
}
},
_getEndpointSpecificParams: function(id, response, maybeXhr) {
var params = {
key: this.getKey(id),
uuid: this.getUuid(id),
name: this.getName(id),
bucket: this.getBucket(id)
};
if (maybeXhr && maybeXhr.getResponseHeader("ETag")) {
params.etag = maybeXhr.getResponseHeader("ETag");
}
else if (response.etag) {
params.etag = response.etag;
}
return params;
},
// Hooks into the base internal `_onSubmitDelete` to add key and bucket params to the delete file request.
_onSubmitDelete: function(id, onSuccessCallback) {
var additionalMandatedParams = {
key: this.getKey(id),
bucket: this.getBucket(id)
};
return qq.FineUploaderBasic.prototype._onSubmitDelete.call(this, id, onSuccessCallback, additionalMandatedParams);
},
_addCannedFile: function(sessionData) {
var id;
/* jshint eqnull:true */
if (sessionData.s3Key == null) {
throw new qq.Error("Did not find s3Key property in server session response. This is required!");
}
else {
id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments);
this._cannedKeys[id] = sessionData.s3Key;
this._cannedBuckets[id] = sessionData.s3Bucket;
}
return id;
}
});
}());
/* globals qq, CryptoJS */
/**
* Handles signature determination for HTML Form Upload requests and Multipart Uploader requests (via the S3 REST API).
*
* If the S3 requests are to be signed server side, this module will send a POST request to the server in an attempt
* to solicit signatures for various S3-related requests. This module also parses the response and attempts
* to determine if the effort was successful.
*
* If the S3 requests are to be signed client-side, without the help of a server, this module will utilize CryptoJS to
* sign the requests directly in the browser and send them off to S3.
*
* @param o Options associated with all such requests
* @returns {{getSignature: Function}} API method used to initiate the signature request.
* @constructor
*/
qq.s3.RequestSigner = function(o) {
"use strict";
var requester,
thisSignatureRequester = this,
pendingSignatures = {},
options = {
expectingPolicy: false,
method: "POST",
signatureSpec: {
credentialsProvider: {},
endpoint: null,
customHeaders: {}
},
maxConnections: 3,
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
},
credentialsProvider;
qq.extend(options, o, true);
credentialsProvider = options.signatureSpec.credentialsProvider;
function handleSignatureReceived(id, xhrOrXdr, isError) {
var responseJson = xhrOrXdr.responseText,
pendingSignatureData = pendingSignatures[id],
promise = pendingSignatureData.promise,
errorMessage, response;
delete pendingSignatures[id];
// Attempt to parse what we would expect to be a JSON response
if (responseJson) {
try {
response = qq.parseJson(responseJson);
}
catch (error) {
options.log("Error attempting to parse signature response: " + error, "error");
}
}
// If we have received a parsable response, and it has an `invalid` property,
// the policy document or request headers may have been tampered with client-side.
if (response && response.invalid) {
isError = true;
errorMessage = "Invalid policy document or request headers!";
}
// Make sure the response contains policy & signature properties
else if (response) {
if (options.expectingPolicy && !response.policy) {
isError = true;
errorMessage = "Response does not include the base64 encoded policy!";
}
else if (!response.signature) {
isError = true;
errorMessage = "Response does not include the signature!";
}
}
// Something unknown went wrong
else {
isError = true;
errorMessage = "Received an empty or invalid response from the server!";
}
if (isError) {
if (errorMessage) {
options.log(errorMessage, "error");
}
promise.failure(errorMessage);
}
else {
promise.success(response);
}
}
function getToSignAndEndOfUrl(type, bucket, key, contentType, headers, uploadId, partNum) {
var method = "POST",
headerNames = [],
headersAsString = "",
endOfUrl;
/*jshint indent:false */
switch (type) {
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_ABORT:
method = "DELETE";
endOfUrl = qq.format("uploadId={}", uploadId);
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_INITIATE:
endOfUrl = "uploads";
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_COMPLETE:
endOfUrl = qq.format("uploadId={}", uploadId);
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_UPLOAD:
method = "PUT";
endOfUrl = qq.format("partNumber={}&uploadId={}", partNum, uploadId);
break;
}
endOfUrl = key + "?" + endOfUrl;
qq.each(headers, function(name) {
headerNames.push(name);
});
headerNames.sort();
qq.each(headerNames, function(idx, name) {
headersAsString += name + ":" + headers[name] + "\n";
});
return {
toSign: qq.format("{}\n\n{}\n\n{}/{}/{}",
method, contentType || "", headersAsString || "\n", bucket, endOfUrl),
endOfUrl: endOfUrl
};
}
function determineSignatureClientSide(toBeSigned, signatureEffort, updatedAccessKey, updatedSessionToken) {
var updatedHeaders;
// REST API request
if (toBeSigned.signatureConstructor) {
if (updatedSessionToken) {
updatedHeaders = toBeSigned.signatureConstructor.getHeaders();
updatedHeaders[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = updatedSessionToken;
toBeSigned.signatureConstructor.withHeaders(updatedHeaders);
}
signApiRequest(toBeSigned.signatureConstructor.getToSign().stringToSign, signatureEffort);
}
// Form upload (w/ policy document)
else {
updatedSessionToken && qq.s3.util.refreshPolicyCredentials(toBeSigned, updatedSessionToken);
signPolicy(toBeSigned, signatureEffort, updatedAccessKey, updatedSessionToken);
}
}
function signPolicy(policy, signatureEffort, updatedAccessKey, updatedSessionToken) {
var policyStr = JSON.stringify(policy),
policyWordArray = CryptoJS.enc.Utf8.parse(policyStr),
base64Policy = CryptoJS.enc.Base64.stringify(policyWordArray),
policyHmacSha1 = CryptoJS.HmacSHA1(base64Policy, credentialsProvider.get().secretKey),
policyHmacSha1Base64 = CryptoJS.enc.Base64.stringify(policyHmacSha1);
signatureEffort.success({
policy: base64Policy,
signature: policyHmacSha1Base64
}, updatedAccessKey, updatedSessionToken);
}
function signApiRequest(headersStr, signatureEffort) {
var headersWordArray = CryptoJS.enc.Utf8.parse(headersStr),
headersHmacSha1 = CryptoJS.HmacSHA1(headersWordArray, credentialsProvider.get().secretKey),
headersHmacSha1Base64 = CryptoJS.enc.Base64.stringify(headersHmacSha1);
signatureEffort.success({signature: headersHmacSha1Base64});
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
contentType: "application/json; charset=utf-8",
endpointStore: {
get: function() {
return options.signatureSpec.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.signatureSpec.customHeaders,
log: options.log,
onComplete: handleSignatureReceived,
cors: options.cors
}));
qq.extend(this, {
/**
* On success, an object containing the parsed JSON response will be passed into the success handler if the
* request succeeds. Otherwise an error message will be passed into the failure method.
*
* @param id File ID.
* @param toBeSigned an Object that holds the item(s) to be signed
* @returns {qq.Promise} A promise that is fulfilled when the response has been received.
*/
getSignature: function(id, toBeSigned) {
var params = toBeSigned,
signatureEffort = new qq.Promise();
if (credentialsProvider.get().secretKey && window.CryptoJS) {
if (credentialsProvider.get().expiration.getTime() > Date.now()) {
determineSignatureClientSide(toBeSigned, signatureEffort);
}
// If credentials are expired, ask for new ones before attempting to sign request
else {
credentialsProvider.onExpired().then(function() {
determineSignatureClientSide(toBeSigned,
signatureEffort,
credentialsProvider.get().accessKey,
credentialsProvider.get().sessionToken);
}, function(errorMsg) {
options.log("Attempt to update expired credentials apparently failed! Unable to sign request. ", "error");
signatureEffort.failure("Unable to sign request - expired credentials.");
});
}
}
else {
options.log("Submitting S3 signature request for " + id);
if (params.signatureConstructor) {
params = {headers: params.signatureConstructor.getToSign().stringToSign};
}
requester.initTransport(id)
.withParams(params)
.send();
pendingSignatures[id] = {
promise: signatureEffort
};
}
return signatureEffort;
},
constructStringToSign: function(type, bucket, key) {
var headers = {},
uploadId, contentType, partNum, toSignAndEndOfUrl;
return {
withHeaders: function(theHeaders) {
headers = theHeaders;
return this;
},
withUploadId: function(theUploadId) {
uploadId = theUploadId;
return this;
},
withContentType: function(theContentType) {
contentType = theContentType;
return this;
},
withPartNum: function(thePartNum) {
partNum = thePartNum;
return this;
},
getToSign: function() {
var sessionToken = credentialsProvider.get().sessionToken;
headers["x-amz-date"] = new Date().toUTCString();
if (sessionToken) {
headers[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
toSignAndEndOfUrl = getToSignAndEndOfUrl(type, bucket, key, contentType, headers, uploadId, partNum);
return {
headers: (function() {
if (contentType) {
headers["Content-Type"] = contentType;
}
return headers;
}()),
endOfUrl: toSignAndEndOfUrl.endOfUrl,
stringToSign: toSignAndEndOfUrl.toSign
};
},
getHeaders: function() {
return qq.extend({}, headers);
},
getEndOfUrl: function() {
return toSignAndEndOfUrl && toSignAndEndOfUrl.endOfUrl;
}
};
}
});
};
qq.s3.RequestSigner.prototype.REQUEST_TYPE = {
MULTIPART_INITIATE: "multipart_initiate",
MULTIPART_COMPLETE: "multipart_complete",
MULTIPART_ABORT: "multipart_abort",
MULTIPART_UPLOAD: "multipart_upload"
};
/*globals qq, XMLHttpRequest*/
/**
* Sends a POST request to the server to notify it of a successful upload to an endpoint. The server is expected to indicate success
* or failure via the response status. Specific information about the failure can be passed from the server via an `error`
* property (by default) in an "application/json" response.
*
* @param o Options associated with all requests.
* @constructor
*/
qq.UploadSuccessAjaxRequester = function(o) {
"use strict";
var requester,
pendingRequests = [],
options = {
method: "POST",
endpoint: null,
maxConnections: 3,
customHeaders: {},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
};
qq.extend(options, o);
function handleSuccessResponse(id, xhrOrXdr, isError) {
var promise = pendingRequests[id],
responseJson = xhrOrXdr.responseText,
successIndicator = {success: true},
failureIndicator = {success: false},
parsedResponse;
delete pendingRequests[id];
options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson));
try {
parsedResponse = qq.parseJson(responseJson);
// If this is a cross-origin request, the server may return a 200 response w/ error or success properties
// in order to ensure any specific error message is picked up by Fine Uploader for all browsers,
// since XDomainRequest (used in IE9 and IE8) doesn't give you access to the
// response body for an "error" response.
if (isError || (parsedResponse && (parsedResponse.error || parsedResponse.success === false))) {
options.log("Upload success request was rejected by the server.", "error");
promise.failure(qq.extend(parsedResponse, failureIndicator));
}
else {
options.log("Upload success was acknowledged by the server.");
promise.success(qq.extend(parsedResponse, successIndicator));
}
}
catch (error) {
// This will be executed if a JSON response is not present. This is not mandatory, so account for this properly.
if (isError) {
options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error");
promise.failure(failureIndicator);
}
else {
options.log("Upload success was acknowledged by the server.");
promise.success(successIndicator);
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
endpointStore: {
get: function() {
return options.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.customHeaders,
log: options.log,
onComplete: handleSuccessResponse,
cors: options.cors
}));
qq.extend(this, {
/**
* Sends a request to the server, notifying it that a recently submitted file was successfully sent.
*
* @param id ID of the associated file
* @param spec `Object` with the properties that correspond to important values that we want to
* send to the server with this request.
* @returns {qq.Promise} A promise to be fulfilled when the response has been received and parsed. The parsed
* payload of the response will be passed into the `failure` or `success` promise method.
*/
sendSuccessRequest: function(id, spec) {
var promise = new qq.Promise();
options.log("Submitting upload success request/notification for " + id);
requester.initTransport(id)
.withParams(spec)
.send();
pendingRequests[id] = promise;
return promise;
}
});
};
/*globals qq*/
/**
* Ajax requester used to send an ["Initiate Multipart Upload"](http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadInitiate.html)
* request to S3 via the REST API.
*
* @param o Options from the caller - will override the defaults.
* @constructor
*/
qq.s3.InitiateMultipartAjaxRequester = function(o) {
"use strict";
var requester,
pendingInitiateRequests = {},
options = {
filenameParam: "qqfilename",
method: "POST",
endpointStore: null,
paramsStore: null,
signatureSpec: null,
aclStore: null,
reducedRedundancy: false,
serverSideEncryption: false,
maxConnections: 3,
getContentType: function(id) {},
getBucket: function(id) {},
getKey: function(id) {},
getName: function(id) {},
log: function(str, level) {}
},
getSignatureAjaxRequester;
qq.extend(options, o);
getSignatureAjaxRequester = new qq.s3.RequestSigner({
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
/**
* Determine all headers for the "Initiate MPU" request, including the "Authorization" header, which must be determined
* by the local server. This is a promissory function. If the server responds with a signature, the headers
* (including the Authorization header) will be passed into the success method of the promise. Otherwise, the failure
* method on the promise will be called.
*
* @param id Associated file ID
* @returns {qq.Promise}
*/
function getHeaders(id) {
var bucket = options.getBucket(id),
headers = {},
promise = new qq.Promise(),
key = options.getKey(id),
signatureConstructor;
headers["x-amz-acl"] = options.aclStore.get(id);
if (options.reducedRedundancy) {
headers[qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (options.serverSideEncryption) {
headers[qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
headers[qq.s3.util.AWS_PARAM_PREFIX + options.filenameParam] = encodeURIComponent(options.getName(id));
qq.each(options.paramsStore.get(id), function(name, val) {
headers[qq.s3.util.AWS_PARAM_PREFIX + name] = encodeURIComponent(val);
});
signatureConstructor = getSignatureAjaxRequester.constructStringToSign
(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_INITIATE, bucket, key)
.withContentType(options.getContentType(id))
.withHeaders(headers);
// Ask the local server to sign the request. Use this signature to form the Authorization header.
getSignatureAjaxRequester.getSignature(id, {signatureConstructor: signatureConstructor}).then(function(response) {
headers = signatureConstructor.getHeaders();
headers.Authorization = "AWS " + options.signatureSpec.credentialsProvider.get().accessKey + ":" + response.signature;
promise.success(headers, signatureConstructor.getEndOfUrl());
}, promise.failure);
return promise;
}
/**
* Called by the base ajax requester when the response has been received. We definitively determine here if the
* "Initiate MPU" request has been a success or not.
*
* @param id ID associated with the file.
* @param xhr `XMLHttpRequest` object containing the response, among other things.
* @param isError A boolean indicating success or failure according to the base ajax requester (primarily based on status code).
*/
function handleInitiateRequestComplete(id, xhr, isError) {
var promise = pendingInitiateRequests[id],
domParser = new DOMParser(),
responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"),
uploadIdElements, messageElements, uploadId, errorMessage, status;
delete pendingInitiateRequests[id];
// The base ajax requester may declare the request to be a failure based on status code.
if (isError) {
status = xhr.status;
messageElements = responseDoc.getElementsByTagName("Message");
if (messageElements.length > 0) {
errorMessage = messageElements[0].textContent;
}
}
// If the base ajax requester has not declared this a failure, make sure we can retrieve the uploadId from the response.
else {
uploadIdElements = responseDoc.getElementsByTagName("UploadId");
if (uploadIdElements.length > 0) {
uploadId = uploadIdElements[0].textContent;
}
else {
errorMessage = "Upload ID missing from request";
}
}
// Either fail the promise (passing a descriptive error message) or declare it a success (passing the upload ID)
if (uploadId === undefined) {
if (errorMessage) {
options.log(qq.format("Specific problem detected initiating multipart upload request for {}: '{}'.", id, errorMessage), "error");
}
else {
options.log(qq.format("Unexplained error with initiate multipart upload request for {}. Status code {}.", id, status), "error");
}
promise.failure("Problem initiating upload request.", xhr);
}
else {
options.log(qq.format("Initiate multipart upload request successful for {}. Upload ID is {}", id, uploadId));
promise.success(uploadId, xhr);
}
}
requester = qq.extend(this, new qq.AjaxRequester({
method: options.method,
contentType: null,
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false, //These headers are not necessary & would break some installations if added
log: options.log,
onComplete: handleInitiateRequestComplete,
successfulResponseCodes: {
POST: [200]
}
}));
qq.extend(this, {
/**
* Sends the "Initiate MPU" request to AWS via the REST API. First, though, we must get a signature from the
* local server for the request. If all is successful, the uploadId from AWS will be passed into the promise's
* success handler. Otherwise, an error message will ultimately be passed into the failure method.
*
* @param id The ID associated with the file
* @returns {qq.Promise}
*/
send: function(id) {
var promise = new qq.Promise();
getHeaders(id).then(function(headers, endOfUrl) {
options.log("Submitting S3 initiate multipart upload request for " + id);
pendingInitiateRequests[id] = promise;
requester.initTransport(id)
.withPath(endOfUrl)
.withHeaders(headers)
.send();
}, promise.failure);
return promise;
}
});
};
/*globals qq*/
/**
* Ajax requester used to send an ["Complete Multipart Upload"](http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html)
* request to S3 via the REST API.
*
* @param o Options passed by the creator, to overwrite any default option values.
* @constructor
*/
qq.s3.CompleteMultipartAjaxRequester = function(o) {
"use strict";
var requester,
pendingCompleteRequests = {},
options = {
method: "POST",
contentType: "text/xml",
endpointStore: null,
signatureSpec: null,
maxConnections: 3,
getBucket: function(id) {},
getKey: function(id) {},
log: function(str, level) {}
},
getSignatureAjaxRequester;
qq.extend(options, o);
// Transport for requesting signatures (for the "Complete" requests) from the local server
getSignatureAjaxRequester = new qq.s3.RequestSigner({
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
/**
* Attach all required headers (including Authorization) to the "Complete" request. This is a promissory function
* that will fulfill the associated promise once all headers have been attached or when an error has occurred that
* prevents headers from being attached.
*
* @param id Associated file ID
* @param uploadId ID of the associated upload, according to AWS
* @returns {qq.Promise}
*/
function getHeaders(id, uploadId) {
var headers = {},
promise = new qq.Promise(),
bucket = options.getBucket(id),
signatureConstructor = getSignatureAjaxRequester.constructStringToSign
(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_COMPLETE, bucket, options.getKey(id))
.withUploadId(uploadId)
.withContentType("application/xml; charset=UTF-8");
// Ask the local server to sign the request. Use this signature to form the Authorization header.
getSignatureAjaxRequester.getSignature(id, {signatureConstructor: signatureConstructor}).then(function(response) {
headers = signatureConstructor.getHeaders();
headers.Authorization = "AWS " + options.signatureSpec.credentialsProvider.get().accessKey + ":" + response.signature;
promise.success(headers, signatureConstructor.getEndOfUrl());
}, promise.failure);
return promise;
}
/**
* Called by the base ajax requester when the response has been received. We definitively determine here if the
* "Complete MPU" request has been a success or not.
*
* @param id ID associated with the file.
* @param xhr `XMLHttpRequest` object containing the response, among other things.
* @param isError A boolean indicating success or failure according to the base ajax requester (primarily based on status code).
*/
function handleCompleteRequestComplete(id, xhr, isError) {
var promise = pendingCompleteRequests[id],
domParser = new DOMParser(),
bucket = options.getBucket(id),
key = options.getKey(id),
responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"),
bucketEls = responseDoc.getElementsByTagName("Bucket"),
keyEls = responseDoc.getElementsByTagName("Key");
delete pendingCompleteRequests[id];
options.log(qq.format("Complete response status {}, body = {}", xhr.status, xhr.responseText));
// If the base requester has determine this a failure, give up.
if (isError) {
options.log(qq.format("Complete Multipart Upload request for {} failed with status {}.", id, xhr.status), "error");
}
else {
// Make sure the correct bucket and key has been specified in the XML response from AWS.
if (bucketEls.length && keyEls.length) {
if (bucketEls[0].textContent !== bucket) {
isError = true;
options.log(qq.format("Wrong bucket in response to Complete Multipart Upload request for {}.", id), "error");
}
// TODO Compare key name from response w/ expected key name if AWS ever fixes the encoding of key names in this response.
}
else {
isError = true;
options.log(qq.format("Missing bucket and/or key in response to Complete Multipart Upload request for {}.", id), "error");
}
}
if (isError) {
promise.failure("Problem combining the file parts!", xhr);
}
else {
promise.success({}, xhr);
}
}
/**
* @param etagEntries Array of objects containing `etag` values and their associated `part` numbers.
* @returns {string} XML string containing the body to send with the "Complete" request
*/
function getCompleteRequestBody(etagEntries) {
var doc = document.implementation.createDocument(null, "CompleteMultipartUpload", null);
// The entries MUST be sorted by part number, per the AWS API spec.
etagEntries.sort(function(a, b) {
return a.part - b.part;
});
// Construct an XML document for each pair of etag/part values that correspond to part uploads.
qq.each(etagEntries, function(idx, etagEntry) {
var part = etagEntry.part,
etag = etagEntry.etag,
partEl = doc.createElement("Part"),
partNumEl = doc.createElement("PartNumber"),
partNumTextEl = doc.createTextNode(part),
etagTextEl = doc.createTextNode(etag),
etagEl = doc.createElement("ETag");
etagEl.appendChild(etagTextEl);
partNumEl.appendChild(partNumTextEl);
partEl.appendChild(partNumEl);
partEl.appendChild(etagEl);
qq(doc).children()[0].appendChild(partEl);
});
// Turn the resulting XML document into a string fit for transport.
return new XMLSerializer().serializeToString(doc);
}
requester = qq.extend(this, new qq.AjaxRequester({
method: options.method,
contentType: "application/xml; charset=UTF-8",
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false, //These headers are not necessary & would break some installations if added
log: options.log,
onComplete: handleCompleteRequestComplete,
successfulResponseCodes: {
POST: [200]
}
}));
qq.extend(this, {
/**
* Sends the "Complete" request and fulfills the returned promise when the success of this request is known.
*
* @param id ID associated with the file.
* @param uploadId AWS uploadId for this file
* @param etagEntries Array of objects containing `etag` values and their associated `part` numbers.
* @returns {qq.Promise}
*/
send: function(id, uploadId, etagEntries) {
var promise = new qq.Promise();
getHeaders(id, uploadId).then(function(headers, endOfUrl) {
var body = getCompleteRequestBody(etagEntries);
options.log("Submitting S3 complete multipart upload request for " + id);
pendingCompleteRequests[id] = promise;
delete headers["Content-Type"];
requester.initTransport(id)
.withPath(endOfUrl)
.withHeaders(headers)
.withPayload(body)
.send();
}, promise.failure);
return promise;
}
});
};
/*globals qq */
/**
* Ajax requester used to send an ["Abort Multipart Upload"](http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html)
* request to S3 via the REST API.
* @param o
* @constructor
*/
qq.s3.AbortMultipartAjaxRequester = function(o) {
"use strict";
var requester,
options = {
method: "DELETE",
endpointStore: null,
signatureSpec: null,
maxConnections: 3,
getBucket: function(id) {},
getKey: function(id) {},
log: function(str, level) {}
},
getSignatureAjaxRequester;
qq.extend(options, o);
// Transport for requesting signatures (for the "Complete" requests) from the local server
getSignatureAjaxRequester = new qq.s3.RequestSigner({
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
/**
* Attach all required headers (including Authorization) to the "Abort" request. This is a promissory function
* that will fulfill the associated promise once all headers have been attached or when an error has occurred that
* prevents headers from being attached.
*
* @param id Associated file ID
* @param uploadId ID of the associated upload, according to AWS
* @returns {qq.Promise}
*/
function getHeaders(id, uploadId) {
var headers = {},
promise = new qq.Promise(),
endpoint = options.endpointStore.get(id),
bucket = options.getBucket(id),
signatureConstructor = getSignatureAjaxRequester.constructStringToSign
(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_ABORT, bucket, options.getKey(id))
.withUploadId(uploadId);
// Ask the local server to sign the request. Use this signature to form the Authorization header.
getSignatureAjaxRequester.getSignature(id, {signatureConstructor: signatureConstructor}).then(function(response) {
headers = signatureConstructor.getHeaders();
headers.Authorization = "AWS " + options.signatureSpec.credentialsProvider.get().accessKey + ":" + response.signature;
promise.success(headers, signatureConstructor.getEndOfUrl());
}, promise.failure);
return promise;
}
/**
* Called by the base ajax requester when the response has been received. We definitively determine here if the
* "Abort MPU" request has been a success or not.
*
* @param id ID associated with the file.
* @param xhr `XMLHttpRequest` object containing the response, among other things.
* @param isError A boolean indicating success or failure according to the base ajax requester (primarily based on status code).
*/
function handleAbortRequestComplete(id, xhr, isError) {
var domParser = new DOMParser(),
responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"),
errorEls = responseDoc.getElementsByTagName("Error"),
awsErrorMsg;
options.log(qq.format("Abort response status {}, body = {}", xhr.status, xhr.responseText));
// If the base requester has determine this a failure, give up.
if (isError) {
options.log(qq.format("Abort Multipart Upload request for {} failed with status {}.", id, xhr.status), "error");
}
else {
// Make sure the correct bucket and key has been specified in the XML response from AWS.
if (errorEls.length) {
isError = true;
awsErrorMsg = responseDoc.getElementsByTagName("Message")[0].textContent;
options.log(qq.format("Failed to Abort Multipart Upload request for {}. Error: {}", id, awsErrorMsg), "error");
}
else {
options.log(qq.format("Abort MPU request succeeded for file ID {}.", id));
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: ["DELETE"],
method: options.method,
contentType: null,
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false, //These headers are not necessary & would break some installations if added
log: options.log,
onComplete: handleAbortRequestComplete,
successfulResponseCodes: {
DELETE: [204]
}
}));
qq.extend(this, {
/**
* Sends the "Abort" request.
*
* @param id ID associated with the file.
* @param uploadId AWS uploadId for this file
*/
send: function(id, uploadId) {
getHeaders(id, uploadId).then(function(headers, endOfUrl) {
options.log("Submitting S3 Abort multipart upload request for " + id);
requester.initTransport(id)
.withPath(endOfUrl)
.withHeaders(headers)
.send();
});
}
});
};
/*globals qq */
/**
* Upload handler used by the upload to S3 module that depends on File API support, and, therefore, makes use of
* `XMLHttpRequest` level 2 to upload `File`s and `Blob`s directly to S3 buckets via the associated AWS API.
*
* If chunking is supported and enabled, the S3 Multipart Upload REST API is utilized.
*
* @param spec Options passed from the base handler
* @param proxy Callbacks & methods used to query for or push out data/changes
*/
qq.s3.XhrUploadHandler = function(spec, proxy) {
"use strict";
var getName = proxy.getName,
log = proxy.log,
expectedStatus = 200,
onGetBucket = spec.getBucket,
onGetKeyName = spec.getKeyName,
filenameParam = spec.filenameParam,
paramsStore = spec.paramsStore,
endpointStore = spec.endpointStore,
aclStore = spec.aclStore,
reducedRedundancy = spec.objectProperties.reducedRedundancy,
serverSideEncryption = spec.objectProperties.serverSideEncryption,
validation = spec.validation,
signature = spec.signature,
handler = this,
credentialsProvider = spec.signature.credentialsProvider,
chunked = {
// Sends a "Complete Multipart Upload" request and then signals completion of the upload
// when the response to this request has been parsed.
combine: function(id) {
var uploadId = handler._getPersistableData(id).uploadId,
etagMap = handler._getPersistableData(id).etags,
result = new qq.Promise();
requesters.completeMultipart.send(id, uploadId, etagMap).then(
result.success,
function failure(reason, xhr) {
result.failure(upload.done(id, xhr).response, xhr);
}
);
return result;
},
// The last step in handling a chunked upload. This is called after each chunk has been sent.
// The request may be successful, or not. If it was successful, we must extract the "ETag" element
// in the XML response and store that along with the associated part number.
// We need these items to "Complete" the multipart upload after all chunks have been successfully sent.
done: function(id, xhr, chunkIdx) {
var response = upload.response.parse(id, xhr),
etag;
if (response.success) {
etag = xhr.getResponseHeader("ETag");
if (!handler._getPersistableData(id).etags) {
handler._getPersistableData(id).etags = [];
}
handler._getPersistableData(id).etags.push({part: chunkIdx + 1, etag: etag});
}
},
/**
* Determines headers that must be attached to the chunked (Multipart Upload) request. One of these headers is an
* Authorization value, which must be determined by asking the local server to sign the request first. So, this
* function returns a promise. Once all headers are determined, the `success` method of the promise is called with
* the headers object. If there was some problem determining the headers, we delegate to the caller's `failure`
* callback.
*
* @param id File ID
* @param chunkIdx Index of the chunk to PUT
* @returns {qq.Promise}
*/
initHeaders: function(id, chunkIdx) {
var headers = {},
endpoint = spec.endpointStore.get(id),
bucket = upload.bucket.getName(id),
key = upload.key.urlSafe(id),
promise = new qq.Promise(),
signatureConstructor = requesters.restSignature.constructStringToSign
(requesters.restSignature.REQUEST_TYPE.MULTIPART_UPLOAD, bucket, key)
.withPartNum(chunkIdx + 1)
.withUploadId(handler._getPersistableData(id).uploadId);
// Ask the local server to sign the request. Use this signature to form the Authorization header.
requesters.restSignature.getSignature(id + "." + chunkIdx, {signatureConstructor: signatureConstructor}).then(function(response) {
headers = signatureConstructor.getHeaders();
headers.Authorization = "AWS " + credentialsProvider.get().accessKey + ":" + response.signature;
promise.success(headers, signatureConstructor.getEndOfUrl());
}, promise.failure);
return promise;
},
put: function(id, chunkIdx) {
var xhr = handler._createXhr(id, chunkIdx),
chunkData = handler._getChunkData(id, chunkIdx),
domain = spec.endpointStore.get(id),
promise = new qq.Promise();
// Add appropriate headers to the multipart upload request.
// Once these have been determined (asynchronously) attach the headers and send the chunk.
chunked.initHeaders(id, chunkIdx).then(function(headers, endOfUrl) {
var url = domain + "/" + endOfUrl;
handler._registerProgressHandler(id, chunkIdx, chunkData.size);
upload.track(id, xhr, chunkIdx).then(promise.success, promise.failure);
xhr.open("PUT", url, true);
qq.each(headers, function(name, val) {
xhr.setRequestHeader(name, val);
});
xhr.send(chunkData.blob);
}, function() {
promise.failure({error: "Problem signing the chunk!"}, xhr);
});
return promise;
},
send: function(id, chunkIdx) {
var promise = new qq.Promise();
chunked.setup(id).then(
// The "Initiate" request succeeded. We are ready to send the first chunk.
function() {
chunked.put(id, chunkIdx).then(promise.success, promise.failure);
},
// We were unable to initiate the chunked upload process.
function(errorMessage, xhr) {
promise.failure({error: errorMessage}, xhr);
}
);
return promise;
},
/**
* Sends an "Initiate Multipart Upload" request to S3 via the REST API, but only if the MPU has not already been
* initiated.
*
* @param id Associated file ID
* @returns {qq.Promise} A promise that is fulfilled when the initiate request has been sent and the response has been parsed.
*/
setup: function(id) {
var promise = new qq.Promise(),
uploadId = handler._getPersistableData(id).uploadId,
uploadIdPromise = new qq.Promise();
if (!uploadId) {
handler._getPersistableData(id).uploadId = uploadIdPromise;
requesters.initiateMultipart.send(id).then(
function(uploadId) {
handler._getPersistableData(id).uploadId = uploadId;
uploadIdPromise.success(uploadId);
promise.success(uploadId);
},
function(errorMsg) {
handler._getPersistableData(id).uploadId = null;
promise.failure(errorMsg);
uploadIdPromise.failure(errorMsg);
}
);
}
else if (uploadId instanceof qq.Promise) {
uploadId.then(function(uploadId) {
promise.success(uploadId);
});
}
else {
promise.success(uploadId);
}
return promise;
}
},
requesters = {
abortMultipart: new qq.s3.AbortMultipartAjaxRequester({
endpointStore: endpointStore,
signatureSpec: signature,
cors: spec.cors,
log: log,
getBucket: function(id) {
return upload.bucket.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
}
}),
completeMultipart: new qq.s3.CompleteMultipartAjaxRequester({
endpointStore: endpointStore,
signatureSpec: signature,
cors: spec.cors,
log: log,
getBucket: function(id) {
return upload.bucket.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
}
}),
initiateMultipart: new qq.s3.InitiateMultipartAjaxRequester({
filenameParam: filenameParam,
endpointStore: endpointStore,
paramsStore: paramsStore,
signatureSpec: signature,
aclStore: aclStore,
reducedRedundancy: reducedRedundancy,
serverSideEncryption: serverSideEncryption,
cors: spec.cors,
log: log,
getContentType: function(id) {
return handler._getMimeType(id);
},
getBucket: function(id) {
return upload.bucket.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
},
getName: function(id) {
return getName(id);
}
}),
policySignature: new qq.s3.RequestSigner({
expectingPolicy: true,
signatureSpec: signature,
cors: spec.cors,
log: log
}),
restSignature: new qq.s3.RequestSigner({
signatureSpec: signature,
cors: spec.cors,
log: log
})
},
simple = {
/**
* Used for simple (non-chunked) uploads to determine the parameters to send along with the request. Part of this
* process involves asking the local server to sign the request, so this function returns a promise. The promise
* is fulfilled when all parameters are determined, or when we determine that all parameters cannnot be calculated
* due to some error.
*
* @param id File ID
* @returns {qq.Promise}
*/
initParams: function(id) {
/*jshint -W040 */
var customParams = paramsStore.get(id);
customParams[filenameParam] = getName(id);
return qq.s3.util.generateAwsParams({
endpoint: endpointStore.get(id),
params: customParams,
type: handler._getMimeType(id),
bucket: upload.bucket.getName(id),
key: handler.getThirdPartyFileId(id),
accessKey: credentialsProvider.get().accessKey,
sessionToken: credentialsProvider.get().sessionToken,
acl: aclStore.get(id),
expectedStatus: expectedStatus,
minFileSize: validation.minSizeLimit,
maxFileSize: validation.maxSizeLimit,
reducedRedundancy: reducedRedundancy,
serverSideEncryption: serverSideEncryption,
log: log
},
qq.bind(requesters.policySignature.getSignature, this, id));
},
send: function(id) {
var promise = new qq.Promise(),
xhr = handler._createXhr(id),
fileOrBlob = handler.getFile(id);
handler._registerProgressHandler(id);
upload.track(id, xhr).then(promise.success, promise.failure);
// Delegate to a function the sets up the XHR request and notifies us when it is ready to be sent, along w/ the payload.
simple.setup(id, xhr, fileOrBlob).then(function(toSend) {
log("Sending upload request for " + id);
xhr.send(toSend);
}, promise.failure);
return promise;
},
/**
* Starts the upload process by delegating to an async function that determine parameters to be attached to the
* request. If all params can be determined, we are called back with the params and the caller of this function is
* informed by invoking the `success` method on the promise returned by this function, passing the payload of the
* request. If some error occurs here, we delegate to a function that signals a failure for this upload attempt.
*
* Note that this is only used by the simple (non-chunked) upload process.
*
* @param id File ID
* @param xhr XMLHttpRequest to use for the upload
* @param fileOrBlob `File` or `Blob` to send
* @returns {qq.Promise}
*/
setup: function(id, xhr, fileOrBlob) {
var formData = new FormData(),
endpoint = endpointStore.get(id),
url = endpoint,
promise = new qq.Promise();
simple.initParams(id).then(
// Success - all params determined
function(awsParams) {
xhr.open("POST", url, true);
qq.obj2FormData(awsParams, formData);
// AWS requires the file field be named "file".
formData.append("file", fileOrBlob);
promise.success(formData);
},
// Failure - we couldn't determine some params (likely the signature)
function(errorMessage) {
promise.failure({error: errorMessage});
}
);
return promise;
}
},
upload = {
/**
* Note that this is called when an upload has reached a termination point,
* regardless of success/failure. For example, it is called when we have
* encountered an error during the upload or when the file may have uploaded successfully.
*
* @param id file ID
*/
bucket: {
promise: function(id) {
var promise = new qq.Promise(),
cachedBucket = handler._getFileState(id).bucket;
if (cachedBucket) {
promise.success(cachedBucket);
}
else {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
promise.success(bucket);
}, promise.failure);
}
return promise;
},
getName: function(id) {
return handler._getFileState(id).bucket;
}
},
done: function(id, xhr) {
var response = upload.response.parse(id, xhr),
isError = response.success !== true;
if (isError && upload.response.shouldReset(response.code)) {
log("This is an unrecoverable error, we must restart the upload entirely on the next retry attempt.", "error");
response.reset = true;
}
return {
success: !isError,
response: response
};
},
key: {
promise: function(id) {
var promise = new qq.Promise(),
key = handler.getThirdPartyFileId(id);
/* jshint eqnull:true */
if (key == null) {
handler._setThirdPartyFileId(id, promise);
onGetKeyName(id, getName(id)).then(
function(keyName) {
handler._setThirdPartyFileId(id, keyName);
promise.success(keyName);
},
function(errorReason) {
handler._setThirdPartyFileId(id, null);
promise.failure(errorReason);
}
);
}
else if (qq.isGenericPromise(key)) {
key.then(promise.success, promise.failure);
}
else {
promise.success(key);
}
return promise;
},
urlSafe: function(id) {
return encodeURIComponent(handler.getThirdPartyFileId(id));
}
},
response: {
parse: function(id, xhr) {
var response = {},
parsedErrorProps;
try {
log(qq.format("Received response status {} with body: {}", xhr.status, xhr.responseText));
if (xhr.status === expectedStatus) {
response.success = true;
}
else {
parsedErrorProps = upload.response.parseError(xhr.responseText);
if (parsedErrorProps) {
response.error = parsedErrorProps.message;
response.code = parsedErrorProps.code;
}
}
}
catch (error) {
log("Error when attempting to parse xhr response text (" + error.message + ")", "error");
}
return response;
},
/**
* This parses an XML response by extracting the "Message" and "Code" elements that accompany AWS error responses.
*
* @param awsResponseXml XML response from AWS
* @returns {object} Object w/ `code` and `message` properties, or undefined if we couldn't find error info in the XML document.
*/
parseError: function(awsResponseXml) {
var parser = new DOMParser(),
parsedDoc = parser.parseFromString(awsResponseXml, "application/xml"),
errorEls = parsedDoc.getElementsByTagName("Error"),
errorDetails = {},
codeEls, messageEls;
if (errorEls.length) {
codeEls = parsedDoc.getElementsByTagName("Code");
messageEls = parsedDoc.getElementsByTagName("Message");
if (messageEls.length) {
errorDetails.message = messageEls[0].textContent;
}
if (codeEls.length) {
errorDetails.code = codeEls[0].textContent;
}
return errorDetails;
}
},
// Determine if the upload should be restarted on the next retry attempt
// based on the error code returned in the response from AWS.
shouldReset: function(errorCode) {
/*jshint -W014 */
return errorCode === "EntityTooSmall"
|| errorCode === "InvalidPart"
|| errorCode === "InvalidPartOrder"
|| errorCode === "NoSuchUpload";
}
},
start: function(id, optChunkIdx) {
var promise = new qq.Promise();
upload.key.promise(id).then(function() {
upload.bucket.promise(id).then(function() {
/* jshint eqnull:true */
if (optChunkIdx == null) {
simple.send(id).then(promise.success, promise.failure);
}
else {
chunked.send(id, optChunkIdx).then(promise.success, promise.failure);
}
});
},
function(errorReason) {
promise.failure({error: errorReason});
});
return promise;
},
track: function(id, xhr, optChunkIdx) {
var promise = new qq.Promise();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var result;
/* jshint eqnull:true */
if (optChunkIdx == null) {
result = upload.done(id, xhr);
promise[result.success ? "success" : "failure"](result.response, xhr);
}
else {
chunked.done(id, xhr, optChunkIdx);
result = upload.done(id, xhr);
promise[result.success ? "success" : "failure"](result.response, xhr);
}
}
};
return promise;
}
};
qq.extend(this, {
uploadChunk: upload.start,
uploadFile: upload.start
});
qq.extend(this, new qq.XhrUploadHandler({
options: qq.extend({namespace: "s3"}, spec),
proxy: qq.extend({getEndpoint: spec.endpointStore.get}, proxy)
}));
qq.override(this, function(super_) {
return {
expunge: function(id) {
var uploadId = handler._getPersistableData(id) && handler._getPersistableData(id).uploadId,
existedInLocalStorage = handler._maybeDeletePersistedChunkData(id);
if (uploadId !== undefined && existedInLocalStorage) {
requesters.abortMultipart.send(id, uploadId);
}
super_.expunge(id);
},
finalizeChunks: function(id) {
return chunked.combine(id);
},
_getLocalStorageId: function(id) {
var baseStorageId = super_._getLocalStorageId(id),
bucketName = upload.bucket.getName(id);
return baseStorageId + "-" + bucketName;
}
};
});
};
/*globals qq */
/**
* Upload handler used by the upload to S3 module that assumes the current user agent does not have any support for the
* File API, and, therefore, makes use of iframes and forms to submit the files directly to S3 buckets via the associated
* AWS API.
*
* @param options Options passed from the base handler
* @param proxy Callbacks & methods used to query for or push out data/changes
*/
qq.s3.FormUploadHandler = function(options, proxy) {
"use strict";
var handler = this,
onUuidChanged = proxy.onUuidChanged,
getName = proxy.getName,
getUuid = proxy.getUuid,
log = proxy.log,
onGetBucket = options.getBucket,
onGetKeyName = options.getKeyName,
filenameParam = options.filenameParam,
paramsStore = options.paramsStore,
endpointStore = options.endpointStore,
aclStore = options.aclStore,
reducedRedundancy = options.objectProperties.reducedRedundancy,
serverSideEncryption = options.objectProperties.serverSideEncryption,
validation = options.validation,
signature = options.signature,
successRedirectUrl = options.iframeSupport.localBlankPagePath,
credentialsProvider = options.signature.credentialsProvider,
getSignatureAjaxRequester = new qq.s3.RequestSigner({
signatureSpec: signature,
cors: options.cors,
log: log
});
if (successRedirectUrl === undefined) {
throw new Error("successRedirectEndpoint MUST be defined if you intend to use browsers that do not support the File API!");
}
/**
* Attempt to parse the contents of an iframe after receiving a response from the server. If the contents cannot be
* read (perhaps due to a security error) it is safe to assume that the upload was not successful since Amazon should
* have redirected to a known endpoint that should provide a parseable response.
*
* @param id ID of the associated file
* @param iframe target of the form submit
* @returns {boolean} true if the contents can be read, false otherwise
*/
function isValidResponse(id, iframe) {
var response,
endpoint = options.endpointStore.get(id),
bucket = qq.s3.util.getBucket(endpoint),
doc,
innerHtml,
responseData;
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
try {
// iframe.contentWindow.document - for IE<7
doc = iframe.contentDocument || iframe.contentWindow.document;
innerHtml = doc.body.innerHTML;
responseData = qq.s3.util.parseIframeResponse(iframe);
if (responseData.bucket === bucket &&
responseData.key === qq.s3.util.encodeQueryStringParam(handler.getThirdPartyFileId(id))) {
return true;
}
log("Response from AWS included an unexpected bucket or key name.", "error");
}
catch (error) {
log("Error when attempting to parse form upload response (" + error.message + ")", "error");
}
return false;
}
function generateAwsParams(id) {
/*jshint -W040 */
var customParams = paramsStore.get(id);
customParams[filenameParam] = getName(id);
return qq.s3.util.generateAwsParams({
endpoint: endpointStore.get(id),
params: customParams,
bucket: handler._getFileState(id).bucket,
key: handler.getThirdPartyFileId(id),
accessKey: credentialsProvider.get().accessKey,
sessionToken: credentialsProvider.get().sessionToken,
acl: aclStore.get(id),
minFileSize: validation.minSizeLimit,
maxFileSize: validation.maxSizeLimit,
successRedirectUrl: successRedirectUrl,
reducedRedundancy: reducedRedundancy,
serverSideEncryption: serverSideEncryption,
log: log
},
qq.bind(getSignatureAjaxRequester.getSignature, this, id));
}
/**
* Creates form, that will be submitted to iframe
*/
function createForm(id, iframe) {
var promise = new qq.Promise(),
method = "POST",
endpoint = options.endpointStore.get(id),
fileName = getName(id);
generateAwsParams(id).then(function(params) {
var form = handler._initFormForUpload({
method: method,
endpoint: endpoint,
params: params,
paramsInBody: true,
targetName: iframe.name
});
promise.success(form);
}, function(errorMessage) {
promise.failure(errorMessage);
handleFinishedUpload(id, iframe, fileName, {error: errorMessage});
});
return promise;
}
function handleUpload(id) {
var iframe = handler._createIframe(id),
input = handler.getInput(id),
promise = new qq.Promise();
createForm(id, iframe).then(function(form) {
form.appendChild(input);
// Register a callback when the response comes in from S3
handler._attachLoadEvent(iframe, function(response) {
log("iframe loaded");
// If the common response handler has determined success or failure immediately
if (response) {
// If there is something fundamentally wrong with the response (such as iframe content is not accessible)
if (response.success === false) {
log("Amazon likely rejected the upload request", "error");
promise.failure(response);
}
}
// The generic response (iframe onload) handler was not able to make a determination regarding the success of the request
else {
response = {};
response.success = isValidResponse(id, iframe);
// If the more specific response handle detected a problem with the response from S3
if (response.success === false) {
log("A success response was received by Amazon, but it was invalid in some way.", "error");
promise.failure(response);
}
else {
qq.extend(response, qq.s3.util.parseIframeResponse(iframe));
promise.success(response);
}
}
handleFinishedUpload(id, iframe);
});
log("Sending upload request for " + id);
form.submit();
qq(form).remove();
}, promise.failure);
return promise;
}
function handleFinishedUpload(id, iframe) {
handler._detachLoadEvent(id);
iframe && qq(iframe).remove();
}
qq.extend(this, new qq.FormUploadHandler({
options: {
isCors: false,
inputName: "file"
},
proxy: {
onCancel: options.onCancel,
onUuidChanged: onUuidChanged,
getName: getName,
getUuid: getUuid,
log: log
}
}));
qq.extend(this, {
uploadFile: function(id) {
var name = getName(id),
promise = new qq.Promise();
if (handler.getThirdPartyFileId(id)) {
if (handler._getFileState(id).bucket) {
handleUpload(id).then(promise.success, promise.failure);
}
else {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
handleUpload(id).then(promise.success, promise.failure);
});
}
}
else {
// The S3 uploader module will either calculate the key or ask the server for it
// and will call us back once it is known.
onGetKeyName(id, name).then(function(key) {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
handler._setThirdPartyFileId(id, key);
handleUpload(id).then(promise.success, promise.failure);
}, function(errorReason) {
promise.failure({error: errorReason});
});
}, function(errorReason) {
promise.failure({error: errorReason});
});
}
return promise;
}
});
};
/*globals qq */
/**
* This defines FineUploader mode w/ support for uploading to S3, which provides all the basic
* functionality of Fine Uploader as well as code to handle uploads directly to S3.
* This module inherits all logic from FineUploader mode and FineUploaderBasicS3 mode and adds some UI-related logic
* specific to the upload-to-S3 workflow. Some inherited options and API methods have a special meaning
* in the context of the S3 uploader.
*/
(function() {
"use strict";
qq.s3.FineUploader = function(o) {
var options = {
failedUploadTextDisplay: {
mode: "custom"
}
};
// Replace any default options with user defined ones
qq.extend(options, o, true);
// Inherit instance data from FineUploader, which should in turn inherit from s3.FineUploaderBasic.
qq.FineUploader.call(this, options, "s3");
if (!qq.supportedFeatures.ajaxUploading && options.iframeSupport.localBlankPagePath === undefined) {
this._options.element.innerHTML = "<div>You MUST set the <code>localBlankPagePath</code> property " +
"of the <code>iframeSupport</code> option since this browser does not support the File API!</div>";
}
};
// Inherit the API methods from FineUploaderBasicS3
qq.extend(qq.s3.FineUploader.prototype, qq.s3.FineUploaderBasic.prototype);
// Inherit public and private API methods related to UI
qq.extend(qq.s3.FineUploader.prototype, qq.uiPublicApi);
qq.extend(qq.s3.FineUploader.prototype, qq.uiPrivateApi);
}());
/*globals qq*/
qq.PasteSupport = function(o) {
"use strict";
var options, detachPasteHandler;
options = {
targetElement: null,
callbacks: {
log: function(message, level) {},
pasteReceived: function(blob) {}
}
};
function isImage(item) {
return item.type &&
item.type.indexOf("image/") === 0;
}
function registerPasteHandler() {
detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
var clipboardData = event.clipboardData;
if (clipboardData) {
qq.each(clipboardData.items, function(idx, item) {
if (isImage(item)) {
var blob = item.getAsFile();
options.callbacks.pasteReceived(blob);
}
});
}
});
}
function unregisterPasteHandler() {
if (detachPasteHandler) {
detachPasteHandler();
}
}
qq.extend(options, o);
registerPasteHandler();
qq.extend(this, {
reset: function() {
unregisterPasteHandler();
}
});
};
/*globals qq, document, CustomEvent*/
qq.DragAndDrop = function(o) {
"use strict";
var options,
HIDE_ZONES_EVENT_NAME = "qq-hidezones",
HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone",
uploadDropZones = [],
droppedFiles = [],
disposeSupport = new qq.DisposeSupport();
options = {
dropZoneElements: [],
allowMultipleItems: true,
classes: {
dropActive: null
},
callbacks: new qq.DragAndDrop.callbacks()
};
qq.extend(options, o, true);
function uploadDroppedFiles(files, uploadDropZone) {
// We need to convert the `FileList` to an actual `Array` to avoid iteration issues
var filesAsArray = Array.prototype.slice.call(files);
options.callbacks.dropLog("Grabbed " + files.length + " dropped files.");
uploadDropZone.dropDisabled(false);
options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement());
}
function traverseFileTree(entry) {
var parseEntryPromise = new qq.Promise();
if (entry.isFile) {
entry.file(function(file) {
var name = entry.name,
fullPath = entry.fullPath,
indexOfNameInFullPath = fullPath.indexOf(name);
// remove file name from full path string
fullPath = fullPath.substr(0, indexOfNameInFullPath);
// remove leading slash in full path string
if (fullPath.charAt(0) === "/") {
fullPath = fullPath.substr(1);
}
file.qqPath = fullPath;
droppedFiles.push(file);
parseEntryPromise.success();
},
function(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
});
}
else if (entry.isDirectory) {
getFilesInDirectory(entry).then(
function allEntriesRead(entries) {
var entriesLeft = entries.length;
qq.each(entries, function(idx, entry) {
traverseFileTree(entry).done(function() {
entriesLeft -= 1;
if (entriesLeft === 0) {
parseEntryPromise.success();
}
});
});
if (!entries.length) {
parseEntryPromise.success();
}
},
function readFailure(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
}
);
}
return parseEntryPromise;
}
// Promissory. Guaranteed to read all files in the root of the passed directory.
function getFilesInDirectory(entry, reader, accumEntries, existingPromise) {
var promise = existingPromise || new qq.Promise(),
dirReader = reader || entry.createReader();
dirReader.readEntries(
function readSuccess(entries) {
var newEntries = accumEntries ? accumEntries.concat(entries) : entries;
if (entries.length) {
setTimeout(function() { // prevent stack oveflow, however unlikely
getFilesInDirectory(entry, dirReader, newEntries, promise);
}, 0);
}
else {
promise.success(newEntries);
}
},
promise.failure
);
return promise;
}
function handleDataTransfer(dataTransfer, uploadDropZone) {
var pendingFolderPromises = [],
handleDataTransferPromise = new qq.Promise();
options.callbacks.processingDroppedFiles();
uploadDropZone.dropDisabled(true);
if (dataTransfer.files.length > 1 && !options.allowMultipleItems) {
options.callbacks.processingDroppedFilesComplete([]);
options.callbacks.dropError("tooManyFilesError", "");
uploadDropZone.dropDisabled(false);
handleDataTransferPromise.failure();
}
else {
droppedFiles = [];
if (qq.isFolderDropSupported(dataTransfer)) {
qq.each(dataTransfer.items, function(idx, item) {
var entry = item.webkitGetAsEntry();
if (entry) {
//due to a bug in Chrome's File System API impl - #149735
if (entry.isFile) {
droppedFiles.push(item.getAsFile());
}
else {
pendingFolderPromises.push(traverseFileTree(entry).done(function() {
pendingFolderPromises.pop();
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}));
}
}
});
}
else {
droppedFiles = dataTransfer.files;
}
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}
return handleDataTransferPromise;
}
function setupDropzone(dropArea) {
var dropZone = new qq.UploadDropZone({
HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME,
element: dropArea,
onEnter: function(e) {
qq(dropArea).addClass(options.classes.dropActive);
e.stopPropagation();
},
onLeaveNotDescendants: function(e) {
qq(dropArea).removeClass(options.classes.dropActive);
},
onDrop: function(e) {
handleDataTransfer(e.dataTransfer, dropZone).then(
function() {
uploadDroppedFiles(droppedFiles, dropZone);
},
function() {
options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error");
}
);
}
});
disposeSupport.addDisposer(function() {
dropZone.dispose();
});
qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide();
uploadDropZones.push(dropZone);
return dropZone;
}
function isFileDrag(dragEvent) {
var fileDrag;
qq.each(dragEvent.dataTransfer.types, function(key, val) {
if (val === "Files") {
fileDrag = true;
return false;
}
});
return fileDrag;
}
// Attempt to determine when the file has left the document. It is not always possible to detect this
// in all cases, but it is generally possible in all browsers, with a few exceptions.
//
// Exceptions:
// * IE10+ & Safari: We can't detect a file leaving the document if the Explorer window housing the file
// overlays the browser window.
// * IE10+: If the file is dragged out of the window too quickly, IE does not set the expected values of the
// event's X & Y properties.
function leavingDocumentOut(e) {
if (qq.firefox()) {
return !e.relatedTarget;
}
if (qq.safari()) {
return e.x < 0 || e.y < 0;
}
return e.x === 0 && e.y === 0;
}
function setupDragDrop() {
var dropZones = options.dropZoneElements,
maybeHideDropZones = function() {
setTimeout(function() {
qq.each(dropZones, function(idx, dropZone) {
qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide();
qq(dropZone).removeClass(options.classes.dropActive);
});
}, 10);
};
qq.each(dropZones, function(idx, dropZone) {
var uploadDropZone = setupDropzone(dropZone);
// IE <= 9 does not support the File API used for drag+drop uploads
if (dropZones.length && qq.supportedFeatures.fileDrop) {
disposeSupport.attach(document, "dragenter", function(e) {
if (!uploadDropZone.dropDisabled() && isFileDrag(e)) {
qq.each(dropZones, function(idx, dropZone) {
// We can't apply styles to non-HTMLElements, since they lack the `style` property.
// Also, if the drop zone isn't initially hidden, let's not mess with `style.display`.
if (dropZone instanceof HTMLElement &&
qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) {
qq(dropZone).css({display: "block"});
}
});
}
});
}
});
disposeSupport.attach(document, "dragleave", function(e) {
if (leavingDocumentOut(e)) {
maybeHideDropZones();
}
});
// Just in case we were not able to detect when a dragged file has left the document,
// hide all relevant drop zones the next time the mouse enters the document.
// Note that mouse events such as this one are not fired during drag operations.
disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) {
maybeHideDropZones();
});
disposeSupport.attach(document, "drop", function(e) {
e.preventDefault();
maybeHideDropZones();
});
disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones);
}
setupDragDrop();
qq.extend(this, {
setupExtraDropzone: function(element) {
options.dropZoneElements.push(element);
setupDropzone(element);
},
removeDropzone: function(element) {
var i,
dzs = options.dropZoneElements;
for (i in dzs) {
if (dzs[i] === element) {
return dzs.splice(i, 1);
}
}
},
dispose: function() {
disposeSupport.dispose();
qq.each(uploadDropZones, function(idx, dropZone) {
dropZone.dispose();
});
}
});
};
qq.DragAndDrop.callbacks = function() {
"use strict";
return {
processingDroppedFiles: function() {},
processingDroppedFilesComplete: function(files, targetEl) {},
dropError: function(code, errorSpecifics) {
qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error");
},
dropLog: function(message, level) {
qq.log(message, level);
}
};
};
qq.UploadDropZone = function(o) {
"use strict";
var disposeSupport = new qq.DisposeSupport(),
options, element, preventDrop, dropOutsideDisabled;
options = {
element: null,
onEnter: function(e) {},
onLeave: function(e) {},
// is not fired when leaving element by hovering descendants
onLeaveNotDescendants: function(e) {},
onDrop: function(e) {}
};
qq.extend(options, o);
element = options.element;
function dragoverShouldBeCanceled() {
return qq.safari() || (qq.firefox() && qq.windows());
}
function disableDropOutside(e) {
// run only once for all instances
if (!dropOutsideDisabled) {
// for these cases we need to catch onDrop to reset dropArea
if (dragoverShouldBeCanceled) {
disposeSupport.attach(document, "dragover", function(e) {
e.preventDefault();
});
} else {
disposeSupport.attach(document, "dragover", function(e) {
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "none";
e.preventDefault();
}
});
}
dropOutsideDisabled = true;
}
}
function isValidFileDrag(e) {
// e.dataTransfer currently causing IE errors
// IE9 does NOT support file API, so drag-and-drop is not possible
if (!qq.supportedFeatures.fileDrop) {
return false;
}
var effectTest, dt = e.dataTransfer,
// do not check dt.types.contains in webkit, because it crashes safari 4
isSafari = qq.safari();
// dt.effectAllowed is none in Safari 5
// dt.types.contains check is for firefox
// dt.effectAllowed crashes IE 11 & 10 when files have been dragged from
// the filesystem
effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none";
return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains("Files")));
}
function isOrSetDropDisabled(isDisabled) {
if (isDisabled !== undefined) {
preventDrop = isDisabled;
}
return preventDrop;
}
function triggerHidezonesEvent() {
var hideZonesEvent;
function triggerUsingOldApi() {
hideZonesEvent = document.createEvent("Event");
hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true);
}
if (window.CustomEvent) {
try {
hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME);
}
catch (err) {
triggerUsingOldApi();
}
}
else {
triggerUsingOldApi();
}
document.dispatchEvent(hideZonesEvent);
}
function attachEvents() {
disposeSupport.attach(element, "dragover", function(e) {
if (!isValidFileDrag(e)) {
return;
}
// dt.effectAllowed crashes IE 11 & 10 when files have been dragged from
// the filesystem
var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed;
if (effect === "move" || effect === "linkMove") {
e.dataTransfer.dropEffect = "move"; // for FF (only move allowed)
} else {
e.dataTransfer.dropEffect = "copy"; // for Chrome
}
e.stopPropagation();
e.preventDefault();
});
disposeSupport.attach(element, "dragenter", function(e) {
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
options.onEnter(e);
}
});
disposeSupport.attach(element, "dragleave", function(e) {
if (!isValidFileDrag(e)) {
return;
}
options.onLeave(e);
var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
// do not fire when moving a mouse over a descendant
if (qq(this).contains(relatedTarget)) {
return;
}
options.onLeaveNotDescendants(e);
});
disposeSupport.attach(element, "drop", function(e) {
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
e.preventDefault();
e.stopPropagation();
options.onDrop(e);
triggerHidezonesEvent();
}
});
}
disableDropOutside();
attachEvents();
qq.extend(this, {
dropDisabled: function(isDisabled) {
return isOrSetDropDisabled(isDisabled);
},
dispose: function() {
disposeSupport.dispose();
},
getElement: function() {
return element;
}
});
};
/*globals qq, XMLHttpRequest*/
qq.DeleteFileAjaxRequester = function(o) {
"use strict";
var requester,
options = {
method: "DELETE",
uuidParamName: "qquuid",
endpointStore: {},
maxConnections: 3,
customHeaders: function(id) {return {};},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {}
};
qq.extend(options, o);
function getMandatedParams() {
if (options.method.toUpperCase() === "POST") {
return {
_method: "DELETE"
};
}
return {};
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: ["POST", "DELETE"],
method: options.method,
endpointStore: options.endpointStore,
paramsStore: options.paramsStore,
mandatedParams: getMandatedParams(),
maxConnections: options.maxConnections,
customHeaders: function(id) {
return options.customHeaders.get(id);
},
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete,
cors: options.cors
}));
qq.extend(this, {
sendDelete: function(id, uuid, additionalMandatedParams) {
var additionalOptions = additionalMandatedParams || {};
options.log("Submitting delete file request for " + id);
if (options.method === "DELETE") {
requester.initTransport(id)
.withPath(uuid)
.withParams(additionalOptions)
.send();
}
else {
additionalOptions[options.uuidParamName] = uuid;
requester.initTransport(id)
.withParams(additionalOptions)
.send();
}
}
});
};
/*global qq, define */
/*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */
/**
* Mega pixel image rendering library for iOS6+
*
* Fixes iOS6+'s image file rendering issue for large size image (over mega-pixel),
* which causes unexpected subsampling when drawing it in canvas.
* By using this library, you can safely render the image with proper stretching.
*
* Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>
* Released under the MIT license
*
* Heavily modified by Widen for Fine Uploader
*/
(function() {
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be subsampled in rendering.
*/
function detectSubsampling(img) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas = document.createElement("canvas"),
ctx;
if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
canvas.width = canvas.height = 1;
ctx = canvas.getContext("2d");
ctx.drawImage(img, -iw + 1, 0);
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering edge pixel or not.
// if alpha value is 0 image is not covering, hence subsampled.
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into canvas for some images.
*/
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement("canvas"),
sy = 0,
ey = ih,
py = ih,
ctx, data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
while (py > sy) {
alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
/**
* Rendering image element (with resizing) and get its data URL
*/
function renderImageToDataURL(img, options, doSquash) {
var canvas = document.createElement("canvas"),
mime = options.mime || "image/jpeg";
renderImageToCanvas(img, canvas, options, doSquash);
return canvas.toDataURL(mime, options.quality || 0.8);
}
function maybeCalculateDownsampledDimensions(spec) {
var maxPixels = 5241000; //iOS specific value
if (!qq.ios()) {
throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
}
if (spec.origHeight * spec.origWidth > maxPixels) {
return {
newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
}
}
}
/**
* Rendering image element (with resizing) into the canvas element
*/
function renderImageToCanvas(img, canvas, options, doSquash) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
width = options.width,
height = options.height,
ctx = canvas.getContext("2d"),
modifiedDimensions;
ctx.save();
if (!qq.supportedFeatures.unlimitedScaledImageSize) {
modifiedDimensions = maybeCalculateDownsampledDimensions({
origWidth: width,
origHeight: height
});
if (modifiedDimensions) {
qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h",
width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight),
"warn");
width = modifiedDimensions.newWidth;
height = modifiedDimensions.newHeight;
}
}
transformCoordinate(canvas, width, height, options.orientation);
// Fine Uploader specific: Save some CPU cycles if not using iOS
// Assumption: This logic is only needed to overcome iOS image sampling issues
if (qq.ios()) {
(function() {
if (detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024, // size of tiling canvas
tmpCanvas = document.createElement("canvas"),
vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1,
dw = Math.ceil(d * width / iw),
dh = Math.ceil(d * height / ih / vertSquashRatio),
sy = 0,
dy = 0,
tmpCtx, sx, dx;
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext("2d");
while (sy < ih) {
sx = 0,
dx = 0;
while (sx < iw) {
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
}())
}
else {
ctx.drawImage(img, 0, 0, width, height);
}
canvas.qqImageRendered && canvas.qqImageRendered();
}
/**
* Transform canvas coordination according to specified frame size and orientation
* Orientation value is from EXIF tag
*/
function transformCoordinate(canvas, width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
default:
canvas.width = width;
canvas.height = height;
}
var ctx = canvas.getContext("2d");
switch (orientation) {
case 2:
// horizontal flip
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180 rotate left
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
// 90 rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-width, 0);
break;
default:
break;
}
}
/**
* MegaPixImage class
*/
function MegaPixImage(srcImage, errorCallback) {
var self = this;
if (window.Blob && srcImage instanceof Blob) {
(function() {
var img = new Image(),
URL = window.URL && window.URL.createObjectURL ? window.URL :
window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
img.src = URL.createObjectURL(srcImage);
self.blob = srcImage;
srcImage = img;
}());
}
if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
srcImage.onload = function() {
var listeners = self.imageLoadListeners;
if (listeners) {
self.imageLoadListeners = null;
// IE11 doesn't reliably report actual image dimensions immediately after onload for small files,
// so let's push this to the end of the UI thread queue.
setTimeout(function() {
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i]();
}
}, 0);
}
};
srcImage.onerror = errorCallback;
this.imageLoadListeners = [];
}
this.srcImage = srcImage;
}
/**
* Rendering megapix image into specified target element
*/
MegaPixImage.prototype.render = function(target, options) {
options = options || {};
var self = this,
imgWidth = this.srcImage.naturalWidth,
imgHeight = this.srcImage.naturalHeight,
width = options.width,
height = options.height,
maxWidth = options.maxWidth,
maxHeight = options.maxHeight,
doSquash = !this.blob || this.blob.type === "image/jpeg",
tagName = target.tagName.toLowerCase(),
opt;
if (this.imageLoadListeners) {
this.imageLoadListeners.push(function() { self.render(target, options) });
return;
}
if (width && !height) {
height = (imgHeight * width / imgWidth) << 0;
} else if (height && !width) {
width = (imgWidth * height / imgHeight) << 0;
} else {
width = imgWidth;
height = imgHeight;
}
if (maxWidth && width > maxWidth) {
width = maxWidth;
height = (imgHeight * width / imgWidth) << 0;
}
if (maxHeight && height > maxHeight) {
height = maxHeight;
width = (imgWidth * height / imgHeight) << 0;
}
opt = { width: width, height: height },
qq.each(options, function(optionsKey, optionsValue) {
opt[optionsKey] = optionsValue;
});
if (tagName === "img") {
(function() {
var oldTargetSrc = target.src;
target.src = renderImageToDataURL(self.srcImage, opt, doSquash);
oldTargetSrc === target.src && target.onload();
}())
} else if (tagName === "canvas") {
renderImageToCanvas(this.srcImage, target, opt, doSquash);
}
if (typeof this.onrender === "function") {
this.onrender(target);
}
};
qq.MegaPixImage = MegaPixImage;
})();
/*globals qq */
/**
* Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>.
*
* @constructor
*/
qq.ImageGenerator = function(log) {
"use strict";
function isImg(el) {
return el.tagName.toLowerCase() === "img";
}
function isCanvas(el) {
return el.tagName.toLowerCase() === "canvas";
}
function isImgCorsSupported() {
return new Image().crossOrigin !== undefined;
}
function isCanvasSupported() {
var canvas = document.createElement("canvas");
return canvas.getContext && canvas.getContext("2d");
}
// This is only meant to determine the MIME type of a renderable image file.
// It is used to ensure images drawn from a URL that have transparent backgrounds
// are rendered correctly, among other things.
function determineMimeOfFileName(nameWithPath) {
/*jshint -W015 */
var pathSegments = nameWithPath.split("/"),
name = pathSegments[pathSegments.length - 1],
extension = qq.getExtension(name);
extension = extension && extension.toLowerCase();
switch (extension) {
case "jpeg":
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "bmp":
return "image/bmp";
case "gif":
return "image/gif";
case "tiff":
case "tif":
return "image/tiff";
}
}
// This will likely not work correctly in IE8 and older.
// It's only used as part of a formula to determine
// if a canvas can be used to scale a server-hosted thumbnail.
// If canvas isn't supported by the UA (IE8 and older)
// this method should not even be called.
function isCrossOrigin(url) {
var targetAnchor = document.createElement("a"),
targetProtocol, targetHostname, targetPort;
targetAnchor.href = url;
targetProtocol = targetAnchor.protocol;
targetPort = targetAnchor.port;
targetHostname = targetAnchor.hostname;
if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
return true;
}
if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
return true;
}
// IE doesn't take ports into consideration when determining if two endpoints are same origin.
if (targetPort !== window.location.port && !qq.ie()) {
return true;
}
return false;
}
function registerImgLoadListeners(img, promise) {
img.onload = function() {
img.onload = null;
img.onerror = null;
promise.success(img);
};
img.onerror = function() {
img.onload = null;
img.onerror = null;
log("Problem drawing thumbnail!", "error");
promise.failure(img, "Problem drawing thumbnail!");
};
}
function registerCanvasDrawImageListener(canvas, promise) {
// The image is drawn on the canvas by a third-party library,
// and we want to know when this is completed. Since the library
// may invoke drawImage many times in a loop, we need to be called
// back when the image is fully rendered. So, we are expecting the
// code that draws this image to follow a convention that involves a
// function attached to the canvas instance be invoked when it is done.
canvas.qqImageRendered = function() {
promise.success(canvas);
};
}
// Fulfills a `qq.Promise` when an image has been drawn onto the target,
// whether that is a <canvas> or an <img>. The attempt is considered a
// failure if the target is not an <img> or a <canvas>, or if the drawing
// attempt was not successful.
function registerThumbnailRenderedListener(imgOrCanvas, promise) {
var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
if (isImg(imgOrCanvas)) {
registerImgLoadListeners(imgOrCanvas, promise);
}
else if (isCanvas(imgOrCanvas)) {
registerCanvasDrawImageListener(imgOrCanvas, promise);
}
else {
promise.failure(imgOrCanvas);
log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
}
return registered;
}
// Draw a preview iff the current UA can natively display it.
// Also rotate the image if necessary.
function draw(fileOrBlob, container, options) {
var drawPreview = new qq.Promise(),
identifier = new qq.Identify(fileOrBlob, log),
maxSize = options.maxSize,
// jshint eqnull:true
orient = options.orient == null ? true : options.orient,
megapixErrorHandler = function() {
container.onerror = null;
container.onload = null;
log("Could not render preview, file may be too large!", "error");
drawPreview.failure(container, "Browser cannot render image!");
};
identifier.isPreviewable().then(
function(mime) {
// If options explicitly specify that Orientation is not desired,
// replace the orient task with a dummy promise that "succeeds" immediately.
var dummyExif = {
parse: function() {
return new qq.Promise().success();
}
},
exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif,
mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
if (registerThumbnailRenderedListener(container, drawPreview)) {
exif.parse().then(
function(exif) {
var orientation = exif && exif.Orientation;
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
orientation: orientation,
mime: mime
});
},
function(failureMsg) {
log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: mime
});
}
);
}
},
function() {
log("Not previewable");
drawPreview.failure(container, "Not previewable");
}
);
return drawPreview;
}
function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize) {
var tempImg = new Image(),
tempImgRender = new qq.Promise();
registerThumbnailRenderedListener(tempImg, tempImgRender);
if (isCrossOrigin(url)) {
tempImg.crossOrigin = "anonymous";
}
tempImg.src = url;
tempImgRender.then(
function rendered() {
registerThumbnailRenderedListener(canvasOrImg, draw);
var mpImg = new qq.MegaPixImage(tempImg);
mpImg.render(canvasOrImg, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: determineMimeOfFileName(url)
});
},
draw.failure
);
}
function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
registerThumbnailRenderedListener(img, draw);
// NOTE: The fact that maxWidth/height is set on the thumbnail for scaled images
// that must drop back to CSS is known and exploited by the templating module.
// In this module, we pre-render "waiting" thumbs for all files immediately after they
// are submitted, and we must be sure to pass any style associated with the "waiting" preview.
qq(img).css({
maxWidth: maxSize + "px",
maxHeight: maxSize + "px"
});
img.src = url;
}
// Draw a (server-hosted) thumbnail given a URL.
// This will optionally scale the thumbnail as well.
// It attempts to use <canvas> to scale, but will fall back
// to max-width and max-height style properties if the UA
// doesn't support canvas or if the images is cross-domain and
// the UA doesn't support the crossorigin attribute on img tags,
// which is required to scale a cross-origin image using <canvas> &
// then export it back to an <img>.
function drawFromUrl(url, container, options) {
var draw = new qq.Promise(),
scale = options.scale,
maxSize = scale ? options.maxSize : null;
// container is an img, scaling needed
if (scale && isImg(container)) {
// Iff canvas is available in this UA, try to use it for scaling.
// Otherwise, fall back to CSS scaling
if (isCanvasSupported()) {
// Attempt to use <canvas> for image scaling,
// but we must fall back to scaling via CSS/styles
// if this is a cross-origin image and the UA doesn't support <img> CORS.
if (isCrossOrigin(url) && !isImgCorsSupported()) {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
else {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
}
else {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
}
// container is a canvas, scaling optional
else if (isCanvas(container)) {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
// container is an img & no scaling: just set the src attr to the passed url
else if (registerThumbnailRenderedListener(container, draw)) {
container.src = url;
}
return draw;
}
qq.extend(this, {
/**
* Generate a thumbnail. Depending on the arguments, this may either result in
* a client-side rendering of an image (if a `Blob` is supplied) or a server-generated
* image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback).
*
* @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image
* @param container <img> or <canvas> to contain the preview
* @param options possible properties include `maxSize` (int), `orient` (bool - default true), and `resize` (bool - default true)
* @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed
*/
generate: function(fileBlobOrUrl, container, options) {
if (qq.isString(fileBlobOrUrl)) {
log("Attempting to update thumbnail based on server response.");
return drawFromUrl(fileBlobOrUrl, container, options || {});
}
else {
log("Attempting to draw client-side image preview.");
return draw(fileBlobOrUrl, container, options || {});
}
}
});
};
/*globals qq */
/**
* EXIF image data parser. Currently only parses the Orientation tag value,
* but this may be expanded to other tags in the future.
*
* @param fileOrBlob Attempt to parse EXIF data in this `Blob`
* @constructor
*/
qq.Exif = function(fileOrBlob, log) {
"use strict";
// Orientation is the only tag parsed here at this time.
var TAG_IDS = [274],
TAG_INFO = {
274: {
name: "Orientation",
bytes: 2
}
};
// Convert a little endian (hex string) to big endian (decimal).
function parseLittleEndian(hex) {
var result = 0,
pow = 0;
while (hex.length > 0) {
result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
hex = hex.substring(2, hex.length);
pow += 8;
}
return result;
}
// Find the byte offset, of Application Segment 1 (EXIF).
// External callers need not supply any arguments.
function seekToApp1(offset, promise) {
var theOffset = offset,
thePromise = promise;
if (theOffset === undefined) {
theOffset = 2;
thePromise = new qq.Promise();
}
qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
var match = /^ffe([0-9])/.exec(hex),
segmentLength;
if (match) {
if (match[1] !== "1") {
segmentLength = parseInt(hex.slice(4, 8), 16);
seekToApp1(theOffset + segmentLength + 2, thePromise);
}
else {
thePromise.success(theOffset);
}
}
else {
thePromise.failure("No EXIF header to be found!");
}
});
return thePromise;
}
// Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only.
function getApp1Offset() {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
if (hex.indexOf("ffd8") !== 0) {
promise.failure("Not a valid JPEG!");
}
else {
seekToApp1().then(function(offset) {
promise.success(offset);
},
function(error) {
promise.failure(error);
});
}
});
return promise;
}
// Determine the byte ordering of the EXIF header.
function isLittleEndian(app1Start) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
promise.success(hex === "4949");
});
return promise;
}
// Determine the number of directory entries in the EXIF header.
function getDirEntryCount(app1Start, littleEndian) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
if (littleEndian) {
return promise.success(parseLittleEndian(hex));
}
else {
promise.success(parseInt(hex, 16));
}
});
return promise;
}
// Get the IFD portion of the EXIF header as a hex string.
function getIfd(app1Start, dirEntries) {
var offset = app1Start + 20,
bytes = dirEntries * 12;
return qq.readBlobToHex(fileOrBlob, offset, bytes);
}
// Obtain an array of all directory entries (as hex strings) in the EXIF header.
function getDirEntries(ifdHex) {
var entries = [],
offset = 0;
while (offset + 24 <= ifdHex.length) {
entries.push(ifdHex.slice(offset, offset + 24));
offset += 24;
}
return entries;
}
// Obtain values for all relevant tags and return them.
function getTagValues(littleEndian, dirEntries) {
var TAG_VAL_OFFSET = 16,
tagsToFind = qq.extend([], TAG_IDS),
vals = {};
qq.each(dirEntries, function(idx, entry) {
var idHex = entry.slice(0, 4),
id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16),
tagsToFindIdx = tagsToFind.indexOf(id),
tagValHex, tagName, tagValLength;
if (tagsToFindIdx >= 0) {
tagName = TAG_INFO[id].name;
tagValLength = TAG_INFO[id].bytes;
tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength * 2));
vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
tagsToFind.splice(tagsToFindIdx, 1);
}
if (tagsToFind.length === 0) {
return false;
}
});
return vals;
}
qq.extend(this, {
/**
* Attempt to parse the EXIF header for the `Blob` associated with this instance.
*
* @returns {qq.Promise} To be fulfilled when the parsing is complete.
* If successful, the parsed EXIF header as an object will be included.
*/
parse: function() {
var parser = new qq.Promise(),
onParseFailure = function(message) {
log(qq.format("EXIF header parse failed: '{}' ", message));
parser.failure(message);
};
getApp1Offset().then(function(app1Offset) {
log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
isLittleEndian(app1Offset).then(function(littleEndian) {
log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
log(qq.format("Found {} APP1 directory entries", dirEntryCount));
getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
var dirEntries = getDirEntries(ifdHex),
tagValues = getTagValues(littleEndian, dirEntries);
log("Successfully parsed some EXIF tags");
parser.success(tagValues);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
return parser;
}
});
};
/*globals qq */
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false,
magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
/**
* Determines if a Blob can be displayed natively in the current browser. This is done by reading magic
* bytes in the beginning of the file, so this is an asynchronous operation. Before we attempt to read the
* file, we will examine the blob's type attribute to save CPU cycles.
*
* @returns {qq.Promise} Promise that is fulfilled when identification is complete.
* If successful, the MIME string is passed to the success handler.
*/
isPreviewable: function() {
var self = this,
idenitifer = new qq.Promise(),
previewable = false,
name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
// Safari is the only supported browser that can deal with TIFFs natively,
// so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable".
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
idenitifer.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
idenitifer.failure();
}
},
function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
idenitifer.failure();
});
}
else {
idenitifer.failure();
}
return idenitifer;
},
/**
* Determines if a Blob can be displayed natively in the current browser. This is done by checking the
* blob's type attribute. This is a synchronous operation, useful for situations where an asynchronous operation
* would be challenging to support. Note that the blob's type property is not as accurate as reading the
* file's magic bytes.
*
* @returns {Boolean} true if the blob can be rendered in the current browser
*/
isPreviewableSync: function() {
var fileMime = fileOrBlob.type,
// Assumption: This will only ever be executed in browsers that support `Object.keys`.
isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0,
previewable = false,
name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
}
else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": ["49492a00", "4d4d002a"]
};
/*globals qq*/
/**
* Attempts to validate an image, wherever possible.
*
* @param blob File or Blob representing a user-selecting image.
* @param log Uses this to post log messages to the console.
* @constructor
*/
qq.ImageValidation = function(blob, log) {
"use strict";
/**
* @param limits Object with possible image-related limits to enforce.
* @returns {boolean} true if at least one of the limits has a non-zero value
*/
function hasNonZeroLimits(limits) {
var atLeastOne = false;
qq.each(limits, function(limit, value) {
if (value > 0) {
atLeastOne = true;
return false;
}
});
return atLeastOne;
}
/**
* @returns {qq.Promise} The promise is a failure if we can't obtain the width & height.
* Otherwise, `success` is called on the returned promise with an object containing
* `width` and `height` properties.
*/
function getWidthHeight() {
var sizeDetermination = new qq.Promise();
new qq.Identify(blob, log).isPreviewable().then(function() {
var image = new Image(),
url = window.URL && window.URL.createObjectURL ? window.URL :
window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :
null;
if (url) {
image.onerror = function() {
log("Cannot determine dimensions for image. May be too large.", "error");
sizeDetermination.failure();
};
image.onload = function() {
sizeDetermination.success({
width: this.width,
height: this.height
});
};
image.src = url.createObjectURL(blob);
}
else {
log("No createObjectURL function available to generate image URL!", "error");
sizeDetermination.failure();
}
}, sizeDetermination.failure);
return sizeDetermination;
}
/**
*
* @param limits Object with possible image-related limits to enforce.
* @param dimensions Object containing `width` & `height` properties for the image to test.
* @returns {String || undefined} The name of the failing limit. Undefined if no failing limits.
*/
function getFailingLimit(limits, dimensions) {
var failingLimit;
qq.each(limits, function(limitName, limitValue) {
if (limitValue > 0) {
var limitMatcher = /(max|min)(Width|Height)/.exec(limitName),
dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1),
actualValue = dimensions[dimensionPropName];
/*jshint -W015*/
switch (limitMatcher[1]) {
case "min":
if (actualValue < limitValue) {
failingLimit = limitName;
return false;
}
break;
case "max":
if (actualValue > limitValue) {
failingLimit = limitName;
return false;
}
break;
}
}
});
return failingLimit;
}
/**
* Validate the associated blob.
*
* @param limits
* @returns {qq.Promise} `success` is called on the promise is the image is valid or
* if the blob is not an image, or if the image is not verifiable.
* Otherwise, `failure` with the name of the failing limit.
*/
this.validate = function(limits) {
var validationEffort = new qq.Promise();
log("Attempting to validate image.");
if (hasNonZeroLimits(limits)) {
getWidthHeight().then(function(dimensions) {
var failingLimit = getFailingLimit(limits, dimensions);
if (failingLimit) {
validationEffort.failure(failingLimit);
}
else {
validationEffort.success();
}
}, validationEffort.success);
}
else {
validationEffort.success();
}
return validationEffort;
};
};
/* globals qq */
/**
* Module used to control populating the initial list of files.
*
* @constructor
*/
qq.Session = function(spec) {
"use strict";
var options = {
endpoint: null,
params: {},
customHeaders: {},
cors: {},
addFileRecord: function(sessionData) {},
log: function(message, level) {}
};
qq.extend(options, spec, true);
function isJsonResponseValid(response) {
if (qq.isArray(response)) {
return true;
}
options.log("Session response is not an array.", "error");
}
function handleFileItems(fileItems, success, xhrOrXdr, promise) {
var someItemsIgnored = false;
success = success && isJsonResponseValid(fileItems);
if (success) {
qq.each(fileItems, function(idx, fileItem) {
/* jshint eqnull:true */
if (fileItem.uuid == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
}
else if (fileItem.name == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
}
else {
try {
options.addFileRecord(fileItem);
return true;
}
catch (err) {
someItemsIgnored = true;
options.log(err.message, "error");
}
}
return false;
});
}
promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
}
// Initiate a call to the server that will be used to populate the initial file list.
// Returns a `qq.Promise`.
this.refresh = function() {
/*jshint indent:false */
var refreshEffort = new qq.Promise(),
refreshCompleteCallback = function(response, success, xhrOrXdr) {
handleFileItems(response, success, xhrOrXdr, refreshEffort);
},
requsterOptions = qq.extend({}, options),
requester = new qq.SessionAjaxRequester(
qq.extend(requsterOptions, {onComplete: refreshCompleteCallback})
);
requester.queryServer();
return refreshEffort;
};
};
/*globals qq, XMLHttpRequest*/
/**
* Thin module used to send GET requests to the server, expecting information about session
* data used to initialize an uploader instance.
*
* @param spec Various options used to influence the associated request.
* @constructor
*/
qq.SessionAjaxRequester = function(spec) {
"use strict";
var requester,
options = {
endpoint: null,
customHeaders: {},
params: {},
cors: {
expected: false,
sendCredentials: false
},
onComplete: function(response, success, xhrOrXdr) {},
log: function(str, level) {}
};
qq.extend(options, spec);
function onComplete(id, xhrOrXdr, isError) {
var response = null;
/* jshint eqnull:true */
if (xhrOrXdr.responseText != null) {
try {
response = qq.parseJson(xhrOrXdr.responseText);
}
catch (err) {
options.log("Problem parsing session response: " + err.message, "error");
isError = true;
}
}
options.onComplete(response, !isError, xhrOrXdr);
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: ["GET"],
method: "GET",
endpointStore: {
get: function() {
return options.endpoint;
}
},
customHeaders: options.customHeaders,
log: options.log,
onComplete: onComplete,
cors: options.cors
}));
qq.extend(this, {
queryServer: function() {
var params = qq.extend({}, options.params);
options.log("Session query request.");
requester.initTransport("sessionRefresh")
.withParams(params)
.withCacheBuster()
.send();
}
});
};
/* globals qq */
/**
* Module that handles support for existing forms.
*
* @param options Options passed from the integrator-supplied options related to form support.
* @param startUpload Callback to invoke when files "stored" should be uploaded.
* @param log Proxy for the logger
* @constructor
*/
qq.FormSupport = function(options, startUpload, log) {
"use strict";
var self = this,
interceptSubmit = options.interceptSubmit,
formEl = options.element,
autoUpload = options.autoUpload;
// Available on the public API associated with this module.
qq.extend(this, {
// To be used by the caller to determine if the endpoint will be determined by some processing
// that occurs in this module, such as if the form has an action attribute.
// Ignore if `attachToForm === false`.
newEndpoint: null,
// To be used by the caller to determine if auto uploading should be allowed.
// Ignore if `attachToForm === false`.
newAutoUpload: autoUpload,
// true if a form was detected and is being tracked by this module
attachedToForm: false,
// Returns an object with names and values for all valid form elements associated with the attached form.
getFormInputsAsObject: function() {
/* jshint eqnull:true */
if (formEl == null) {
return null;
}
return self._form2Obj(formEl);
}
});
// If the form contains an action attribute, this should be the new upload endpoint.
function determineNewEndpoint(formEl) {
if (formEl.getAttribute("action")) {
self.newEndpoint = formEl.getAttribute("action");
}
}
// Return true only if the form is valid, or if we cannot make this determination.
// If the form is invalid, ensure invalid field(s) are highlighted in the UI.
function validateForm(formEl, nativeSubmit) {
if (formEl.checkValidity && !formEl.checkValidity()) {
log("Form did not pass validation checks - will not upload.", "error");
nativeSubmit();
}
else {
return true;
}
}
// Intercept form submit attempts, unless the integrator has told us not to do this.
function maybeUploadOnSubmit(formEl) {
var nativeSubmit = formEl.submit;
// Intercept and squelch submit events.
qq(formEl).attach("submit", function(event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
validateForm(formEl, nativeSubmit) && startUpload();
});
// The form's `submit()` function may be called instead (i.e. via jQuery.submit()).
// Intercept that too.
formEl.submit = function() {
validateForm(formEl, nativeSubmit) && startUpload();
};
}
// If the element value passed from the uploader is a string, assume it is an element ID - select it.
// The rest of the code in this module depends on this being an HTMLElement.
function determineFormEl(formEl) {
if (formEl) {
if (qq.isString(formEl)) {
formEl = document.getElementById(formEl);
}
if (formEl) {
log("Attaching to form element.");
determineNewEndpoint(formEl);
interceptSubmit && maybeUploadOnSubmit(formEl);
}
}
return formEl;
}
formEl = determineFormEl(formEl);
this.attachedToForm = !!formEl;
};
qq.extend(qq.FormSupport.prototype, {
// Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will
// construct from a given form when the form is submitted.
_form2Obj: function(form) {
"use strict";
var obj = {},
notIrrelevantType = function(type) {
var irrelevantTypes = [
"button",
"image",
"reset",
"submit"
];
return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
},
radioOrCheckbox = function(type) {
return qq.indexOf(["checkbox", "radio"], type.toLowerCase()) >= 0;
},
ignoreValue = function(el) {
if (radioOrCheckbox(el.type) && !el.checked) {
return true;
}
return el.disabled && el.type.toLowerCase() !== "hidden";
},
selectValue = function(select) {
var value = null;
qq.each(qq(select).children(), function(idx, child) {
if (child.tagName.toLowerCase() === "option" && child.selected) {
value = child.value;
return false;
}
});
return value;
};
qq.each(form.elements, function(idx, el) {
if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") &&
notIrrelevantType(el.type) &&
!ignoreValue(el)) {
obj[el.name] = el.value;
}
else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
var value = selectValue(el);
if (value !== null) {
obj[el.name] = value;
}
}
});
return obj;
}
});
/* globals qq, ExifRestorer */
/**
* Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`.
* Scaled images are generated and converted to blobs on-demand.
* Multiple scaled images per reference image with varying sizes and other properties are supported.
*
* @param spec Information about the scaled images to generate.
* @param log Logger instance
* @constructor
*/
qq.Scaler = function(spec, log) {
"use strict";
var self = this,
includeOriginal = spec.sendOriginal,
orient = spec.orient,
defaultType = spec.defaultType,
defaultQuality = spec.defaultQuality / 100,
failedToScaleText = spec.failureText,
includeExif = spec.includeExif,
sizes = this._getSortedSizes(spec.sizes);
// Revealed API for instances of this module
qq.extend(this, {
// If no targeted sizes have been declared or if this browser doesn't support
// client-side image preview generation, there is no scaling to do.
enabled: qq.supportedFeatures.scaling && sizes.length > 0,
getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
var self = this,
records = [],
originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData,
idenitifier = new qq.Identify(originalBlob, log);
// If the reference file cannot be rendered natively, we can't create scaled versions.
if (idenitifier.isPreviewableSync()) {
// Create records for each scaled version & add them to the records array, smallest first.
qq.each(sizes, function(idx, sizeRecord) {
var outputType = self._determineOutputType({
defaultType: defaultType,
requestedType: sizeRecord.type,
refType: originalBlob.type
});
records.push({
uuid: qq.getUniqueId(),
name: self._getName(originalFileName, {
name: sizeRecord.name,
type: outputType,
refType: originalBlob.type
}),
blob: new qq.BlobProxy(originalBlob,
qq.bind(self._generateScaledImage, self, {
maxSize: sizeRecord.maxSize,
orient: orient,
type: outputType,
quality: defaultQuality,
failedText: failedToScaleText,
includeExif: includeExif,
log: log
}))
});
});
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: includeOriginal ? originalBlob : null
});
}
else {
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: originalBlob
});
}
return records;
},
handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
var self = this,
buttonId = file.qqButtonId || (file.blob && file.blob.qqButtonId),
scaledIds = [],
originalId = null,
addFileToHandler = api.addFileToHandler,
uploadData = api.uploadData,
paramsStore = api.paramsStore,
proxyGroupId = qq.getUniqueId();
qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
var blobSize = record.size,
id;
if (record.blob instanceof qq.BlobProxy) {
blobSize = -1;
}
id = uploadData.addFile({
uuid: record.uuid,
name: record.name,
size: blobSize,
batchId: batchId,
proxyGroupId: proxyGroupId
});
if (record.blob instanceof qq.BlobProxy) {
scaledIds.push(id);
}
else {
originalId = id;
}
if (record.blob) {
addFileToHandler(id, record.blob);
fileList.push({id: id, file: record.blob});
}
else {
uploadData.setStatus(id, qq.status.REJECTED);
}
});
// If we are potentially uploading an original file and some scaled versions,
// ensure the scaled versions include reference's to the parent's UUID and size
// in their associated upload requests.
if (originalId !== null) {
qq.each(scaledIds, function(idx, scaledId) {
var params = {
qqparentuuid: uploadData.retrieve({id: originalId}).uuid,
qqparentsize: uploadData.retrieve({id: originalId}).size
};
// Make sure the UUID for each scaled image is sent with the upload request,
// to be consistent (since we may need to ensure it is sent for the original file as well).
params[uuidParamName] = uploadData.retrieve({id: scaledId}).uuid;
uploadData.setParentId(scaledId, originalId);
paramsStore.addReadOnly(scaledId, params);
});
// If any scaled images are tied to this parent image, be SURE we send its UUID as an upload request
// parameter as well.
if (scaledIds.length) {
(function() {
var param = {};
param[uuidParamName] = uploadData.retrieve({id: originalId}).uuid;
paramsStore.addReadOnly(originalId, param);
}());
}
}
}
});
};
qq.extend(qq.Scaler.prototype, {
scaleImage: function(id, specs, api) {
"use strict";
if (!qq.supportedFeatures.scaling) {
throw new qq.Error("Scaling is not supported in this browser!");
}
var scalingEffort = new qq.Promise(),
log = api.log,
file = api.getFile(id),
uploadData = api.uploadData.retrieve({id: id}),
name = uploadData && uploadData.name,
uuid = uploadData && uploadData.uuid,
scalingOptions = {
sendOriginal: false,
orient: specs.orient,
defaultType: specs.type || null,
defaultQuality: specs.quality,
failedToScaleText: "Unable to scale",
sizes: [{name: "", maxSize: specs.maxSize}]
},
scaler = new qq.Scaler(scalingOptions, log);
if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
scalingEffort.failure();
log("Could not generate requested scaled image for " + id + ". " +
"Scaling is either not possible in this browser, or the file could not be located.", "error");
}
else {
(qq.bind(function() {
// Assumption: There will never be more than one record
var record = scaler.getFileRecords(uuid, name, file)[0];
if (record && record.blob instanceof qq.BlobProxy) {
record.blob.create().then(scalingEffort.success, scalingEffort.failure);
}
else {
log(id + " is not a scalable image!", "error");
scalingEffort.failure();
}
}, this)());
}
return scalingEffort;
},
// NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format.
// image/jpeg and image/png are the only safe choices at this time.
_determineOutputType: function(spec) {
"use strict";
var requestedType = spec.requestedType,
defaultType = spec.defaultType,
referenceType = spec.refType;
// If a default type and requested type have not been specified, this should be a
// JPEG if the original type is a JPEG, otherwise, a PNG.
if (!defaultType && !requestedType) {
if (referenceType !== "image/jpeg") {
return "image/png";
}
return referenceType;
}
// A specified default type is used when a requested type is not specified.
if (!requestedType) {
return defaultType;
}
// If requested type is specified, use it, as long as this recognized type is supported by the current UA
if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
if (requestedType === "image/tiff") {
return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
}
return requestedType;
}
return defaultType;
},
// Get a file name for a generated scaled file record, based on the provided scaled image description
_getName: function(originalName, scaledVersionProperties) {
"use strict";
var startOfExt = originalName.lastIndexOf("."),
versionType = scaledVersionProperties.type || "image/png",
referenceType = scaledVersionProperties.refType,
scaledName = "",
scaledExt = qq.getExtension(originalName),
nameAppendage = "";
if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
nameAppendage = " (" + scaledVersionProperties.name + ")";
}
if (startOfExt >= 0) {
scaledName = originalName.substr(0, startOfExt);
if (referenceType !== versionType) {
scaledExt = versionType.split("/")[1];
}
scaledName += nameAppendage + "." + scaledExt;
}
else {
scaledName = originalName + nameAppendage;
}
return scaledName;
},
// We want the smallest scaled file to be uploaded first
_getSortedSizes: function(sizes) {
"use strict";
sizes = qq.extend([], sizes);
return sizes.sort(function(a, b) {
if (a.maxSize > b.maxSize) {
return 1;
}
if (a.maxSize < b.maxSize) {
return -1;
}
return 0;
});
},
_generateScaledImage: function(spec, sourceFile) {
"use strict";
var self = this,
log = spec.log,
maxSize = spec.maxSize,
orient = spec.orient,
type = spec.type,
quality = spec.quality,
failedText = spec.failedText,
includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg",
scalingEffort = new qq.Promise(),
imageGenerator = new qq.ImageGenerator(log),
canvas = document.createElement("canvas");
log("Attempting to generate scaled version for " + sourceFile.name);
imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient}).then(function() {
var scaledImageDataUri = canvas.toDataURL(type, quality),
signalSuccess = function() {
log("Success generating scaled version for " + sourceFile.name);
var blob = qq.dataUriToBlob(scaledImageDataUri);
scalingEffort.success(blob);
};
if (includeExif) {
self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
scaledImageDataUri = scaledImageDataUriWithExif;
signalSuccess();
},
function() {
log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
signalSuccess();
});
}
else {
signalSuccess();
}
}, function() {
log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
scalingEffort.failure(failedText);
});
return scalingEffort;
},
// Attempt to insert the original image's EXIF header into a scaled version.
_insertExifHeader: function(originalImage, scaledImageDataUri, log) {
"use strict";
var reader = new FileReader(),
insertionEffort = new qq.Promise(),
originalImageDataUri = "";
reader.onload = function() {
originalImageDataUri = reader.result;
insertionEffort.success(ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
};
reader.onerror = function() {
log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
insertionEffort.failure();
};
reader.readAsDataURL(originalImage);
return insertionEffort;
},
_dataUriToBlob: function(dataUri) {
"use strict";
var byteString, mimeString, arrayBuffer, intArray;
// convert base64 to raw binary data held in a string
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
}
else {
byteString = decodeURI(dataUri.split(",")[1]);
}
// extract the MIME
mimeString = dataUri.split(",")[0]
.split(":")[1]
.split(";")[0];
// write the bytes of the binary string to an ArrayBuffer
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return this._createBlob(arrayBuffer, mimeString);
},
_createBlob: function(data, mime) {
"use strict";
var BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder,
blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
}
else {
return new Blob([data], {type: mime});
}
}
});
//Based on MinifyJpeg
//http://elicon.blog57.fc2.com/blog-entry-206.html
var ExifRestorer = (function()
{
var ExifRestorer = {};
ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
ExifRestorer.encode64 = function(input)
{
var output = "",
chr1, chr2, chr3 = "",
enc1, enc2, enc3, enc4 = "",
i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.KEY_STR.charAt(enc1) +
this.KEY_STR.charAt(enc2) +
this.KEY_STR.charAt(enc3) +
this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
};
ExifRestorer.restore = function(origFileBase64, resizedFileBase64)
{
var expectedBase64Header = "data:image/jpeg;base64,";
if (!origFileBase64.match(expectedBase64Header))
{
return resizedFileBase64;
}
var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return expectedBase64Header + this.encode64(image);
};
ExifRestorer.exifManipulation = function(resizedFileBase64, segments)
{
var exifArray = this.getExifArray(segments),
newImageArray = this.insertExif(resizedFileBase64, exifArray),
aBuffer = new Uint8Array(newImageArray);
return aBuffer;
};
ExifRestorer.getExifArray = function(segments)
{
var seg;
for (var x = 0; x < segments.length; x++)
{
seg = segments[x];
if (seg[0] == 255 & seg[1] == 225) //(ff e1)
{
return seg;
}
}
return [];
};
ExifRestorer.insertExif = function(resizedFileBase64, exifArray)
{
var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""),
buf = this.decode64(imageData),
separatePoint = buf.indexOf(255,3),
mae = buf.slice(0, separatePoint),
ato = buf.slice(separatePoint),
array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
};
ExifRestorer.slice2Segments = function(rawImageArray)
{
var head = 0,
segments = [];
while (1)
{
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218){break;}
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216)
{
head += 2;
}
else
{
var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3],
endPoint = head + length + 2,
seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length){break;}
}
return segments;
};
ExifRestorer.decode64 = function(input)
{
var output = "",
chr1, chr2, chr3 = "",
enc1, enc2, enc3, enc4 = "",
i = 0,
buf = [];
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
throw new Error("There were invalid base64 characters in the input text. " +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
buf.push(chr1);
if (enc3 != 64) {
buf.push(chr2);
}
if (enc4 != 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return buf;
};
return ExifRestorer;
})();
/* globals qq */
/**
* Keeps a running tally of total upload progress for a batch of files.
*
* @param callback Invoked when total progress changes, passing calculated total loaded & total size values.
* @param getSize Function that returns the size of a file given its ID
* @constructor
*/
qq.TotalProgress = function(callback, getSize) {
"use strict";
var perFileProgress = {},
totalLoaded = 0,
totalSize = 0,
lastLoadedSent = -1,
lastTotalSent = -1,
callbackProxy = function(loaded, total) {
if (loaded !== lastLoadedSent || total !== lastTotalSent) {
callback(loaded, total);
}
lastLoadedSent = loaded;
lastTotalSent = total;
},
/**
* @param failed Array of file IDs that have failed
* @param retryable Array of file IDs that are retryable
* @returns true if none of the failed files are eligible for retry
*/
noRetryableFiles = function(failed, retryable) {
var none = true;
qq.each(failed, function(idx, failedId) {
if (qq.indexOf(retryable, failedId) >= 0) {
none = false;
return false;
}
});
return none;
},
onCancel = function(id) {
updateTotalProgress(id, -1, -1);
delete perFileProgress[id];
},
onAllComplete = function(successful, failed, retryable) {
if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
callbackProxy(totalSize, totalSize);
this.reset();
}
},
onNew = function(id) {
var size = getSize(id);
// We might not know the size yet, such as for blob proxies
if (size > 0) {
updateTotalProgress(id, 0, size);
perFileProgress[id] = {loaded: 0, total: size};
}
},
/**
* Invokes the callback with the current total progress of all files in the batch. Called whenever it may
* be appropriate to re-calculate and dissemenate this data.
*
* @param id ID of a file that has changed in some important way
* @param newLoaded New loaded value for this file. -1 if this value should no longer be part of calculations
* @param newTotal New total size of the file. -1 if this value should no longer be part of calculations
*/
updateTotalProgress = function(id, newLoaded, newTotal) {
var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0,
oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
if (newLoaded === -1 && newTotal === -1) {
totalLoaded -= oldLoaded;
totalSize -= oldTotal;
}
else {
if (newLoaded) {
totalLoaded += newLoaded - oldLoaded;
}
if (newTotal) {
totalSize += newTotal - oldTotal;
}
}
callbackProxy(totalLoaded, totalSize);
};
qq.extend(this, {
// Called when a batch of files has completed uploading.
onAllComplete: onAllComplete,
// Called when the status of a file has changed.
onStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
onCancel(id);
}
else if (newStatus === qq.status.SUBMITTING) {
onNew(id);
}
},
// Called whenever the upload progress of an individual file has changed.
onIndividualProgress: function(id, loaded, total) {
updateTotalProgress(id, loaded, total);
perFileProgress[id] = {loaded: loaded, total: total};
},
// Called whenever the total size of a file has changed, such as when the size of a generated blob is known.
onNewSize: function(id) {
onNew(id);
},
reset: function() {
perFileProgress = {};
totalLoaded = 0;
totalSize = 0;
}
});
};
/*globals qq */
// Base handler for UI (FineUploader mode) events.
// Some more specific handlers inherit from this one.
qq.UiEventHandler = function(s, protectedApi) {
"use strict";
var disposer = new qq.DisposeSupport(),
spec = {
eventType: "click",
attachTo: null,
onHandled: function(target, event) {}
};
// This makes up the "public" API methods that will be accessible
// to instances constructing a base or child handler
qq.extend(this, {
addHandler: function(element) {
addHandler(element);
},
dispose: function() {
disposer.dispose();
}
});
function addHandler(element) {
disposer.attach(element, spec.eventType, function(event) {
// Only in IE: the `event` is a property of the `window`.
event = event || window.event;
// On older browsers, we must check the `srcElement` instead of the `target`.
var target = event.target || event.srcElement;
spec.onHandled(target, event);
});
}
// These make up the "protected" API methods that children of this base handler will utilize.
qq.extend(protectedApi, {
getFileIdFromItem: function(item) {
return item.qqFileId;
},
getDisposeSupport: function() {
return disposer;
}
});
qq.extend(spec, s);
if (spec.attachTo) {
addHandler(spec.attachTo);
}
};
/* global qq */
qq.FileButtonsClickHandler = function(s) {
"use strict";
var inheritedInternalApi = {},
spec = {
templating: null,
log: function(message, lvl) {},
onDeleteFile: function(fileId) {},
onCancel: function(fileId) {},
onRetry: function(fileId) {},
onPause: function(fileId) {},
onContinue: function(fileId) {},
onGetName: function(fileId) {}
},
buttonHandlers = {
cancel: function(id) { spec.onCancel(id); },
retry: function(id) { spec.onRetry(id); },
deleteButton: function(id) { spec.onDeleteFile(id); },
pause: function(id) { spec.onPause(id); },
continueButton: function(id) { spec.onContinue(id); }
};
function examineEvent(target, event) {
qq.each(buttonHandlers, function(buttonType, handler) {
var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1),
fileId;
if (spec.templating["is" + firstLetterCapButtonType](target)) {
fileId = spec.templating.getFileId(target);
qq.preventDefault(event);
spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
handler(fileId);
return false;
}
});
}
qq.extend(spec, s);
spec.eventType = "click";
spec.onHandled = examineEvent;
spec.attachTo = spec.templating.getFileList();
qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
};
/*globals qq */
// Child of FilenameEditHandler. Used to detect click events on filename display elements.
qq.FilenameClickHandler = function(s) {
"use strict";
var inheritedInternalApi = {},
spec = {
templating: null,
log: function(message, lvl) {},
classes: {
file: "qq-upload-file",
editNameIcon: "qq-edit-filename-icon"
},
onGetUploadStatus: function(fileId) {},
onGetName: function(fileId) {}
};
qq.extend(spec, s);
// This will be called by the parent handler when a `click` event is received on the list element.
function examineEvent(target, event) {
if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {
var fileId = spec.templating.getFileId(target),
status = spec.onGetUploadStatus(fileId);
// We only allow users to change filenames of files that have been submitted but not yet uploaded.
if (status === qq.status.SUBMITTED) {
spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
qq.preventDefault(event);
inheritedInternalApi.handleFilenameEdit(fileId, target, true);
}
}
}
spec.eventType = "click";
spec.onHandled = examineEvent;
qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
};
/*globals qq */
// Child of FilenameEditHandler. Used to detect focusin events on file edit input elements.
qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) {
"use strict";
var spec = {
templating: null,
onGetUploadStatus: function(fileId) {},
log: function(message, lvl) {}
};
if (!inheritedInternalApi) {
inheritedInternalApi = {};
}
// This will be called by the parent handler when a `focusin` event is received on the list element.
function handleInputFocus(target, event) {
if (spec.templating.isEditInput(target)) {
var fileId = spec.templating.getFileId(target),
status = spec.onGetUploadStatus(fileId);
if (status === qq.status.SUBMITTED) {
spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
inheritedInternalApi.handleFilenameEdit(fileId, target);
}
}
}
spec.eventType = "focusin";
spec.onHandled = handleInputFocus;
qq.extend(spec, s);
qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
};
/*globals qq */
/**
* Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only
* needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event.
*
* @param spec Overrides for default specifications
*/
qq.FilenameInputFocusHandler = function(spec) {
"use strict";
spec.eventType = "focus";
spec.attachTo = null;
qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {}));
};
/*globals qq */
// Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler.
// Children will delegate to this handler when specific edit-related actions are detected.
qq.FilenameEditHandler = function(s, inheritedInternalApi) {
"use strict";
var spec = {
templating: null,
log: function(message, lvl) {},
onGetUploadStatus: function(fileId) {},
onGetName: function(fileId) {},
onSetName: function(fileId, newName) {},
onEditingStatusChange: function(fileId, isEditing) {}
};
function getFilenameSansExtension(fileId) {
var filenameSansExt = spec.onGetName(fileId),
extIdx = filenameSansExt.lastIndexOf(".");
if (extIdx > 0) {
filenameSansExt = filenameSansExt.substr(0, extIdx);
}
return filenameSansExt;
}
function getOriginalExtension(fileId) {
var origName = spec.onGetName(fileId);
return qq.getExtension(origName);
}
// Callback iff the name has been changed
function handleNameUpdate(newFilenameInputEl, fileId) {
var newName = newFilenameInputEl.value,
origExtension;
if (newName !== undefined && qq.trimStr(newName).length > 0) {
origExtension = getOriginalExtension(fileId);
if (origExtension !== undefined) {
newName = newName + "." + origExtension;
}
spec.onSetName(fileId, newName);
}
spec.onEditingStatusChange(fileId, false);
}
// The name has been updated if the filename edit input loses focus.
function registerInputBlurHandler(inputEl, fileId) {
inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() {
handleNameUpdate(inputEl, fileId);
});
}
// The name has been updated if the user presses enter.
function registerInputEnterKeyHandler(inputEl, fileId) {
inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
handleNameUpdate(inputEl, fileId);
}
});
}
qq.extend(spec, s);
spec.attachTo = spec.templating.getFileList();
qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
qq.extend(inheritedInternalApi, {
handleFilenameEdit: function(id, target, focusInput) {
var newFilenameInputEl = spec.templating.getEditInput(id);
spec.onEditingStatusChange(id, true);
newFilenameInputEl.value = getFilenameSansExtension(id);
if (focusInput) {
newFilenameInputEl.focus();
}
registerInputBlurHandler(newFilenameInputEl, id);
registerInputEnterKeyHandler(newFilenameInputEl, id);
}
});
};
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else if (thatWords.length > 0xffff) {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
} else {
// Copy all words at once
thisWords.push.apply(thisWords, thatWords);
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push((Math.random() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
/*! 2015-07-29 */
|
/*! Native Promise Only
v0.7.5-a (c) Kyle Simpson
MIT License: http://getify.mit-license.org
*/
(function UMD(name,context,definition){
// special form of UMD for polyfilling across evironments
context[name] = context[name] || definition();
if (typeof module != "undefined" && module.exports) { module.exports = context[name]; }
else if (typeof define == "function" && define.amd) { define(function $AMD$(){ return context[name]; }); }
})("Promise",typeof global != "undefined" ? global : this,function DEF(){
/*jshint validthis:true */
"use strict";
var cycle, scheduling_queue, ToString = Object.prototype.toString,
timer = (typeof setImmediate != "undefined") ?
function timer(fn) { return setImmediate(fn); } :
setTimeout,
builtInProp = Object.defineProperty ?
function builtInProp(obj,name,val,config) {
return Object.defineProperty(obj,name,{
value: val,
writable: true,
configurable: config !== false
});
} :
function builtInProp(obj,name,val) {
obj[name] = val;
return obj;
}
;
// Note: using a queue instead of array for efficiency
function Queue() {
var first, last, item;
function Item(fn,self) {
this.fn = fn;
this.self = self;
this.next = void 0;
}
return {
add: function add(fn,self) {
item = new Item(fn,self);
if (last) {
last.next = item;
}
else {
first = item;
}
last = item;
item = void 0;
},
drain: function drain() {
var f = first;
first = last = cycle = void 0;
while (f) {
f.fn.call(f.self);
f = f.next;
}
}
};
}
scheduling_queue = Queue();
function schedule(fn,self) {
scheduling_queue.add(fn,self);
if (!cycle) {
cycle = timer(scheduling_queue.drain);
}
}
// promise duck typing?
function isThenable(o) {
var _then, o_type = typeof o;
if (o !== null &&
(
o_type === "object" || o_type === "function"
)
) {
_then = o.then;
}
return typeof _then == "function" ? _then : false;
}
function notify() {
for (var i=0; i<this.chain.length; i++) {
notifyIsolated(
this,
(this.state === 1) ? this.chain[i].success : this.chain[i].failure,
this.chain[i]
);
}
this.chain.length = 0;
}
// NOTE: This is a separate function to isolate
// the `try..catch` so that other code can be
// optimized better
function notifyIsolated(self,cb,chain) {
var ret, _then;
try {
if (cb === false) {
chain.reject(self.msg);
}
else {
if (cb === true) ret = self.msg;
else ret = cb.call(void 0,self.msg);
if (ret === chain.promise) {
chain.reject(TypeError("Promise-chain cycle"));
}
else if (_then = isThenable(ret)) {
_then.call(ret,chain.resolve,chain.reject);
}
else {
chain.resolve(ret);
}
}
}
catch (err) {
chain.reject(err);
}
}
function checkYourself(self) {
if (self.triggered) {
return false;
}
self.triggered = true;
if (self.def) {
self = self.def;
}
return self;
}
function resolve(msg) {
var _then, def_wrapper, self = checkYourself(this);
// self-check failed
if (self === false) { return; }
try {
if (_then = isThenable(msg)) {
def_wrapper = new MakeDefWrapper(self);
_then.call(msg,
function $resolve$(){ resolve.apply(def_wrapper,arguments); },
function $reject$(){ reject.apply(def_wrapper,arguments); }
);
}
else {
self.msg = msg;
self.state = 1;
if (self.chain.length > 0) {
schedule(notify,self);
}
}
}
catch (err) {
reject.call(def_wrapper || (new MakeDefWrapper(self)),err);
}
}
function reject(msg) {
var self = checkYourself(this);
// self-check failed
if (self === false) { return; }
self.msg = msg;
self.state = 2;
if (self.chain.length > 0) {
schedule(notify,self);
}
}
function iteratePromises(Constructor,arr,resolver,rejecter) {
for (var idx=0; idx<arr.length; idx++) {
(function(idx){
Constructor.resolve(arr[idx])
.then(
function $resolver$(msg){
resolver(idx,msg);
},
rejecter
);
})(idx);
}
}
function MakeDefWrapper(self) {
this.def = self;
this.triggered = false;
}
function MakeDef(self) {
this.promise = self;
this.state = 0;
this.triggered = false;
this.chain = [];
this.msg = void 0;
}
function Promise(executor) {
if (typeof executor != "function") {
throw TypeError("Not a function");
}
if (this.__NPO__ !== 0) {
throw TypeError("Not a promise");
}
// instance shadowing the inherited "brand"
// to signal an already "initialized" promise
this.__NPO__ = 1;
var self = this, def = new MakeDef(self);
builtInProp(self,"then",function then(success,failure) {
var o = {
success: typeof success == "function" ? success : true,
failure: typeof failure == "function" ? failure : false
};
// Note: `then(..)` itself can be borrowed to be used against
// a different promise constructor for making the chained promise,
// by substituting a different `this` binding.
o.promise = new this.constructor(function extractChain(resolve,reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
o.resolve = resolve;
o.reject = reject;
});
def.chain.push(o);
if (def.state !== 0) {
schedule(notify,def);
}
return o.promise;
},false);
// `catch` not allowed as identifier in older JS engines
builtInProp(self,"catch",function $catch$(failure) {
return this.then(void 0,failure);
},false);
try {
executor.call(
void 0,
function publicResolve(msg){
resolve.call(def,msg);
},
function publicReject(msg) {
reject.call(def,msg);
}
);
}
catch (err) {
reject.call(def,err);
}
}
var PromisePrototype = builtInProp({},"constructor",Promise,
/*configurable=*/false
);
builtInProp(
Promise,"prototype",PromisePrototype,
/*configurable=*/false
);
// built-in "brand" to signal an "uninitialized" promise
builtInProp(PromisePrototype,"__NPO__",0,
/*configurable=*/false
);
builtInProp(Promise,"resolve",function Promise$resolve(msg) {
var Constructor = this;
// spec mandated checks
// note: best "isPromise" check that's practical for now
if (typeof msg == "object" && msg.__NPO__ === 1) {
return msg;
}
return new Constructor(function executor(resolve,reject){
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
resolve(msg);
});
});
builtInProp(Promise,"reject",function Promise$reject(msg) {
return new this(function executor(resolve,reject){
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
reject(msg);
});
});
builtInProp(Promise,"all",function Promise$all(arr) {
var Constructor = this;
// spec mandated checks
if (ToString.call(arr) != "[object Array]") {
return Constructor.reject(TypeError("Not an array"));
}
if (arr.length === 0) {
return Constructor.resolve([]);
}
return new Constructor(function executor(resolve,reject){
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
var len = arr.length, msgs = Array(len), count = 0;
iteratePromises(Constructor,arr,function resolver(idx,msg) {
msgs[idx] = msg;
if (++count === len) {
resolve(msgs);
}
},reject);
});
});
builtInProp(Promise,"race",function Promise$race(arr) {
var Constructor = this;
// spec mandated checks
if (ToString.call(arr) != "[object Array]") {
return Constructor.reject(TypeError("Not an array"));
}
return new Constructor(function executor(resolve,reject){
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
iteratePromises(Constructor,arr,function resolver(idx,msg){
resolve(msg);
},reject);
});
});
return Promise;
});
|
L.DeferredLayer=L.LayerGroup.extend({options:{js:[],init:null},_script_cache:{},initialize:function(t){L.Util.setOptions(this,t),L.LayerGroup.prototype.initialize.apply(this),this._loaded=!1},onAdd:function(t){if(L.LayerGroup.prototype.onAdd.apply(this,[t]),!this._loaded){var i=function(){this._loaded=!0;var t=this.options.init();t&&this.addLayer(t)};this._loadScripts(this.options.js.reverse(),L.Util.bind(i,this))}},_loadScripts:function(t,i,e){function a(){r._loadScripts(t,i,e)}if(!t||0==t.length)return i(e);var o,r=this,n=t.pop();if(o=this._script_cache[n],void 0===o){o={url:n,wait:[]};var s=document.createElement("script");s.src=n,s.type="text/javascript",s.onload=function(){o.e.readyState="completed";var t=0;for(t=0;t<o.wait.length;t++)o.wait[t]()},o.e=s,document.getElementsByTagName("head")[0].appendChild(s)}o.wait.push(a),"completed"==o.e.readyState&&a(),this._script_cache[n]=o}});
//# sourceMappingURL=./1.1.0/layer/Layer.Deferred.min.js.map |
/*!
* js-data-http
* @version 3.0.0-alpha.7 - Homepage <http://www.js-data.io/docs/dshttpadapter>
* @author Jason Dobry <jason.dobry@gmail.com>
* @copyright (c) 2014-2015 Jason Dobry
* @license MIT <https://github.com/js-data/js-data-http/blob/master/LICENSE>
*
* @overview HTTP adapter for js-data.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("js-data"));
else if(typeof define === 'function' && define.amd)
define(["js-data"], factory);
else if(typeof exports === 'object')
exports["HttpAdapter"] = factory(require("js-data"));
else
root["HttpAdapter"] = factory(root["JSData"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _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; };
var _jsData = __webpack_require__(1);
var _jsDataAdapter = __webpack_require__(2);
var _jsDataAdapter2 = _interopRequireDefault(_jsDataAdapter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global fetch:true Headers:true Request:true */
var axios = __webpack_require__(3);
var _ = _jsData.utils._;
var addHiddenPropsToTarget = _jsData.utils.addHiddenPropsToTarget;
var copy = _jsData.utils.copy;
var deepMixIn = _jsData.utils.deepMixIn;
var extend = _jsData.utils.extend;
var fillIn = _jsData.utils.fillIn;
var forOwn = _jsData.utils.forOwn;
var get = _jsData.utils.get;
var isArray = _jsData.utils.isArray;
var isFunction = _jsData.utils.isFunction;
var isNumber = _jsData.utils.isNumber;
var isObject = _jsData.utils.isObject;
var isSorN = _jsData.utils.isSorN;
var isString = _jsData.utils.isString;
var isUndefined = _jsData.utils.isUndefined;
var resolve = _jsData.utils.resolve;
var reject = _jsData.utils.reject;
var toJson = _jsData.utils.toJson;
var hasFetch = false;
try {
hasFetch = window && window.fetch;
} catch (e) {}
var noop = function noop() {
var self = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var opts = args[args.length - 1];
self.dbg.apply(self, [opts.op].concat(args));
return resolve();
};
var noop2 = function noop2() {
var self = this;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var opts = args[args.length - 2];
self.dbg.apply(self, [opts.op].concat(args));
return resolve();
};
function isValidString(value) {
return value != null && value !== '';
}
function join(items, separator) {
separator || (separator = '');
return items.filter(isValidString).join(separator);
}
function makePath() {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var result = join(args, '/');
return result.replace(/([^:\/]|^)\/{2,}/g, '$1/');
}
function encode(val) {
return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');
}
function buildUrl(url, params) {
if (!params) {
return url;
}
var parts = [];
forOwn(params, function (val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (!isArray(val)) {
val = [val];
}
val.forEach(function (v) {
if (window.toString.call(v) === '[object Date]') {
v = v.toISOString();
} else if (isObject(v)) {
v = toJson(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
if (parts.length > 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
}
return url;
}
var __super__ = _jsDataAdapter2.default.prototype;
var DEFAULTS = {
// Default and user-defined settings
/**
* @name HttpAdapter#basePath
* @type {string}
*/
basePath: '',
/**
* @name HttpAdapter#forceTrailingSlash
* @type {boolean}
* @default false
*/
forceTrailingSlash: false,
/**
* @name HttpAdapter#http
* @type {Function}
*/
http: axios,
/**
* @name HttpAdapter#httpConfig
* @type {Object}
*/
httpConfig: {},
/**
* @name HttpAdapter#suffix
* @type {string}
*/
suffix: '',
/**
* @name HttpAdapter#useFetch
* @type {boolean}
* @default false
*/
useFetch: false
};
/**
* HttpAdapter class.
*
* @class HttpAdapter
* @param {Object} [opts] Configuration options.
* @param {string} [opts.basePath=''] TODO
* @param {boolean} [opts.debug=false] TODO
* @param {boolean} [opts.forceTrailingSlash=false] TODO
* @param {Object} [opts.http=axios] TODO
* @param {Object} [opts.httpConfig={}] TODO
* @param {string} [opts.suffix=''] TODO
* @param {boolean} [opts.useFetch=false] TODO
*/
function HttpAdapter(opts) {
var self = this;
opts || (opts = {});
fillIn(opts, DEFAULTS);
_jsDataAdapter2.default.call(self, opts);
}
// Setup prototype inheritance from Adapter
HttpAdapter.prototype = Object.create(_jsDataAdapter2.default.prototype, {
constructor: {
value: HttpAdapter,
enumerable: false,
writable: true,
configurable: true
}
});
Object.defineProperty(HttpAdapter, '__super__', {
configurable: true,
value: _jsDataAdapter2.default
});
addHiddenPropsToTarget(HttpAdapter.prototype, {
/**
* @name HttpAdapter#afterDEL
* @method
* @param {string} url
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterDEL: noop2,
/**
* @name HttpAdapter#afterGET
* @method
* @param {string} url
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterGET: noop2,
/**
* @name HttpAdapter#afterHTTP
* @method
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterHTTP: noop2,
/**
* @name HttpAdapter#afterPOST
* @method
* @param {string} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterPOST: noop2,
/**
* @name HttpAdapter#afterPUT
* @method
* @param {string} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
* @param {Object} response
*/
afterPUT: noop2,
/**
* @name HttpAdapter#beforeDEL
* @method
* @param {Object} url
* @param {Object} config
* @param {Object} opts
*/
beforeDEL: noop,
/**
* @name HttpAdapter#beforeGET
* @method
* @param {Object} url
* @param {Object} config
* @param {Object} opts
*/
beforeGET: noop,
/**
* @name HttpAdapter#beforeHTTP
* @method
* @param {Object} config
* @param {Object} opts
*/
beforeHTTP: noop,
/**
* @name HttpAdapter#beforePOST
* @method
* @param {Object} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
*/
beforePOST: noop,
/**
* @name HttpAdapter#beforePUT
* @method
* @param {Object} url
* @param {Object} data
* @param {Object} config
* @param {Object} opts
*/
beforePUT: noop,
_create: function _create(mapper, props, opts) {
var self = this;
return self.POST(self.getPath('create', mapper, props, opts), self.serialize(mapper, props, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_createMany: function _createMany(mapper, props, opts) {
var self = this;
return self.POST(self.getPath('createMany', mapper, null, opts), self.serialize(mapper, props, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_destroy: function _destroy(mapper, id, opts) {
var self = this;
return self.DEL(self.getPath('destroy', mapper, id, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_destroyAll: function _destroyAll(mapper, query, opts) {
var self = this;
return self.DEL(self.getPath('destroyAll', mapper, null, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_end: function _end(mapper, opts, response) {
return [this.deserialize(mapper, response.data, opts), response];
},
_find: function _find(mapper, id, opts) {
var self = this;
return self.GET(self.getPath('find', mapper, id, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_findAll: function _findAll(mapper, query, opts) {
var self = this;
return self.GET(self.getPath('findAll', mapper, opts.params, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_update: function _update(mapper, id, props, opts) {
var self = this;
return self.PUT(self.getPath('update', mapper, id, opts), self.serialize(mapper, props, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_updateAll: function _updateAll(mapper, props, query, opts) {
var self = this;
return self.PUT(self.getPath('updateAll', mapper, null, opts), self.serialize(mapper, props, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
_updateMany: function _updateMany(mapper, records, opts) {
var self = this;
return self.PUT(self.getPath('updateMany', mapper, null, opts), self.serialize(mapper, records, opts), opts).then(function (response) {
return self._end(mapper, opts, response);
});
},
/**
* Create a new the record from the provided `props`.
*
* @name HttpAdapter#create
* @method
* @param {Object} mapper The mapper.
* @param {Object} props Properties to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
create: function create(mapper, props, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.create.call(self, mapper, props, opts);
},
/**
* Create multiple new records in batch.
*
* @name HttpAdapter#createMany
* @method
* @param {Object} mapper The mapper.
* @param {Array} props Array of property objects to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
createMany: function createMany(mapper, props, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.createMany.call(self, mapper, props, opts);
},
/**
* Make an Http request to `url` according to the configuration in `config`.
*
* @name HttpAdapter#DEL
* @method
* @param {string} url Url for the request.
* @param {Object} [config] Http configuration that will be passed to
* {@link HttpAdapter#HTTP}.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
DEL: function DEL(url, config, opts) {
var self = this;
var op = void 0;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.method = config.method || 'delete';
// beforeDEL lifecycle hook
op = opts.op = 'beforeDEL';
return resolve(self[op](url, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'DEL';
self.dbg(op, url, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterDEL lifecycle hook
op = opts.op = 'afterDEL';
return resolve(self[op](url, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Transform the server response object into the payload that will be returned
* to JSData.
*
* @name HttpAdapter#deserialize
* @method
* @param {Object} mapper The mapper used for the operation.
* @param {Object} response Response object from {@link HttpAdapter#HTTP}.
* @param {Object} opts Configuration options.
* @return {(Object|Array)} Deserialized data.
*/
deserialize: function deserialize(mapper, response, opts) {
opts || (opts = {});
if (isFunction(opts.deserialize)) {
return opts.deserialize(mapper, response, opts);
}
if (isFunction(mapper.deserialize)) {
return mapper.deserialize(mapper, response, opts);
}
if (response) {
if (response.hasOwnProperty('data')) {
return response.data;
}
}
return response;
},
/**
* Destroy the record with the given primary key.
*
* @name HttpAdapter#destroy
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to destroy.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
destroy: function destroy(mapper, id, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.destroy.call(self, mapper, id, opts);
},
/**
* Destroy the records that match the selection `query`.
*
* @name HttpAdapter#destroyAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} query Selection query.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
destroyAll: function destroyAll(mapper, query, opts) {
var self = this;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.destroyAll.call(self, mapper, query, opts);
},
/**
* Log an error.
*
* @name HttpAdapter#error
* @method
* @param {...*} [args] Arguments to log.
*/
error: function error() {
if (console) {
var _console;
(_console = console)[typeof console.error === 'function' ? 'error' : 'log'].apply(_console, arguments);
}
},
/**
* Make an Http request using `window.fetch`.
*
* @name HttpAdapter#fetch
* @method
* @param {Object} config Request configuration.
* @param {Object} config.data Payload for the request.
* @param {string} config.method Http method for the request.
* @param {Object} config.headers Headers for the request.
* @param {Object} config.params Querystring for the request.
* @param {string} config.url Url for the request.
* @param {Object} [opts] Configuration options.
*/
fetch: function (_fetch) {
function fetch(_x, _x2) {
return _fetch.apply(this, arguments);
}
fetch.toString = function () {
return _fetch.toString();
};
return fetch;
}(function (config, opts) {
var requestConfig = {
method: config.method,
// turn the plain headers object into the Fetch Headers object
headers: new Headers(config.headers)
};
if (config.data) {
requestConfig.body = toJson(config.data);
}
return fetch(new Request(buildUrl(config.url, config.params), requestConfig)).then(function (response) {
response.config = {
method: config.method,
url: config.url
};
return response.json().then(function (data) {
response.data = data;
return response;
});
});
}),
/**
* Retrieve the record with the given primary key.
*
* @name HttpAdapter#find
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to retrieve.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
find: function find(mapper, id, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.find.call(self, mapper, id, opts);
},
/**
* Retrieve the records that match the selection `query`.
*
* @name HttpAdapter#findAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} query Selection query.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
findAll: function findAll(mapper, query, opts) {
var self = this;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.suffix = self.getSuffix(mapper, opts);
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
return __super__.findAll.call(self, mapper, query, opts);
},
/**
* TODO
*
* @name HttpAdapter#GET
* @method
* @param {string} url The url for the request.
* @param {Object} config Request configuration options.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
GET: function GET(url, config, opts) {
var self = this;
var op = void 0;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.method = config.method || 'get';
// beforeGET lifecycle hook
op = opts.op = 'beforeGET';
return resolve(self[op](url, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'GET';
self.dbg(op, url, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterGET lifecycle hook
op = opts.op = 'afterGET';
return resolve(self[op](url, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* @name HttpAdapter#getEndpoint
* @method
* @param {Object} mapper TODO
* @param {*} id TODO
* @param {boolean} opts TODO
* @return {string} Full path.
*/
getEndpoint: function getEndpoint(mapper, id, opts) {
var self = this;
opts || (opts = {});
opts.params || (opts.params = {});
var relationList = mapper.relationList || [];
var endpoint = isUndefined(opts.endpoint) ? isUndefined(mapper.endpoint) ? mapper.name : mapper.endpoint : opts.endpoint;
relationList.forEach(function (def) {
if (def.type !== 'belongsTo' || !def.parent) {
return;
}
var item = void 0;
var parentKey = def.foreignKey;
var parentDef = def.getRelation();
var parentId = opts.params[parentKey];
if (parentId === false || !parentKey || !parentDef) {
if (parentId === false) {
delete opts.params[parentKey];
}
return false;
} else {
delete opts.params[parentKey];
if (isObject(id)) {
item = id;
}
if (item) {
parentId = parentId || def.getForeignKey(item) || (def.getLocalField(item) ? get(def.getLocalField(item), parentDef.idAttribute) : null);
}
if (parentId) {
var _ret = function () {
delete opts.endpoint;
var _opts = {};
forOwn(opts, function (value, key) {
_opts[key] = value;
});
_(_opts, parentDef);
endpoint = makePath(self.getEndpoint(parentDef, parentId, _opts), parentId, endpoint);
return {
v: false
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
}
});
return endpoint;
},
/**
* @name HttpAdapter#getPath
* @method
* @param {string} method TODO
* @param {Object} mapper TODO
* @param {(string|number)?} id TODO
* @param {Object} opts Configuration options.
*/
getPath: function getPath(method, mapper, id, opts) {
var self = this;
opts || (opts = {});
var args = [isUndefined(opts.basePath) ? isUndefined(mapper.basePath) ? self.basePath : mapper.basePath : opts.basePath, self.getEndpoint(mapper, isString(id) || isNumber(id) || method === 'create' ? id : null, opts)];
if (method === 'find' || method === 'update' || method === 'destroy') {
args.push(id);
}
return makePath.apply(_jsData.utils, args);
},
getSuffix: function getSuffix(mapper, opts) {
opts || (opts = {});
if (isUndefined(opts.suffix)) {
if (isUndefined(mapper.suffix)) {
return this.suffix;
}
return mapper.suffix;
}
return opts.suffix;
},
/**
* Make an Http request.
*
* @name HttpAdapter#HTTP
* @method
* @param {Object} config Request configuration options.
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
HTTP: function HTTP(config, opts) {
var self = this;
var start = new Date();
opts || (opts = {});
config = copy(config);
config = deepMixIn(config, self.httpConfig);
if (self.forceTrailingSlash && config.url[config.url.length - 1] !== '/') {
config.url += '/';
}
config.method = config.method.toUpperCase();
var suffix = config.suffix || opts.suffix || self.suffix;
if (suffix && config.url.substr(config.url.length - suffix.length) !== suffix) {
config.url += suffix;
}
function logResponse(data) {
var str = start.toUTCString() + ' - ' + config.method.toUpperCase() + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms';
if (data.status >= 200 && data.status < 300) {
if (self.log) {
self.dbg('debug', str, data);
}
return data;
} else {
if (self.error) {
self.error('\'FAILED: ' + str, data);
}
return reject(data);
}
}
if (!self.http) {
throw new Error('You have not configured this adapter with an http library!');
}
return resolve(self.beforeHTTP(config, opts)).then(function (_config) {
config = _config || config;
if (hasFetch && (self.useFetch || opts.useFetch || !self.http)) {
return self.fetch(config, opts).then(logResponse, logResponse);
}
return self.http(config).then(logResponse, logResponse).catch(function (err) {
return self.responseError(err, config, opts);
});
}).then(function (response) {
return resolve(self.afterHTTP(config, opts, response)).then(function (_response) {
return _response || response;
});
});
},
/**
* TODO
*
* @name HttpAdapter#POST
* @method
* @param {*} url TODO
* @param {Object} data TODO
* @param {Object} config TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
POST: function POST(url, data, config, opts) {
var self = this;
var op = void 0;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.data = data || config.data;
config.method = config.method || 'post';
// beforePOST lifecycle hook
op = opts.op = 'beforePOST';
return resolve(self[op](url, data, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'POST';
self.dbg(op, url, data, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterPOST lifecycle hook
op = opts.op = 'afterPOST';
return resolve(self[op](url, data, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* TODO
*
* @name HttpAdapter#PUT
* @method
* @param {*} url TODO
* @param {Object} data TODO
* @param {Object} config TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
PUT: function PUT(url, data, config, opts) {
var self = this;
var op = void 0;
config || (config = {});
opts || (opts = {});
config.url = url || config.url;
config.data = data || config.data;
config.method = config.method || 'put';
// beforePUT lifecycle hook
op = opts.op = 'beforePUT';
return resolve(self[op](url, data, config, opts)).then(function (_config) {
// Allow re-assignment from lifecycle hook
config = isUndefined(_config) ? config : _config;
op = opts.op = 'PUT';
self.dbg(op, url, data, config, opts);
return self.HTTP(config, opts);
}).then(function (response) {
// afterPUT lifecycle hook
op = opts.op = 'afterPUT';
return resolve(self[op](url, data, config, opts, response)).then(function (_response) {
// Allow re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* TODO
*
* @name HttpAdapter#queryTransform
* @method
* @param {Object} mapper TODO
* @param {*} params TODO
* @param {*} opts TODO
* @return {*} Transformed params.
*/
queryTransform: function queryTransform(mapper, params, opts) {
opts || (opts = {});
if (isFunction(opts.queryTransform)) {
return opts.queryTransform(mapper, params, opts);
}
if (isFunction(mapper.queryTransform)) {
return mapper.queryTransform(mapper, params, opts);
}
return params;
},
/**
* Error handler invoked when the promise returned by {@link HttpAdapter#http}
* is rejected. Default implementation is to just return the error wrapped in
* a rejected Promise, aka rethrow the error. {@link HttpAdapter#http} is
* called by {@link HttpAdapter#HTTP}.
*
* @name HttpAdapter#responseError
* @method
* @param {*} err The error that {@link HttpAdapter#http} rejected with.
* @param {Object} config The `config` argument that was passed to {@link HttpAdapter#HTTP}.
* @param {*} opts The `opts` argument that was passed to {@link HttpAdapter#HTTP}.
* @return {Promise}
*/
responseError: function responseError(err, config, opts) {
return reject(err);
},
/**
* TODO
*
* @name HttpAdapter#serialize
* @method
* @param {Object} mapper TODO
* @param {Object} data TODO
* @param {*} opts TODO
* @return {*} Serialized data.
*/
serialize: function serialize(mapper, data, opts) {
opts || (opts = {});
if (isFunction(opts.serialize)) {
return opts.serialize(mapper, data, opts);
}
if (isFunction(mapper.serialize)) {
return mapper.serialize(mapper, data, opts);
}
return data;
},
/**
* TODO
*
* @name HttpAdapter#update
* @method
* @param {Object} mapper TODO
* @param {*} id TODO
* @param {*} props TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
update: function update(mapper, id, props, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.update.call(self, mapper, id, props, opts);
},
/**
* TODO
*
* @name HttpAdapter#updateAll
* @method
* @param {Object} mapper TODO
* @param {Object} props TODO
* @param {Object} query TODO
* @param {Object} [opts] Configuration options.
* @return {Promise}
*/
updateAll: function updateAll(mapper, props, query, opts) {
var self = this;
query || (query = {});
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
deepMixIn(opts.params, query);
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.updateAll.call(self, mapper, props, query, opts);
},
/**
* Update multiple records in batch.
*
* {@link HttpAdapter#beforeUpdateMany} will be called before calling
* {@link HttpAdapter#PUT}.
* {@link HttpAdapter#afterUpdateMany} will be called after calling
* {@link HttpAdapter#PUT}.
*
* @name HttpAdapter#updateMany
* @method
* @param {Object} mapper The mapper.
* @param {Array} records Array of property objects to send as the payload.
* @param {Object} [opts] Configuration options.
* @param {string} [opts.params] TODO
* @param {string} [opts.suffix={@link HttpAdapter#suffix}] TODO
* @return {Promise}
*/
updateMany: function updateMany(mapper, records, opts) {
var self = this;
opts = opts ? copy(opts) : {};
opts.params || (opts.params = {});
opts.params = self.queryTransform(mapper, opts.params, opts);
opts.suffix = self.getSuffix(mapper, opts);
return __super__.updateMany.call(self, mapper, records, opts);
}
});
/**
* Add an Http actions to a mapper.
*
* @name HttpAdapter.addAction
* @method
* @param {string} name Name of the new action.
* @param {Object} [opts] Action configuration
* @param {string} [opts.adapter]
* @param {string} [opts.pathname]
* @param {Function} [opts.request]
* @param {Function} [opts.response]
* @param {Function} [opts.responseError]
* @return {Function} Decoration function, which should be passed the mapper to
* decorate when invoked.
*/
HttpAdapter.addAction = function (name, opts) {
if (!name || !isString(name)) {
throw new TypeError('action(name[, opts]): Expected: string, Found: ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name)));
}
return function (mapper) {
if (mapper[name]) {
throw new Error('action(name[, opts]): ' + name + ' already exists on target!');
}
opts.request = opts.request || function (config) {
return config;
};
opts.response = opts.response || function (response) {
return response;
};
opts.responseError = opts.responseError || function (err) {
return reject(err);
};
mapper[name] = function (id, _opts) {
var self = this;
if (isObject(id)) {
_opts = id;
}
_opts = _opts || {};
var adapter = self.getAdapter(opts.adapter || self.defaultAdapter || 'http');
var config = {};
fillIn(config, opts);
if (!_opts.hasOwnProperty('endpoint') && config.endpoint) {
_opts.endpoint = config.endpoint;
}
if (typeof _opts.getEndpoint === 'function') {
config.url = _opts.getEndpoint(self, _opts);
} else {
var _args = [_opts.basePath || self.basePath || adapter.basePath, adapter.getEndpoint(self, isSorN(id) ? id : null, _opts)];
if (isSorN(id)) {
_args.push(id);
}
_args.push(opts.pathname || name);
config.url = makePath.apply(null, _args);
}
config.method = config.method || 'GET';
config.mapper = self.name;
deepMixIn(config)(_opts);
return resolve(config).then(_opts.request || opts.request).then(function (config) {
return adapter.HTTP(config);
}).then(function (data) {
if (data && data.config) {
data.config.mapper = self.name;
}
return data;
}).then(_opts.response || opts.response, _opts.responseError || opts.responseError);
};
return mapper;
};
};
/**
* Add multiple Http actions to a mapper. See {@link HttpAdapter.addAction} for
* action configuration options.
*
* @name HttpAdapter.addActions
* @method
* @param {Object.<string, Object>} opts Object where the key is an action name
* and the value is the configuration for the action.
* @return {Function} Decoration function, which should be passed the mapper to
* decorate when invoked.
*/
HttpAdapter.addActions = function (opts) {
opts || (opts = {});
return function (mapper) {
forOwn(mapper, function (value, key) {
HttpAdapter.addAction(key, value)(mapper);
});
return mapper;
};
};
/**
* Alternative to ES6 class syntax for extending `HttpAdapter`.
*
* __ES6__:
* ```javascript
* class MyHttpAdapter extends HttpAdapter {
* deserialize (Model, data, opts) {
* const data = super.deserialize(Model, data, opts)
* data.foo = 'bar'
* return data
* }
* }
* ```
*
* __ES5__:
* ```javascript
* var instanceProps = {
* // override deserialize
* deserialize: function (Model, data, opts) {
* var Ctor = this.constructor
* var superDeserialize = (Ctor.__super__ || Object.getPrototypeOf(Ctor)).deserialize
* // call the super deserialize
* var data = superDeserialize(Model, data, opts)
* data.foo = 'bar'
* return data
* },
* say: function () { return 'hi' }
* }
* var classProps = {
* yell: function () { return 'HI' }
* }
*
* var MyHttpAdapter = HttpAdapter.extend(instanceProps, classProps)
* var adapter = new MyHttpAdapter()
* adapter.say() // "hi"
* MyHttpAdapter.yell() // "HI"
* ```
*
* @name HttpAdapter.extend
* @method
* @param {Object} [instanceProps] Properties that will be added to the
* prototype of the subclass.
* @param {Object} [classProps] Properties that will be added as static
* properties to the subclass itself.
* @return {Object} Subclass of `HttpAdapter`.
*/
HttpAdapter.extend = extend;
/**
* Details of the current version of the `js-data-http` module.
*
* @name HttpAdapter.version
* @type {Object}
* @property {string} version.full The full semver value.
* @property {number} version.major The major version number.
* @property {number} version.minor The minor version number.
* @property {number} version.patch The patch version number.
* @property {(string|boolean)} version.alpha The alpha version value,
* otherwise `false` if the current version is not alpha.
* @property {(string|boolean)} version.beta The beta version value,
* otherwise `false` if the current version is not beta.
*/
HttpAdapter.version = {
full: '3.0.0-alpha.7',
major: parseInt('3', 10),
minor: parseInt('0', 10),
patch: parseInt('0', 10),
alpha: true ? '7' : false,
beta: true ? 'false' : false
};
/**
* Registered as `js-data-http` in NPM and Bower. The build of `js-data-http`
* that works on Node.js is registered in NPM as `js-data-http-node`. The build
* of `js-data-http` that does not bundle `axios` is registered in NPM and Bower
* as `js-data-fetch`.
*
* __Script tag__:
* ```javascript
* window.HttpAdapter
* ```
* __CommonJS__:
* ```javascript
* var HttpAdapter = require('js-data-http')
* ```
* __ES6 Modules__:
* ```javascript
* import HttpAdapter from 'js-data-http'
* ```
* __AMD__:
* ```javascript
* define('myApp', ['js-data-http'], function (HttpAdapter) { ... })
* ```
*
* @module js-data-http
*/
module.exports = HttpAdapter;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
(function (global, factory) {
true ? factory(__webpack_require__(1)) :
typeof define === 'function' && define.amd ? define('js-data-adapter', ['js-data'], factory) :
(factory(global.JSData));
}(this, function (jsData) { '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.defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
babelHelpers.slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
babelHelpers;
var addHiddenPropsToTarget = jsData.utils.addHiddenPropsToTarget;
var extend = jsData.utils.extend;
var fillIn = jsData.utils.fillIn;
var forEachRelation = jsData.utils.forEachRelation;
var get = jsData.utils.get;
var isArray = jsData.utils.isArray;
var isObject = jsData.utils.isObject;
var isUndefined = jsData.utils.isUndefined;
var omit = jsData.utils.omit;
var plainCopy = jsData.utils.plainCopy;
var resolve = jsData.utils.resolve;
var noop = function noop() {
var self = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var opts = args[args.length - 1];
self.dbg.apply(self, [opts.op].concat(args));
return resolve();
};
var noop2 = function noop2() {
var self = this;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var opts = args[args.length - 2];
self.dbg.apply(self, [opts.op].concat(args));
return resolve();
};
var unique = function unique(array) {
var seen = {};
var final = [];
array.forEach(function (item) {
if (item in seen) {
return;
}
final.push(item);
seen[item] = 0;
});
return final;
};
var withoutRelations = function withoutRelations(mapper, props) {
return omit(props, mapper.relationFields || []);
};
var DEFAULTS = {
/**
* Whether to log debugging information.
*
* @name Adapter#debug
* @type {boolean}
* @default false
*/
debug: false,
/**
* Whether to return a more detailed response object.
*
* @name Adapter#raw
* @type {boolean}
* @default false
*/
raw: false
};
/**
* Abstract class meant to be extended by adapters.
*
* @class Adapter
* @abstract
* @param {Object} [opts] Configuration opts.
* @param {boolean} [opts.debug=false] Whether to log debugging information.
* @param {boolean} [opts.raw=false] Whether to return a more detailed response
* object.
*/
function Adapter(opts) {
var self = this;
opts || (opts = {});
fillIn(opts, DEFAULTS);
fillIn(self, opts);
}
Adapter.reserved = ['orderBy', 'sort', 'limit', 'offset', 'skip', 'where'];
/**
* Response object used when `raw` is `true`. May contain other fields in
* addition to `data`.
*
* @typedef {Object} Response
* @property {Object} data Response data.
* @property {string} op The operation for which the response was created.
*/
function Response(data, meta, op) {
var self = this;
meta || (meta = {});
self.data = data;
fillIn(self, meta);
self.op = op;
}
Adapter.Response = Response;
/**
* Alternative to ES6 class syntax for extending `Adapter`.
*
* @name Adapter.extend
* @method
* @param {Object} [instanceProps] Properties that will be added to the
* prototype of the subclass.
* @param {Object} [classProps] Properties that will be added as static
* properties to the subclass itself.
* @return {Object} Subclass of `Adapter`.
*/
Adapter.extend = extend;
addHiddenPropsToTarget(Adapter.prototype, {
/**
* Lifecycle method method called by <a href="#create__anchor">create</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#create__anchor">create</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the created record.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#create__anchor">create</a>.
*
* @name Adapter#afterCreate
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#create__anchor">create</a>.
* @param {Object} props The `props` argument passed to <a href="#create__anchor">create</a>.
* @param {Object} opts The `opts` argument passed to <a href="#create__anchor">create</a>.
* @property {string} opts.op `afterCreate`
* @param {Object|Response} response Created record or {@link Response}, depending on the value of `opts.raw`.
*/
afterCreate: noop2,
/**
* Lifecycle method method called by <a href="#createMany__anchor">createMany</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#createMany__anchor">createMany</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the created records.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#createMany__anchor">createMany</a>.
*
* @name Adapter#afterCreate
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#createMany__anchor">createMany</a>.
* @param {Object[]} props The `props` argument passed to <a href="#createMany__anchor">createMany</a>.
* @param {Object} opts The `opts` argument passed to <a href="#createMany__anchor">createMany</a>.
* @property {string} opts.op `afterCreateMany`
* @param {Object[]|Response} response Created records or {@link Response}, depending on the value of `opts.raw`.
*/
afterCreateMany: noop2,
/**
* Lifecycle method method called by <a href="#destroy__anchor">destroy</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#destroy__anchor">destroy</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be `undefined`.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#destroy__anchor">destroy</a>.
*
* @name Adapter#afterDestroy
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#destroy__anchor">destroy</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#destroy__anchor">destroy</a>.
* @param {Object} opts The `opts` argument passed to <a href="#destroy__anchor">destroy</a>.
* @property {string} opts.op `afterDestroy`
* @param {undefined|Response} response `undefined` or {@link Response}, depending on the value of `opts.raw`.
*/
afterDestroy: noop2,
/**
* Lifecycle method method called by <a href="#destroyAll__anchor">destroyAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#destroyAll__anchor">destroyAll</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be `undefined`.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#destroyAll__anchor">destroyAll</a>.
*
* @name Adapter#afterDestroyAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @param {Object} query The `query` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @property {string} opts.op `afterDestroyAll`
* @param {undefined|Response} response `undefined` or {@link Response}, depending on the value of `opts.raw`.
*/
afterDestroyAll: noop2,
/**
* Lifecycle method method called by <a href="#find__anchor">find</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#find__anchor">find</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the found record, if any.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#find__anchor">find</a>.
*
* @name Adapter#afterFind
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#find__anchor">find</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#find__anchor">find</a>.
* @param {Object} opts The `opts` argument passed to <a href="#find__anchor">find</a>.
* @property {string} opts.op `afterFind`
* @param {Object|Response} response The found record or {@link Response}, depending on the value of `opts.raw`.
*/
afterFind: noop2,
/**
* Lifecycle method method called by <a href="#findAll__anchor">findAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#findAll__anchor">findAll</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the found records, if any.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#findAll__anchor">findAll</a>.
*
* @name Adapter#afterFindAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#findAll__anchor">findAll</a>.
* @param {Object} query The `query` argument passed to <a href="#findAll__anchor">findAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#findAll__anchor">findAll</a>.
* @property {string} opts.op `afterFindAll`
* @param {Object[]|Response} response The found records or {@link Response}, depending on the value of `opts.raw`.
*/
afterFindAll: noop2,
/**
* Lifecycle method method called by <a href="#update__anchor">update</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#update__anchor">update</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the updated record.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#update__anchor">update</a>.
*
* @name Adapter#afterUpdate
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#update__anchor">update</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#update__anchor">update</a>.
* @param {Object} props The `props` argument passed to <a href="#update__anchor">update</a>.
* @param {Object} opts The `opts` argument passed to <a href="#update__anchor">update</a>.
* @property {string} opts.op `afterUpdate`
* @param {Object|Response} response The updated record or {@link Response}, depending on the value of `opts.raw`.
*/
afterUpdate: noop2,
/**
* Lifecycle method method called by <a href="#updateAll__anchor">updateAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#updateAll__anchor">updateAll</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the updated records, if any.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#updateAll__anchor">updateAll</a>.
*
* @name Adapter#afterUpdateAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} props The `props` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} query The `query` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @property {string} opts.op `afterUpdateAll`
* @param {Object[]|Response} response The updated records or {@link Response}, depending on the value of `opts.raw`.
*/
afterUpdateAll: noop2,
/**
* Lifecycle method method called by <a href="#updateMany__anchor">updateMany</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#updateMany__anchor">updateMany</a> to wait for the Promise to resolve before continuing.
*
* If `opts.raw` is `true` then `response` will be a detailed response object, otherwise `response` will be the updated records, if any.
*
* `response` may be modified. You can also re-assign `response` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#updateMany__anchor">updateMany</a>.
*
* @name Adapter#afterUpdateMany
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @param {Object[]} records The `records` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @param {Object} opts The `opts` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @property {string} opts.op `afterUpdateMany`
* @param {Object[]|Response} response The updated records or {@link Response}, depending on the value of `opts.raw`.
*/
afterUpdateMany: noop2,
/**
* Lifecycle method method called by <a href="#create__anchor">create</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#create__anchor">create</a> to wait for the Promise to resolve before continuing.
*
* `props` may be modified. You can also re-assign `props` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#create__anchor">create</a>.
*
* @name Adapter#beforeCreate
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#create__anchor">create</a>.
* @param {Object} props The `props` argument passed to <a href="#create__anchor">create</a>.
* @param {Object} opts The `opts` argument passed to <a href="#create__anchor">create</a>.
* @property {string} opts.op `beforeCreate`
*/
beforeCreate: noop,
/**
* Lifecycle method method called by <a href="#createMany__anchor">createMany</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#createMany__anchor">createMany</a> to wait for the Promise to resolve before continuing.
*
* `props` may be modified. You can also re-assign `props` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#createMany__anchor">createMany</a>.
*
* @name Adapter#beforeCreateMany
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#createMany__anchor">createMany</a>.
* @param {Object[]} props The `props` argument passed to <a href="#createMany__anchor">createMany</a>.
* @param {Object} opts The `opts` argument passed to <a href="#createMany__anchor">createMany</a>.
* @property {string} opts.op `beforeCreateMany`
*/
beforeCreateMany: noop,
/**
* Lifecycle method method called by <a href="#destroy__anchor">destroy</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#destroy__anchor">destroy</a> to wait for the Promise to resolve before continuing.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#destroy__anchor">destroy</a>.
*
* @name Adapter#beforeDestroy
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#destroy__anchor">destroy</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#destroy__anchor">destroy</a>.
* @param {Object} opts The `opts` argument passed to <a href="#destroy__anchor">destroy</a>.
* @property {string} opts.op `beforeDestroy`
*/
beforeDestroy: noop,
/**
* Lifecycle method method called by <a href="#destroyAll__anchor">destroyAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#destroyAll__anchor">destroyAll</a> to wait for the Promise to resolve before continuing.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#destroyAll__anchor">destroyAll</a>.
*
* @name Adapter#beforeDestroyAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @param {Object} query The `query` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#destroyAll__anchor">destroyAll</a>.
* @property {string} opts.op `beforeDestroyAll`
*/
beforeDestroyAll: noop,
/**
* Lifecycle method method called by <a href="#find__anchor">find</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#find__anchor">find</a> to wait for the Promise to resolve before continuing.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#find__anchor">find</a>.
*
* @name Adapter#beforeFind
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#find__anchor">find</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#find__anchor">find</a>.
* @param {Object} opts The `opts` argument passed to <a href="#find__anchor">find</a>.
* @property {string} opts.op `beforeFind`
*/
beforeFind: noop,
/**
* Lifecycle method method called by <a href="#findAll__anchor">findAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#findAll__anchor">findAll</a> to wait for the Promise to resolve before continuing.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#findAll__anchor">findAll</a>.
*
* @name Adapter#beforeFindAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#findAll__anchor">findAll</a>.
* @param {Object} query The `query` argument passed to <a href="#findAll__anchor">findAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#findAll__anchor">findAll</a>.
* @property {string} opts.op `beforeFindAll`
*/
beforeFindAll: noop,
/**
* Lifecycle method method called by <a href="#update__anchor">update</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#update__anchor">update</a> to wait for the Promise to resolve before continuing.
*
* `props` may be modified. You can also re-assign `props` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#update__anchor">update</a>.
*
* @name Adapter#beforeUpdate
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#update__anchor">update</a>.
* @param {(string|number)} id The `id` argument passed to <a href="#update__anchor">update</a>.
* @param {Object} props The `props` argument passed to <a href="#update__anchor">update</a>.
* @param {Object} opts The `opts` argument passed to <a href="#update__anchor">update</a>.
* @property {string} opts.op `beforeUpdate`
*/
beforeUpdate: noop,
/**
* Lifecycle method method called by <a href="#updateAll__anchor">updateAll</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#updateAll__anchor">updateAll</a> to wait for the Promise to resolve before continuing.
*
* `props` may be modified. You can also re-assign `props` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#updateAll__anchor">updateAll</a>.
*
* @name Adapter#beforeUpdateAll
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} props The `props` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} query The `query` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @param {Object} opts The `opts` argument passed to <a href="#updateAll__anchor">updateAll</a>.
* @property {string} opts.op `beforeUpdateAll`
*/
beforeUpdateAll: noop,
/**
* Lifecycle method method called by <a href="#updateMany__anchor">updateMany</a>.
*
* Override this method to add custom behavior for this lifecycle hook.
*
* Returning a Promise causes <a href="#updateMany__anchor">updateMany</a> to wait for the Promise to resolve before continuing.
*
* `props` may be modified. You can also re-assign `props` to another value by returning a different value or a Promise that resolves to a different value.
*
* A thrown error or rejected Promise will bubble up and reject the Promise returned by <a href="#updateMany__anchor">updateMany</a>.
*
* @name Adapter#beforeUpdateMany
* @method
* @param {Object} mapper The `mapper` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @param {Object[]} props The `props` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @param {Object} opts The `opts` argument passed to <a href="#updateMany__anchor">updateMany</a>.
* @property {string} opts.op `beforeUpdateMany`
*/
beforeUpdateMany: noop,
/**
* Shortcut for `#log('debug'[, arg1[, arg2[, argn]]])`.
*
* @name Adapter#dbg
* @method
*/
dbg: function dbg() {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
this.log.apply(this, ['debug'].concat(args));
},
/**
* Create a new record. Called by `Mapper#create`.
*
* @name Adapter#create
* @method
* @param {Object} mapper The mapper.
* @param {Object} props The record to be created.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
create: function create(mapper, props, opts) {
var self = this;
var op = void 0;
props || (props = {});
opts || (opts = {});
// beforeCreate lifecycle hook
op = opts.op = 'beforeCreate';
return resolve(self[op](mapper, props, opts)).then(function (_props) {
// Allow for re-assignment from lifecycle hook
props = isUndefined(_props) ? props : _props;
props = withoutRelations(mapper, props);
op = opts.op = 'create';
self.dbg(op, mapper, props, opts);
return resolve(self._create(mapper, props, opts));
}).then(function (results) {
var _results = babelHelpers.slicedToArray(results, 2);
var data = _results[0];
var result = _results[1];
result || (result = {});
var response = new Response(data, result, 'create');
response.created = data ? 1 : 0;
response = self.respond(response, opts);
// afterCreate lifecycle hook
op = opts.op = 'afterCreate';
return resolve(self[op](mapper, props, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Create multiple records in a single batch. Called by `Mapper#createMany`.
*
* @name Adapter#createMany
* @method
* @param {Object} mapper The mapper.
* @param {Object} props The records to be created.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
createMany: function createMany(mapper, props, opts) {
var self = this;
var op = void 0;
props || (props = {});
opts || (opts = {});
// beforeCreateMany lifecycle hook
op = opts.op = 'beforeCreateMany';
return resolve(self[op](mapper, props, opts)).then(function (_props) {
// Allow for re-assignment from lifecycle hook
props = isUndefined(_props) ? props : _props;
props = props.map(function (record) {
return withoutRelations(mapper, record);
});
op = opts.op = 'createMany';
self.dbg(op, mapper, props, opts);
return resolve(self._createMany(mapper, props, opts));
}).then(function (results) {
var _results2 = babelHelpers.slicedToArray(results, 2);
var data = _results2[0];
var result = _results2[1];
data || (data = []);
result || (result = {});
var response = new Response(data, result, 'createMany');
response.created = data.length;
response = self.respond(response, opts);
// afterCreateMany lifecycle hook
op = opts.op = 'afterCreateMany';
return resolve(self[op](mapper, props, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Destroy the record with the given primary key. Called by
* `Mapper#destroy`.
*
* @name Adapter#destroy
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to destroy.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
destroy: function destroy(mapper, id, opts) {
var self = this;
var op = void 0;
opts || (opts = {});
// beforeDestroy lifecycle hook
op = opts.op = 'beforeDestroy';
return resolve(self[op](mapper, id, opts)).then(function () {
op = opts.op = 'destroy';
self.dbg(op, mapper, id, opts);
return resolve(self._destroy(mapper, id, opts));
}).then(function (results) {
var _results3 = babelHelpers.slicedToArray(results, 2);
var data = _results3[0];
var result = _results3[1];
result || (result = {});
var response = new Response(data, result, 'destroy');
response = self.respond(response, opts);
// afterDestroy lifecycle hook
op = opts.op = 'afterDestroy';
return resolve(self[op](mapper, id, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Destroy the records that match the selection query. Called by
* `Mapper#destroyAll`.
*
* @name Adapter#destroyAll
* @method
* @param {Object} mapper the mapper.
* @param {Object} [query] Selection query.
* @param {Object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
destroyAll: function destroyAll(mapper, query, opts) {
var self = this;
var op = void 0;
query || (query = {});
opts || (opts = {});
// beforeDestroyAll lifecycle hook
op = opts.op = 'beforeDestroyAll';
return resolve(self[op](mapper, query, opts)).then(function () {
op = opts.op = 'destroyAll';
self.dbg(op, mapper, query, opts);
return resolve(self._destroyAll(mapper, query, opts));
}).then(function (results) {
var _results4 = babelHelpers.slicedToArray(results, 2);
var data = _results4[0];
var result = _results4[1];
result || (result = {});
var response = new Response(data, result, 'destroyAll');
response = self.respond(response, opts);
// afterDestroyAll lifecycle hook
op = opts.op = 'afterDestroyAll';
return resolve(self[op](mapper, query, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Return the foreignKey from the given record for the provided relationship.
*
* There may be reasons why you may want to override this method, like when
* the id of the parent doesn't exactly match up to the key on the child.
*
* Override with care.
*
* @name Adapter#makeHasManyForeignKey
* @method
* @return {*}
*/
makeHasManyForeignKey: function makeHasManyForeignKey(mapper, def, record) {
return def.getForeignKey(record);
},
/**
* Return the localKeys from the given record for the provided relationship.
*
* Override with care.
*
* @name Adapter#makeHasManyLocalKeys
* @method
* @return {*}
*/
makeHasManyLocalKeys: function makeHasManyLocalKeys(mapper, def, record) {
var localKeys = [];
var itemKeys = get(record, def.localKeys) || [];
itemKeys = isArray(itemKeys) ? itemKeys : Object.keys(itemKeys);
localKeys = localKeys.concat(itemKeys);
return unique(localKeys).filter(function (x) {
return x;
});
},
/**
* Return the foreignKeys from the given record for the provided relationship.
*
* Override with care.
*
* @name Adapter#makeHasManyForeignKeys
* @method
* @return {*}
*/
makeHasManyForeignKeys: function makeHasManyForeignKeys(mapper, def, record) {
return get(record, mapper.idAttribute);
},
/**
* Load a hasMany relationship.
*
* Override with care.
*
* @name Adapter#loadHasMany
* @method
* @return {Promise}
*/
loadHasMany: function loadHasMany(mapper, def, records, __opts) {
var self = this;
var singular = false;
if (isObject(records) && !isArray(records)) {
singular = true;
records = [records];
}
var IDs = records.map(function (record) {
return self.makeHasManyForeignKey(mapper, def, record);
});
var query = {
where: {}
};
var criteria = query.where[def.foreignKey] = {};
if (singular) {
// more efficient query when we only have one record
criteria['=='] = IDs[0];
} else {
criteria['in'] = IDs.filter(function (id) {
return id;
});
}
return self.findAll(def.getRelation(), query, __opts).then(function (relatedItems) {
records.forEach(function (record) {
var attached = [];
// avoid unneccesary iteration when we only have one record
if (singular) {
attached = relatedItems;
} else {
relatedItems.forEach(function (relatedItem) {
if (get(relatedItem, def.foreignKey) === record[mapper.idAttribute]) {
attached.push(relatedItem);
}
});
}
def.setLocalField(record, attached);
});
});
},
loadHasManyLocalKeys: function loadHasManyLocalKeys(mapper, def, records, __opts) {
var self = this;
var record = void 0;
var relatedMapper = def.getRelation();
if (isObject(records) && !isArray(records)) {
record = records;
}
if (record) {
return self.findAll(relatedMapper, {
where: babelHelpers.defineProperty({}, relatedMapper.idAttribute, {
'in': self.makeHasManyLocalKeys(mapper, def, record)
})
}, __opts).then(function (relatedItems) {
def.setLocalField(record, relatedItems);
});
} else {
var _ret = function () {
var localKeys = [];
records.forEach(function (record) {
localKeys = localKeys.concat(self.self.makeHasManyLocalKeys(mapper, def, record));
});
return {
v: self.findAll(relatedMapper, {
where: babelHelpers.defineProperty({}, relatedMapper.idAttribute, {
'in': unique(localKeys).filter(function (x) {
return x;
})
})
}, __opts).then(function (relatedItems) {
records.forEach(function (item) {
var attached = [];
var itemKeys = get(item, def.localKeys) || [];
itemKeys = isArray(itemKeys) ? itemKeys : Object.keys(itemKeys);
relatedItems.forEach(function (relatedItem) {
if (itemKeys && itemKeys.indexOf(relatedItem[relatedMapper.idAttribute]) !== -1) {
attached.push(relatedItem);
}
});
def.setLocalField(item, attached);
});
return relatedItems;
})
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : babelHelpers.typeof(_ret)) === "object") return _ret.v;
}
},
loadHasManyForeignKeys: function loadHasManyForeignKeys(mapper, def, records, __opts) {
var self = this;
var relatedMapper = def.getRelation();
var idAttribute = mapper.idAttribute;
var record = void 0;
if (isObject(records) && !isArray(records)) {
record = records;
}
if (record) {
return self.findAll(def.getRelation(), {
where: babelHelpers.defineProperty({}, def.foreignKeys, {
'contains': self.makeHasManyForeignKeys(mapper, def, record)
})
}, __opts).then(function (relatedItems) {
def.setLocalField(record, relatedItems);
});
} else {
return self.findAll(relatedMapper, {
where: babelHelpers.defineProperty({}, def.foreignKeys, {
'isectNotEmpty': records.map(function (record) {
return self.makeHasManyForeignKeys(mapper, def, record);
})
})
}, __opts).then(function (relatedItems) {
var foreignKeysField = def.foreignKeys;
records.forEach(function (record) {
var _relatedItems = [];
var id = get(record, idAttribute);
relatedItems.forEach(function (relatedItem) {
var foreignKeys = get(relatedItems, foreignKeysField) || [];
if (foreignKeys.indexOf(id) !== -1) {
_relatedItems.push(relatedItem);
}
});
def.setLocalField(record, _relatedItems);
});
});
}
},
/**
* Load a hasOne relationship.
*
* Override with care.
*
* @name Adapter#loadHasOne
* @method
* @return {Promise}
*/
loadHasOne: function loadHasOne(mapper, def, records, __opts) {
if (isObject(records) && !isArray(records)) {
records = [records];
}
return this.loadHasMany(mapper, def, records, __opts).then(function () {
records.forEach(function (record) {
var relatedData = def.getLocalField(record);
if (isArray(relatedData) && relatedData.length) {
def.setLocalField(record, relatedData[0]);
}
});
});
},
/**
* Return the foreignKey from the given record for the provided relationship.
*
* Override with care.
*
* @name Adapter#makeBelongsToForeignKey
* @method
* @return {*}
*/
makeBelongsToForeignKey: function makeBelongsToForeignKey(mapper, def, record) {
return def.getForeignKey(record);
},
/**
* Load a belongsTo relationship.
*
* Override with care.
*
* @name Adapter#loadBelongsTo
* @method
* @return {Promise}
*/
loadBelongsTo: function loadBelongsTo(mapper, def, records, __opts) {
var self = this;
var relationDef = def.getRelation();
if (isObject(records) && !isArray(records)) {
var _ret2 = function () {
var record = records;
return {
v: self.find(relationDef, self.makeBelongsToForeignKey(mapper, def, record), __opts).then(function (relatedItem) {
def.setLocalField(record, relatedItem);
})
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : babelHelpers.typeof(_ret2)) === "object") return _ret2.v;
} else {
var keys = records.map(function (record) {
return self.makeBelongsToForeignKey(mapper, def, record);
}).filter(function (key) {
return key;
});
return self.findAll(relationDef, {
where: babelHelpers.defineProperty({}, relationDef.idAttribute, {
'in': keys
})
}, __opts).then(function (relatedItems) {
records.forEach(function (record) {
relatedItems.forEach(function (relatedItem) {
if (relatedItem[relationDef.idAttribute] === record[def.foreignKey]) {
def.setLocalField(record, relatedItem);
}
});
});
});
}
},
/**
* Retrieve the record with the given primary key. Called by `Mapper#find`.
*
* @name Adapter#find
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to retrieve.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {string[]} [opts.with=[]] Relations to eager load.
* @return {Promise}
*/
find: function find(mapper, id, opts) {
var self = this;
var record = void 0,
op = void 0;
opts || (opts = {});
opts.with || (opts.with = []);
// beforeFind lifecycle hook
op = opts.op = 'beforeFind';
return resolve(self[op](mapper, id, opts)).then(function () {
op = opts.op = 'find';
self.dbg(op, mapper, id, opts);
return resolve(self._find(mapper, id, opts));
}).then(function (results) {
var _results5 = babelHelpers.slicedToArray(results, 1);
var _record = _results5[0];
if (!_record) {
return;
}
record = _record;
var tasks = [];
forEachRelation(mapper, opts, function (def, __opts) {
var task = void 0;
if (def.foreignKey && (def.type === 'hasOne' || def.type === 'hasMany')) {
if (def.type === 'hasOne') {
task = self.loadHasOne(mapper, def, record, __opts);
} else {
task = self.loadHasMany(mapper, def, record, __opts);
}
} else if (def.type === 'hasMany' && def.localKeys) {
task = self.loadHasManyLocalKeys(mapper, def, record, __opts);
} else if (def.type === 'hasMany' && def.foreignKeys) {
task = self.loadHasManyForeignKeys(mapper, def, record, __opts);
} else if (def.type === 'belongsTo') {
task = self.loadBelongsTo(mapper, def, record, __opts);
}
if (task) {
tasks.push(task);
}
});
return Promise.all(tasks);
}).then(function () {
var response = new Response(record, {}, 'find');
response.found = record ? 1 : 0;
response = self.respond(response, opts);
// afterFind lifecycle hook
op = opts.op = 'afterFind';
return resolve(self[op](mapper, id, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Retrieve the records that match the selection query.
*
* @name Adapter#findAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} [query] Selection query.
* @param {Object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {string[]} [opts.with=[]] Relations to eager load.
* @return {Promise}
*/
findAll: function findAll(mapper, query, opts) {
var self = this;
opts || (opts = {});
opts.with || (opts.with = []);
var records = [];
var op = void 0;
// beforeFindAll lifecycle hook
op = opts.op = 'beforeFindAll';
return resolve(self[op](mapper, query, opts)).then(function () {
op = opts.op = 'findAll';
self.dbg(op, mapper, query, opts);
return resolve(self._findAll(mapper, query, opts));
}).then(function (results) {
var _results6 = babelHelpers.slicedToArray(results, 1);
var _records = _results6[0];
_records || (_records = []);
records = _records;
var tasks = [];
forEachRelation(mapper, opts, function (def, __opts) {
var task = void 0;
if (def.foreignKey && (def.type === 'hasOne' || def.type === 'hasMany')) {
if (def.type === 'hasMany') {
task = self.loadHasMany(mapper, def, records, __opts);
} else {
task = self.loadHasOne(mapper, def, records, __opts);
}
} else if (def.type === 'hasMany' && def.localKeys) {
task = self.loadHasManyLocalKeys(mapper, def, records, __opts);
} else if (def.type === 'hasMany' && def.foreignKeys) {
task = self.loadHasManyForeignKeys(mapper, def, records, __opts);
} else if (def.type === 'belongsTo') {
task = self.loadBelongsTo(mapper, def, records, __opts);
}
if (task) {
tasks.push(task);
}
});
return Promise.all(tasks);
}).then(function () {
var response = new Response(records, {}, 'findAll');
response.found = records.length;
response = self.respond(response, opts);
// afterFindAll lifecycle hook
op = opts.op = 'afterFindAll';
return resolve(self[op](mapper, query, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Resolve the value of the specified option based on the given options and
* this adapter's settings. Override with care.
*
* @name Adapter#getOpt
* @method
* @param {string} opt The name of the option.
* @param {Object} [opts] Configuration options.
* @return {*} The value of the specified option.
*/
getOpt: function getOpt(opt, opts) {
opts || (opts = {});
return isUndefined(opts[opt]) ? plainCopy(this[opt]) : plainCopy(opts[opt]);
},
/**
* Logging utility method. Override this method if you want to send log
* messages to something other than the console.
*
* @name Adapter#log
* @method
* @param {string} level Log level.
* @param {...*} values Values to log.
*/
log: function log(level) {
for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
if (level && !args.length) {
args.push(level);
level = 'debug';
}
if (level === 'debug' && !this.debug) {
return;
}
var prefix = level.toUpperCase() + ': (Adapter)';
if (console[level]) {
var _console;
(_console = console)[level].apply(_console, [prefix].concat(args));
} else {
var _console2;
(_console2 = console).log.apply(_console2, [prefix].concat(args));
}
},
/**
* @name Adapter#respond
* @method
* @param {Object} response Response object.
* @param {Object} opts Configuration options.
* return {Object} If `opts.raw == true` then return `response`, else return
* `response.data`.
*/
respond: function respond(response, opts) {
return this.getOpt('raw', opts) ? response : response.data;
},
/**
* Apply the given update to the record with the specified primary key. Called
* by `Mapper#update`.
*
* @name Adapter#update
* @method
* @param {Object} mapper The mapper.
* @param {(string|number)} id The primary key of the record to be updated.
* @param {Object} props The update to apply to the record.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
update: function update(mapper, id, props, opts) {
var self = this;
props || (props = {});
opts || (opts = {});
var op = void 0;
// beforeUpdate lifecycle hook
op = opts.op = 'beforeUpdate';
return resolve(self[op](mapper, id, props, opts)).then(function (_props) {
// Allow for re-assignment from lifecycle hook
props = isUndefined(_props) ? props : _props;
op = opts.op = 'update';
self.dbg(op, mapper, id, props, opts);
return resolve(self._update(mapper, id, props, opts));
}).then(function (results) {
var _results7 = babelHelpers.slicedToArray(results, 2);
var data = _results7[0];
var result = _results7[1];
result || (result = {});
var response = new Response(data, result, 'update');
response.updated = data ? 1 : 0;
response = self.respond(response, opts);
// afterUpdate lifecycle hook
op = opts.op = 'afterUpdate';
return resolve(self[op](mapper, id, props, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Apply the given update to all records that match the selection query.
* Called by `Mapper#updateAll`.
*
* @name Adapter#updateAll
* @method
* @param {Object} mapper The mapper.
* @param {Object} props The update to apply to the selected records.
* @param {Object} [query] Selection query.
* @param {Object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
updateAll: function updateAll(mapper, props, query, opts) {
var self = this;
props || (props = {});
query || (query = {});
opts || (opts = {});
var op = void 0;
// beforeUpdateAll lifecycle hook
op = opts.op = 'beforeUpdateAll';
return resolve(self[op](mapper, props, query, opts)).then(function (_props) {
// Allow for re-assignment from lifecycle hook
props = isUndefined(_props) ? props : _props;
op = opts.op = 'updateAll';
self.dbg(op, mapper, props, query, opts);
return resolve(self._updateAll(mapper, props, query, opts));
}).then(function (results) {
var _results8 = babelHelpers.slicedToArray(results, 2);
var data = _results8[0];
var result = _results8[1];
data || (data = []);
result || (result = {});
var response = new Response(data, result, 'updateAll');
response.updated = data.length;
response = self.respond(response, opts);
// afterUpdateAll lifecycle hook
op = opts.op = 'afterUpdateAll';
return resolve(self[op](mapper, props, query, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
},
/**
* Update the given records in a single batch. Called by `Mapper#updateMany`.
*
* @name Adapter#updateMany
* @method
* @param {Object} mapper The mapper.
* @param {Object[]} records The records to update.
* @param {Object} [opts] Configuration options.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @return {Promise}
*/
updateMany: function updateMany(mapper, records, opts) {
var self = this;
records || (records = []);
opts || (opts = {});
var op = void 0;
var idAttribute = mapper.idAttribute;
records = records.filter(function (record) {
return get(record, idAttribute);
});
// beforeUpdateMany lifecycle hook
op = opts.op = 'beforeUpdateMany';
return resolve(self[op](mapper, records, opts)).then(function (_records) {
// Allow for re-assignment from lifecycle hook
records = isUndefined(_records) ? records : _records;
records = records.map(function (record) {
return withoutRelations(mapper, record);
});
op = opts.op = 'updateMany';
self.dbg(op, mapper, records, opts);
return resolve(self._updateMany(mapper, records, opts));
}).then(function (results) {
var _results9 = babelHelpers.slicedToArray(results, 2);
var data = _results9[0];
var result = _results9[1];
data || (data = []);
result || (result = {});
var response = new Response(data, result, 'updateMany');
response.updated = data.length;
response = self.respond(response, opts);
// afterUpdateMany lifecycle hook
op = opts.op = 'afterUpdateMany';
return resolve(self[op](mapper, records, opts, response)).then(function (_response) {
// Allow for re-assignment from lifecycle hook
return isUndefined(_response) ? response : _response;
});
});
}
});
module.exports = Adapter;
}));
//# sourceMappingURL=js-data-adapter.js.map
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(4);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var defaults = __webpack_require__(5);
var utils = __webpack_require__(6);
var dispatchRequest = __webpack_require__(7);
var InterceptorManager = __webpack_require__(16);
var isAbsoluteURL = __webpack_require__(17);
var combineURLs = __webpack_require__(18);
var bind = __webpack_require__(19);
var transformData = __webpack_require__(12);
function Axios(defaultConfig) {
this.defaults = utils.merge({}, defaultConfig);
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = utils.merge({
url: arguments[0]
}, arguments[1]);
}
config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
// Support baseURL config
if (config.baseURL && !isAbsoluteURL(config.url)) {
config.url = combineURLs(config.baseURL, config.url);
}
// Don't allow overriding defaults.withCredentials
config.withCredentials = config.withCredentials || this.defaults.withCredentials;
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
var defaultInstance = new Axios(defaults);
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
axios.create = function create(defaultConfig) {
return new Axios(defaultConfig);
};
// Expose defaults
axios.defaults = defaultInstance.defaults;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(20);
// Expose interceptors
axios.interceptors = defaultInstance.interceptors;
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
var PROTECTION_PREFIX = /^\)\]\}',?\n/;
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
module.exports = {
transformRequest: [function transformResponseJSON(data, headers) {
if (utils.isFormData(data)) {
return data;
}
if (utils.isArrayBuffer(data)) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) {
// Set application/json if no Content-Type has been specified
if (!utils.isUndefined(headers)) {
utils.forEach(headers, function processContentTypeHeader(val, key) {
if (key.toLowerCase() === 'content-type') {
headers['Content-Type'] = val;
}
});
if (utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = 'application/json;charset=utf-8';
}
}
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponseJSON(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
data = data.replace(PROTECTION_PREFIX, '');
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
patch: utils.merge(DEFAULT_CONTENT_TYPE),
post: utils.merge(DEFAULT_CONTENT_TYPE),
put: utils.merge(DEFAULT_CONTENT_TYPE)
},
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
/***/ },
/* 6 */
/***/ function(module, exports) {
'use strict';
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString.call(val) === '[object FormData]';
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* typeof document.createElement -> undefined
*/
function isStandardBrowserEnv() {
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
typeof document.createElement === 'function'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray(obj)) {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
trim: trim
};
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Dispatch a request to the server using whichever adapter
* is supported by the current environment.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
return new Promise(function executor(resolve, reject) {
try {
var adapter;
if (typeof config.adapter === 'function') {
// For custom adapter support
adapter = config.adapter;
} else if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(9);
} else if (typeof process !== 'undefined') {
// For node use HTTP adapter
adapter = __webpack_require__(9);
}
if (typeof adapter === 'function') {
adapter(resolve, reject, config);
}
} catch (e) {
reject(e);
}
});
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)))
/***/ },
/* 8 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
var buildURL = __webpack_require__(10);
var parseHeaders = __webpack_require__(11);
var transformData = __webpack_require__(12);
var isURLSameOrigin = __webpack_require__(13);
var btoa = window.btoa || __webpack_require__(14);
module.exports = function xhrAdapter(resolve, reject, config) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// For IE 8/9 CORS support
// Only supports POST and GET calls and doesn't returns the response headers.
if (window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
request = new window.XDomainRequest();
}
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onload = function handleLoad() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
var response = {
data: transformData(
responseData,
responseHeaders,
config.transformResponse
),
// IE sends 1223 instead of 204 (https://github.com/mzabriskie/axios/issues/201)
status: request.status === 1223 ? 204 : request.status,
statusText: request.status === 1223 ? 'No Content' : request.statusText,
headers: responseHeaders,
config: config
};
// Resolve or reject the Promise based on the status
((response.status >= 200 && response.status < 300) ||
(!('status' in request) && response.responseText) ?
resolve :
reject)(response);
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new Error('Network Error'));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(15);
// Add xsrf header
var xsrfValue = config.withCredentials || isURLSameOrigin(config.url) ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (config.withCredentials) {
request.withCredentials = true;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
if (request.responseType !== 'json') {
throw e;
}
}
}
if (utils.isArrayBuffer(requestData)) {
requestData = new DataView(requestData);
}
// Send the request
request.send(requestData);
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
}
if (!utils.isArray(val)) {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ },
/* 14 */
/***/ function(module, exports) {
'use strict';
// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.code = 5;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
function btoa(input) {
var str = String(input);
var output = '';
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars;
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3 / 4);
if (charCode > 0xFF) {
throw new InvalidCharacterError('INVALID_CHARACTER_ERR: DOM Exception 5');
}
block = block << 8 | charCode;
}
return output;
}
module.exports = btoa;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(6);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ },
/* 17 */
/***/ function(module, exports) {
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ },
/* 18 */
/***/ function(module, exports) {
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
};
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ },
/* 20 */
/***/ function(module, exports) {
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }
/******/ ])
});
;
//# sourceMappingURL=js-data-http.js.map |
require("../../lib/jasmine-promise");
var MockFs = require("../../../fs-mock");
var normalize = require('../../../fs').normal;
describe("link", function () {
it("should", function () {
var mock = MockFs();
// make some content
return mock.makeTree("a/b")
.then(function () {
return mock.write("a/b/c.txt", "Hello, World!")
})
// verify content
.then(function () {
return mock.read("a/b/c.txt")
})
.then(function (content) {
expect(content).toBe("Hello, World!");
})
// link it
.then(function () {
return mock.link("a/b/c.txt", "a/b/d.txt")
})
// should be non-destructive
.then(function () {
return mock.read("a/b/c.txt")
})
.then(function (content) {
expect(content).toBe("Hello, World!");
})
// should be listed
.then(function () {
return mock.listTree()
})
.then(function (content) {
expect(content).toEqual([
".",
"a",
normalize("a/b"),
normalize("a/b/c.txt"),
normalize("a/b/d.txt")
])
})
// should be identified as a file
.then(function () {
return mock.isFile("a/b/d.txt");
})
.then(function (isFile) {
expect(isFile).toBe(true);
})
// should have the same content
.then(function () {
return mock.read("a/b/d.txt");
})
.then(function (content) {
expect(content).toBe("Hello, World!");
});
});
});
|
/**
* 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.
*
* @emails react-core
*/
"use strict";
var React;
var ReactTestUtils;
var ReactComponent;
var ReactCompositeComponent;
var ComponentLifeCycle;
var CompositeComponentLifeCycle;
var clone = function(o) {
return JSON.parse(JSON.stringify(o));
};
var GET_INIT_STATE_RETURN_VAL = {
hasWillMountCompleted: false,
hasRenderCompleted: false,
hasDidMountCompleted: false,
hasWillUnmountCompleted: false
};
var INIT_RENDER_STATE = {
hasWillMountCompleted: true,
hasRenderCompleted: false,
hasDidMountCompleted: false,
hasWillUnmountCompleted: false
};
var DID_MOUNT_STATE = {
hasWillMountCompleted: true,
hasRenderCompleted: true,
hasDidMountCompleted: false,
hasWillUnmountCompleted: false
};
var NEXT_RENDER_STATE = {
hasWillMountCompleted: true,
hasRenderCompleted: true,
hasDidMountCompleted: true,
hasWillUnmountCompleted: false
};
var WILL_UNMOUNT_STATE = {
hasWillMountCompleted: true,
hasDidMountCompleted: true,
hasRenderCompleted: true,
hasWillUnmountCompleted: false
};
var POST_WILL_UNMOUNT_STATE = {
hasWillMountCompleted: true,
hasDidMountCompleted: true,
hasRenderCompleted: true,
hasWillUnmountCompleted: true
};
/**
* TODO: We should make any setState calls fail in
* `getInitialState` and `componentWillMount`. They will usually fail
* anyways because `this._renderedComponent` is empty, however, if a component
* is *reused*, then that won't be the case and things will appear to work in
* some cases. Better to just block all updates in initialization.
*/
describe('ReactComponentLifeCycle', function() {
beforeEach(function() {
require('mock-modules').dumpCache();
React = require('React');
ReactTestUtils = require('ReactTestUtils');
ReactComponent = require('ReactComponent');
ReactCompositeComponent = require('ReactCompositeComponent');
ComponentLifeCycle = ReactComponent.LifeCycle;
CompositeComponentLifeCycle = ReactCompositeComponent.LifeCycle;
});
it('should not reuse an instance when it has been unmounted', function() {
var container = document.createElement('div');
var StatefulComponent = React.createClass({
getInitialState: function() {
return { };
},
render: function() {
return (
<div></div>
);
}
});
var element = <StatefulComponent />;
var firstInstance = React.render(element, container);
React.unmountComponentAtNode(container);
var secondInstance = React.render(element, container);
expect(firstInstance).not.toBe(secondInstance);
});
/**
* If a state update triggers rerendering that in turn fires an onDOMReady,
* that second onDOMReady should not fail.
*/
it('it should fire onDOMReady when already in onDOMReady', function() {
var _testJournal = [];
var Child = React.createClass({
componentDidMount: function() {
_testJournal.push('Child:onDOMReady');
},
render: function() {
return <div></div>;
}
});
var SwitcherParent = React.createClass({
getInitialState: function() {
_testJournal.push('SwitcherParent:getInitialState');
return {showHasOnDOMReadyComponent: false};
},
componentDidMount: function() {
_testJournal.push('SwitcherParent:onDOMReady');
this.switchIt();
},
switchIt: function() {
this.setState({showHasOnDOMReadyComponent: true});
},
render: function() {
return (
<div>{
this.state.showHasOnDOMReadyComponent ?
<Child /> :
<div> </div>
}</div>
);
}
});
var instance = <SwitcherParent />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(_testJournal).toEqual([
'SwitcherParent:getInitialState',
'SwitcherParent:onDOMReady',
'Child:onDOMReady'
]);
});
// You could assign state here, but not access members of it, unless you
// had provided a getInitialState method.
it('throws when accessing state in componentWillMount', function() {
var StatefulComponent = React.createClass({
componentWillMount: function() {
this.state.yada;
},
render: function() {
return (
<div></div>
);
}
});
var instance = <StatefulComponent />;
expect(function() {
instance = ReactTestUtils.renderIntoDocument(instance);
}).toThrow();
});
it('should allow update state inside of componentWillMount', function() {
var StatefulComponent = React.createClass({
componentWillMount: function() {
this.setState({stateField: 'something'});
},
render: function() {
return (
<div></div>
);
}
});
var instance = <StatefulComponent />;
expect(function() {
instance = ReactTestUtils.renderIntoDocument(instance);
}).not.toThrow();
});
it('should allow update state inside of getInitialState', function() {
var StatefulComponent = React.createClass({
getInitialState: function() {
this.setState({stateField: 'something'});
return {stateField: 'somethingelse'};
},
render: function() {
return (
<div></div>
);
}
});
var instance = <StatefulComponent />;
expect(function() {
instance = ReactTestUtils.renderIntoDocument(instance);
}).not.toThrow();
// The return value of getInitialState overrides anything from setState
expect(instance.state.stateField).toEqual('somethingelse');
});
it('should carry through each of the phases of setup', function() {
var LifeCycleComponent = React.createClass({
getInitialState: function() {
this._testJournal = {};
var initState = {
hasWillMountCompleted: false,
hasDidMountCompleted: false,
hasRenderCompleted: false,
hasWillUnmountCompleted: false
};
this._testJournal.returnedFromGetInitialState = clone(initState);
this._testJournal.lifeCycleAtStartOfGetInitialState =
this._lifeCycleState;
this._testJournal.compositeLifeCycleAtStartOfGetInitialState =
this._compositeLifeCycleState;
return initState;
},
componentWillMount: function() {
this._testJournal.stateAtStartOfWillMount = clone(this.state);
this._testJournal.lifeCycleAtStartOfWillMount =
this._lifeCycleState;
this._testJournal.compositeLifeCycleAtStartOfWillMount =
this._compositeLifeCycleState;
this.state.hasWillMountCompleted = true;
},
componentDidMount: function() {
this._testJournal.stateAtStartOfDidMount = clone(this.state);
this._testJournal.lifeCycleAtStartOfDidMount =
this._lifeCycleState;
this.setState({hasDidMountCompleted: true});
},
render: function() {
var isInitialRender = !this.state.hasRenderCompleted;
if (isInitialRender) {
this._testJournal.stateInInitialRender = clone(this.state);
this._testJournal.lifeCycleInInitialRender = this._lifeCycleState;
this._testJournal.compositeLifeCycleInInitialRender =
this._compositeLifeCycleState;
} else {
this._testJournal.stateInLaterRender = clone(this.state);
this._testJournal.lifeCycleInLaterRender = this._lifeCycleState;
}
// you would *NEVER* do anything like this in real code!
this.state.hasRenderCompleted = true;
return (
<div ref="theDiv">
I am the inner DIV
</div>
);
},
componentWillUnmount: function() {
this._testJournal.stateAtStartOfWillUnmount = clone(this.state);
this._testJournal.lifeCycleAtStartOfWillUnmount =
this._lifeCycleState;
this.state.hasWillUnmountCompleted = true;
}
});
// A component that is merely "constructed" (as in "constructor") but not
// yet initialized, or rendered.
//
var instance = ReactTestUtils.renderIntoDocument(<LifeCycleComponent />);
// getInitialState
expect(instance._testJournal.returnedFromGetInitialState).toEqual(
GET_INIT_STATE_RETURN_VAL
);
expect(instance._testJournal.lifeCycleAtStartOfGetInitialState)
.toBe(ComponentLifeCycle.MOUNTED);
expect(instance._testJournal.compositeLifeCycleAtStartOfGetInitialState)
.toBe(CompositeComponentLifeCycle.MOUNTING);
// componentWillMount
expect(instance._testJournal.stateAtStartOfWillMount).toEqual(
instance._testJournal.returnedFromGetInitialState
);
expect(instance._testJournal.lifeCycleAtStartOfWillMount)
.toBe(ComponentLifeCycle.MOUNTED);
expect(instance._testJournal.compositeLifeCycleAtStartOfWillMount)
.toBe(CompositeComponentLifeCycle.MOUNTING);
// componentDidMount
expect(instance._testJournal.stateAtStartOfDidMount)
.toEqual(DID_MOUNT_STATE);
expect(instance._testJournal.lifeCycleAtStartOfDidMount).toBe(
ComponentLifeCycle.MOUNTED
);
// render
expect(instance._testJournal.stateInInitialRender)
.toEqual(INIT_RENDER_STATE);
expect(instance._testJournal.lifeCycleInInitialRender).toBe(
ComponentLifeCycle.MOUNTED
);
expect(instance._testJournal.compositeLifeCycleInInitialRender).toBe(
CompositeComponentLifeCycle.MOUNTING
);
expect(instance._lifeCycleState).toBe(ComponentLifeCycle.MOUNTED);
// Now *update the component*
instance.forceUpdate();
// render 2nd time
expect(instance._testJournal.stateInLaterRender)
.toEqual(NEXT_RENDER_STATE);
expect(instance._testJournal.lifeCycleInLaterRender).toBe(
ComponentLifeCycle.MOUNTED
);
expect(instance._lifeCycleState).toBe(ComponentLifeCycle.MOUNTED);
// Now *unmountComponent*
instance.unmountComponent();
expect(instance._testJournal.stateAtStartOfWillUnmount)
.toEqual(WILL_UNMOUNT_STATE);
// componentWillUnmount called right before unmount.
expect(instance._testJournal.lifeCycleAtStartOfWillUnmount).toBe(
ComponentLifeCycle.MOUNTED
);
// But the current lifecycle of the component is unmounted.
expect(instance._lifeCycleState).toBe(ComponentLifeCycle.UNMOUNTED);
expect(instance.state).toEqual(POST_WILL_UNMOUNT_STATE);
});
it('should throw when calling setProps() on an owned component', function() {
/**
* calls setProps in an componentDidMount.
*/
var PropsUpdaterInOnDOMReady = React.createClass({
componentDidMount: function() {
this.refs.theSimpleComponent.setProps({
valueToUseInitially: this.props.valueToUseInOnDOMReady
});
},
render: function() {
return (
<div
className={this.props.valueToUseInitially}
ref="theSimpleComponent"
/>
);
}
});
var instance =
<PropsUpdaterInOnDOMReady
valueToUseInitially="hello"
valueToUseInOnDOMReady="goodbye"
/>;
expect(function() {
instance = ReactTestUtils.renderIntoDocument(instance);
}).toThrow(
'Invariant Violation: replaceProps(...): You called `setProps` or ' +
'`replaceProps` on a component with a parent. This is an anti-pattern ' +
'since props will get reactively updated when rendered. Instead, ' +
'change the owner\'s `render` method to pass the correct value as ' +
'props to the component where it is created.'
);
});
it('should not throw when updating an auxiliary component', function() {
var Tooltip = React.createClass({
render: function() {
return <div>{this.props.children}</div>;
},
componentDidMount: function() {
this.container = document.createElement('div');
this.updateTooltip();
},
componentDidUpdate: function() {
this.updateTooltip();
},
updateTooltip: function() {
// Even though this.props.tooltip has an owner, updating it shouldn't
// throw here because it's mounted as a root component
React.render(this.props.tooltip, this.container);
}
});
var Component = React.createClass({
render: function() {
return (
<Tooltip
ref="tooltip"
tooltip={<div>{this.props.tooltipText}</div>}>
{this.props.text}
</Tooltip>
);
}
});
var container = document.createElement('div');
var instance = React.render(
<Component text="uno" tooltipText="one" />,
container
);
// Since `instance` is a root component, we can set its props. This also
// makes Tooltip rerender the tooltip component, which shouldn't throw.
instance.setProps({text: "dos", tooltipText: "two"});
});
it('should not allow setProps() called on an unmounted element',
function() {
var PropsToUpdate = React.createClass({
render: function() {
return <div className={this.props.value} ref="theSimpleComponent" />;
}
});
var instance = <PropsToUpdate value="hello" />;
expect(instance.setProps).not.toBeDefined();
});
it('should allow state updates in componentDidMount', function() {
/**
* calls setState in an componentDidMount.
*/
var SetStateInComponentDidMount = React.createClass({
getInitialState: function() {
return {
stateField: this.props.valueToUseInitially
};
},
componentDidMount: function() {
this.setState({stateField: this.props.valueToUseInOnDOMReady});
},
render: function() {
return (<div></div>);
}
});
var instance =
<SetStateInComponentDidMount
valueToUseInitially="hello"
valueToUseInOnDOMReady="goodbye"
/>;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.state.stateField).toBe('goodbye');
});
it('should call nested lifecycle methods in the right order', function() {
var log;
var logger = function(msg) {
return function() {
// return true for shouldComponentUpdate
log.push(msg);
return true;
};
};
var Outer = React.createClass({
render: function() {
return <div><Inner x={this.props.x} /></div>;
},
componentWillMount: logger('outer componentWillMount'),
componentDidMount: logger('outer componentDidMount'),
componentWillReceiveProps: logger('outer componentWillReceiveProps'),
shouldComponentUpdate: logger('outer shouldComponentUpdate'),
componentWillUpdate: logger('outer componentWillUpdate'),
componentDidUpdate: logger('outer componentDidUpdate'),
componentWillUnmount: logger('outer componentWillUnmount')
});
var Inner = React.createClass({
render: function() {
return <span>{this.props.x}</span>;
},
componentWillMount: logger('inner componentWillMount'),
componentDidMount: logger('inner componentDidMount'),
componentWillReceiveProps: logger('inner componentWillReceiveProps'),
shouldComponentUpdate: logger('inner shouldComponentUpdate'),
componentWillUpdate: logger('inner componentWillUpdate'),
componentDidUpdate: logger('inner componentDidUpdate'),
componentWillUnmount: logger('inner componentWillUnmount')
});
var instance;
log = [];
instance = ReactTestUtils.renderIntoDocument(<Outer x={17} />);
expect(log).toEqual([
'outer componentWillMount',
'inner componentWillMount',
'inner componentDidMount',
'outer componentDidMount'
]);
log = [];
instance.setProps({x: 42});
expect(log).toEqual([
'outer componentWillReceiveProps',
'outer shouldComponentUpdate',
'outer componentWillUpdate',
'inner componentWillReceiveProps',
'inner shouldComponentUpdate',
'inner componentWillUpdate',
'inner componentDidUpdate',
'outer componentDidUpdate'
]);
log = [];
instance.unmountComponent();
expect(log).toEqual([
'outer componentWillUnmount',
'inner componentWillUnmount'
]);
});
});
|
YUI.add('series-histogram-base', function (Y, NAME) {
/**
* Provides core functionality for creating a bar or column series.
*
* @module charts
* @submodule series-histogram
*/
var Y_Lang = Y.Lang;
/**
* Histogram is the base class for Column and Bar series.
*
* @class Histogram
* @constructor
* @param {Object} config (optional) Configuration parameters.
* @submodule series-histogram
*/
function Histogram(){}
Histogram.prototype = {
/**
* Draws the series.
*
* @method drawSeries
* @protected
*/
drawSeries: function()
{
if(this.get("xcoords").length < 1)
{
return;
}
var style = Y.clone(this.get("styles").marker),
graphic = this.get("graphic"),
setSize,
calculatedSize,
xcoords = this.get("xcoords"),
ycoords = this.get("ycoords"),
i = 0,
len = xcoords.length,
top = ycoords[0],
type = this.get("type"),
seriesTypeCollection = this.get("seriesTypeCollection"),
seriesLen = seriesTypeCollection.length || 0,
seriesSize = 0,
totalSize = 0,
offset = 0,
ratio,
renderer,
order = this.get("order"),
graphOrder = this.get("graphOrder"),
left,
marker,
setSizeKey,
calculatedSizeKey,
config,
fillColors = null,
borderColors = null,
xMarkerPlane = [],
yMarkerPlane = [],
xMarkerPlaneLeft,
xMarkerPlaneRight,
yMarkerPlaneTop,
yMarkerPlaneBottom,
dimensions = {
width: [],
height: []
},
xvalues = [],
yvalues = [],
groupMarkers = this.get("groupMarkers");
if(Y_Lang.isArray(style.fill.color))
{
fillColors = style.fill.color.concat();
}
if(Y_Lang.isArray(style.border.color))
{
borderColors = style.border.color.concat();
}
if(this.get("direction") == "vertical")
{
setSizeKey = "height";
calculatedSizeKey = "width";
}
else
{
setSizeKey = "width";
calculatedSizeKey = "height";
}
setSize = style[setSizeKey];
calculatedSize = style[calculatedSizeKey];
this._createMarkerCache();
for(; i < seriesLen; ++i)
{
renderer = seriesTypeCollection[i];
seriesSize += renderer.get("styles").marker[setSizeKey];
if(order > i)
{
offset = seriesSize;
}
}
totalSize = len * seriesSize;
this._maxSize = graphic.get(setSizeKey);
if(totalSize > this._maxSize)
{
ratio = graphic.get(setSizeKey)/totalSize;
seriesSize *= ratio;
offset *= ratio;
setSize *= ratio;
setSize = Math.max(setSize, 1);
this._maxSize = setSize;
}
offset -= seriesSize/2;
for(i = 0; i < len; ++i)
{
xMarkerPlaneLeft = xcoords[i] - seriesSize/2;
xMarkerPlaneRight = xMarkerPlaneLeft + seriesSize;
yMarkerPlaneTop = ycoords[i] - seriesSize/2;
yMarkerPlaneBottom = yMarkerPlaneTop + seriesSize;
xMarkerPlane.push({start: xMarkerPlaneLeft, end: xMarkerPlaneRight});
yMarkerPlane.push({start: yMarkerPlaneTop, end: yMarkerPlaneBottom});
if(isNaN(xcoords[i]) || isNaN(ycoords[i]))
{
this._markers.push(null);
continue;
}
config = this._getMarkerDimensions(xcoords[i], ycoords[i], calculatedSize, offset);
if(!isNaN(config.calculatedSize) && config.calculatedSize > 0)
{
top = config.top;
left = config.left;
if(groupMarkers)
{
dimensions[setSizeKey][i] = setSize;
dimensions[calculatedSizeKey][i] = config.calculatedSize;
xvalues.push(left);
yvalues.push(top);
}
else
{
style[setSizeKey] = setSize;
style[calculatedSizeKey] = config.calculatedSize;
style.x = left;
style.y = top;
if(fillColors)
{
style.fill.color = fillColors[i % fillColors.length];
}
if(borderColors)
{
style.border.color = borderColors[i % borderColors.length];
}
marker = this.getMarker(style, graphOrder, i);
}
}
else if(!groupMarkers)
{
this._markers.push(null);
}
}
this.set("xMarkerPlane", xMarkerPlane);
this.set("yMarkerPlane", yMarkerPlane);
if(groupMarkers)
{
this._createGroupMarker({
fill: style.fill,
border: style.border,
dimensions: dimensions,
xvalues: xvalues,
yvalues: yvalues,
shape: style.shape
});
}
else
{
this._clearMarkerCache();
}
},
/**
* Collection of default colors used for marker fills in a series when not specified by user.
*
* @property _defaultFillColors
* @type Array
* @protected
*/
_defaultFillColors: ["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"],
/**
* Gets the default style values for the markers.
*
* @method _getPlotDefaults
* @return Object
* @private
*/
_getPlotDefaults: function()
{
var defs = {
fill:{
type: "solid",
alpha: 1,
colors:null,
alphas: null,
ratios: null
},
border:{
weight: 0,
alpha: 1
},
width: 12,
height: 12,
shape: "rect",
padding:{
top: 0,
left: 0,
right: 0,
bottom: 0
}
};
defs.fill.color = this._getDefaultColor(this.get("graphOrder"), "fill");
defs.border.color = this._getDefaultColor(this.get("graphOrder"), "border");
return defs;
}
};
Y.Histogram = Histogram;
}, '@VERSION@', {"requires": ["series-marker"]});
|
/**
* Globalize v1.0.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-20T16:57Z
*/
/*!
* Globalize v1.0.1 2016-01-20T16:57Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"cldr/event"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
root.Globalize = factory( root.Cldr );
}
}( this, function( Cldr ) {
/**
* A toString method that outputs meaningful values for objects or arrays and
* still performs as fast as a plain string in case variable is string, or as
* fast as `"" + number` in case variable is a number.
* Ref: http://jsperf.com/my-stringify
*/
var toString = function( variable ) {
return typeof variable === "string" ? variable : ( typeof variable === "number" ? "" +
variable : JSON.stringify( variable ) );
};
/**
* formatMessage( message, data )
*
* @message [String] A message with optional {vars} to be replaced.
*
* @data [Array or JSON] Object with replacing-variables content.
*
* Return the formatted message. For example:
*
* - formatMessage( "{0} second", [ 1 ] ); // 1 second
*
* - formatMessage( "{0}/{1}", ["m", "s"] ); // m/s
*
* - formatMessage( "{name} <{email}>", {
* name: "Foo",
* email: "bar@baz.qux"
* }); // Foo <bar@baz.qux>
*/
var formatMessage = function( message, data ) {
// Replace {attribute}'s
message = message.replace( /{[0-9a-zA-Z-_. ]+}/g, function( name ) {
name = name.replace( /^{([^}]*)}$/, "$1" );
return toString( data[ name ] );
});
return message;
};
var objectExtend = function() {
var destination = arguments[ 0 ],
sources = [].slice.call( arguments, 1 );
sources.forEach(function( source ) {
var prop;
for ( prop in source ) {
destination[ prop ] = source[ prop ];
}
});
return destination;
};
var createError = function( code, message, attributes ) {
var error;
message = code + ( message ? ": " + formatMessage( message, attributes ) : "" );
error = new Error( message );
error.code = code;
objectExtend( error, attributes );
return error;
};
var validate = function( code, message, check, attributes ) {
if ( !check ) {
throw createError( code, message, attributes );
}
};
var alwaysArray = function( stringOrArray ) {
return Array.isArray( stringOrArray ) ? stringOrArray : stringOrArray ? [ stringOrArray ] : [];
};
var validateCldr = function( path, value, options ) {
var skipBoolean;
options = options || {};
skipBoolean = alwaysArray( options.skip ).some(function( pathRe ) {
return pathRe.test( path );
});
validate( "E_MISSING_CLDR", "Missing required CLDR content `{path}`.", value || skipBoolean, {
path: path
});
};
var validateDefaultLocale = function( value ) {
validate( "E_DEFAULT_LOCALE_NOT_DEFINED", "Default locale has not been defined.",
value !== undefined, {} );
};
var validateParameterPresence = function( value, name ) {
validate( "E_MISSING_PARAMETER", "Missing required parameter `{name}`.",
value !== undefined, { name: name });
};
/**
* range( value, name, minimum, maximum )
*
* @value [Number].
*
* @name [String] name of variable.
*
* @minimum [Number]. The lowest valid value, inclusive.
*
* @maximum [Number]. The greatest valid value, inclusive.
*/
var validateParameterRange = function( value, name, minimum, maximum ) {
validate(
"E_PAR_OUT_OF_RANGE",
"Parameter `{name}` has value `{value}` out of range [{minimum}, {maximum}].",
value === undefined || value >= minimum && value <= maximum,
{
maximum: maximum,
minimum: minimum,
name: name,
value: value
}
);
};
var validateParameterType = function( value, name, check, expected ) {
validate(
"E_INVALID_PAR_TYPE",
"Invalid `{name}` parameter ({value}). {expected} expected.",
check,
{
expected: expected,
name: name,
value: value
}
);
};
var validateParameterTypeLocale = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "string" || value instanceof Cldr,
"String or Cldr instance"
);
};
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateParameterTypePlainObject = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || isPlainObject( value ),
"Plain Object"
);
};
var alwaysCldr = function( localeOrCldr ) {
return localeOrCldr instanceof Cldr ? localeOrCldr : new Cldr( localeOrCldr );
};
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions
var regexpEscape = function( string ) {
return string.replace( /([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1" );
};
var stringPad = function( str, count, right ) {
var length;
if ( typeof str !== "string" ) {
str = String( str );
}
for ( length = str.length; length < count; length += 1 ) {
str = ( right ? ( str + "0" ) : ( "0" + str ) );
}
return str;
};
function validateLikelySubtags( cldr ) {
cldr.once( "get", validateCldr );
cldr.get( "supplemental/likelySubtags" );
}
/**
* [new] Globalize( locale|cldr )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Create a Globalize instance.
*/
function Globalize( locale ) {
if ( !( this instanceof Globalize ) ) {
return new Globalize( locale );
}
validateParameterPresence( locale, "locale" );
validateParameterTypeLocale( locale, "locale" );
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
/**
* Globalize.load( json, ... )
*
* @json [JSON]
*
* Load resolved or unresolved cldr data.
* Somewhat equivalent to previous Globalize.addCultureInfo(...).
*/
Globalize.load = function() {
// validations are delegated to Cldr.load().
Cldr.load.apply( Cldr, arguments );
};
/**
* Globalize.locale( [locale|cldr] )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Set default Cldr instance if locale or cldr argument is passed.
*
* Return the default Cldr instance.
*/
Globalize.locale = function( locale ) {
validateParameterTypeLocale( locale, "locale" );
if ( arguments.length ) {
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
return this.cldr;
};
/**
* Optimization to avoid duplicating some internal functions across modules.
*/
Globalize._alwaysArray = alwaysArray;
Globalize._createError = createError;
Globalize._formatMessage = formatMessage;
Globalize._isPlainObject = isPlainObject;
Globalize._objectExtend = objectExtend;
Globalize._regexpEscape = regexpEscape;
Globalize._stringPad = stringPad;
Globalize._validate = validate;
Globalize._validateCldr = validateCldr;
Globalize._validateDefaultLocale = validateDefaultLocale;
Globalize._validateParameterPresence = validateParameterPresence;
Globalize._validateParameterRange = validateParameterRange;
Globalize._validateParameterTypePlainObject = validateParameterTypePlainObject;
Globalize._validateParameterType = validateParameterType;
return Globalize;
}));
|
angular.module("uib/template/datepicker/day.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/datepicker/day.html",
"<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left uib-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-left\"></i><span class=\"sr-only\">previous</span></button></th>\n" +
" <th colspan=\"{{::5 + showWeeks}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm uib-title\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right uib-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-right\"></i><span class=\"sr-only\">next</span></button></th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th ng-if=\"showWeeks\" class=\"text-center\"></th>\n" +
" <th ng-repeat=\"label in ::labels track by $index\" class=\"text-center\"><small aria-label=\"{{::label.full}}\">{{::label.abbr}}</small></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr class=\"uib-weeks\" ng-repeat=\"row in rows track by $index\" role=\"row\">\n" +
" <td ng-if=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
" <td ng-repeat=\"dt in row\" class=\"uib-day text-center\" role=\"gridcell\"\n" +
" id=\"{{::dt.uid}}\"\n" +
" ng-class=\"::dt.customClass\">\n" +
" <button type=\"button\" class=\"btn btn-default btn-sm\"\n" +
" uib-is-class=\"\n" +
" 'btn-info' for selectedDt,\n" +
" 'active' for activeDt\n" +
" on dt\"\n" +
" ng-click=\"select(dt.date)\"\n" +
" ng-disabled=\"::dt.disabled\"\n" +
" tabindex=\"-1\"><span ng-class=\"::{'text-muted': dt.secondary, 'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
|
;(function(window, document, undefined) {
'use strict';
/**
* Construct a new Cleave instance by passing the configuration object
*
* @param {Object} opts
* @param {String / HTMLElement} element
*/
var Cleave = function (element, opts) {
var owner = this;
if (typeof element === 'string') {
owner.element = document.querySelector(element);
} else {
owner.element = ((typeof element.length !== 'undefined') && element.length > 0) ? element[0] : element;
}
opts.initValue = owner.element.value;
owner.properties = Cleave.DefaultProperties.assign({}, opts);
owner.init();
};
Cleave.prototype = {
init: function () {
var owner = this, pps = owner.properties;
// no need to use this lib
if (!pps.numeral && !pps.phone && !pps.creditCard && !pps.date && pps.blocks.length === 0) {
return;
}
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
owner.element.addEventListener('input', owner.onChange.bind(owner));
owner.element.addEventListener('keydown', owner.onKeydown.bind(owner));
owner.initPhoneFormatter();
owner.initDateFormatter();
owner.initNumeralFormatter();
owner.onInput(pps.initValue);
},
initNumeralFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.numeral) {
return;
}
pps.numeralFormatter = new Cleave.NumeralFormatter(
pps.numeralDecimalMark,
pps.numeralDecimalScale,
pps.numeralThousandsGroupStyle,
pps.delimiter
);
},
initDateFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.date) {
return;
}
pps.dateFormatter = new Cleave.DateFormatter(pps.datePattern);
pps.blocks = pps.dateFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
},
initPhoneFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.phone) {
return;
}
// Cleave.AsYouTypeFormatter should be provided by
// external google closure lib
try {
pps.phoneFormatter = new Cleave.PhoneFormatter(
new window.Cleave.AsYouTypeFormatter(pps.phoneRegionCode),
pps.delimiter
);
} catch (ex) {
throw new Error('Please include phone-type-formatter.{country}.js lib');
}
},
onKeydown: function (event) {
var owner = this, pps = owner.properties,
charCode = event.which || event.keyCode;
// hit backspace when last character is delimiter
if (charCode === 8 && owner.element.value.slice(-1) === pps.delimiter) {
pps.backspace = true;
return;
}
pps.backspace = false;
},
onChange: function () {
this.onInput(this.element.value);
},
onInput: function (value) {
var owner = this, pps = owner.properties,
prev = value,
Util = Cleave.Util;
// case 1: delete one more character "4"
// 1234*| -> hit backspace -> 123|
// case 2: last character is not delimiter which is:
// 12|34* -> hit backspace -> 1|34*
if (pps.backspace && value.slice(-1) !== pps.delimiter) {
value = Util.headStr(value, value.length - 1);
}
// phone formatter
if (pps.phone) {
pps.result = pps.phoneFormatter.format(value);
owner.updateValueState();
return;
}
// numeral formatter
if (pps.numeral) {
pps.result = pps.numeralFormatter.format(value);
owner.updateValueState();
return;
}
// date
if (pps.date) {
value = pps.dateFormatter.getValidatedDate(value);
}
// strip delimiters
value = Util.strip(value, pps.delimiterRE);
// prefix
value = Util.getPrefixAppliedValue(value, pps.prefix);
// strip non-numeric characters
if (pps.numericOnly) {
value = Util.strip(value, /[^\d]/g);
}
// update credit card blocks
// and at least one of first 4 characters has changed
if (pps.creditCard && Util.headStr(pps.result, 4) !== Util.headStr(value, 4)) {
pps.blocks = Cleave.CreditCardDetector.getBlocksByPAN(value, pps.creditCardStrictMode);
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
}
// strip over length characters
value = Util.headStr(value, pps.maxLength);
// convert case
value = pps.uppercase ? value.toUpperCase() : value;
value = pps.lowercase ? value.toLowerCase() : value;
// apply blocks
pps.result = Util.getFormattedValue(value, pps.blocks, pps.blocksLength, pps.delimiter);
// nothing changed
// prevent update value to avoid caret position change
if (prev === pps.result) {
return;
}
owner.updateValueState();
},
updateValueState: function () {
var owner = this;
owner.element.value = owner.properties.result;
},
setPhoneRegionCode: function (phoneRegionCode) {
var owner = this, pps = owner.properties;
pps.phoneRegionCode = phoneRegionCode;
owner.initPhoneFormatter();
owner.onChange();
},
setRawValue: function (value) {
var owner = this;
owner.element.value = value;
owner.onInput(value);
},
getRawValue: function () {
var owner = this, pps = owner.properties;
return Cleave.Util.strip(owner.element.value, pps.delimiterRE);
},
getFormattedValue: function () {
return this.element.value;
},
destroy: function () {
var owner = this;
owner.element.removeEventListener('input', owner.onChange.bind(owner));
owner.element.removeEventListener('keydown', owner.onKeydown.bind(owner));
},
toString: function () {
return '[Cleave Object]';
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
Cleave.NumeralFormatter = require('./shortcuts/NumeralFormatter');
Cleave.DateFormatter = require('./shortcuts/DateFormatter');
Cleave.PhoneFormatter = require('./shortcuts/PhoneFormatter');
Cleave.CreditCardDetector = require('./shortcuts/CreditCardDetector');
Cleave.Util = require('./utils/Util');
Cleave.DefaultProperties = require('./common/DefaultProperties');
// CommonJS
module.exports = exports = Cleave;
}
'use strict';
var Util = {
noop: function () {
},
strip: function (value, re) {
return value.replace(re, '');
},
headStr: function (str, length) {
return str.slice(0, length);
},
getMaxLength: function (blocks) {
return blocks.reduce(function (previous, current) {
return previous + current;
}, 0);
},
getPrefixAppliedValue: function (value, prefix) {
var prefixLength = prefix.length,
prefixLengthValue;
if (prefixLength === 0) {
return value;
}
prefixLengthValue = value.slice(0, prefixLength);
if (prefixLengthValue.length < prefixLength) {
value = prefix;
} else if (prefixLengthValue !== prefix) {
value = prefix + value.slice(prefixLength);
}
return value;
},
getFormattedValue: function (value, blocks, blocksLength, delimiter) {
var result = '';
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
result += sub;
if (sub.length === length && index < blocksLength - 1) {
result += delimiter;
}
// update remaining string
value = rest;
}
});
return result;
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = Util;
}
'use strict';
/**
* Props Assignment
*
* Separate this, so react module can share the usage
*/
var DefaultProperties = {
// Maybe change to object-assign
// for now just keep it as simple
assign: function (target, opts) {
target = target || {};
opts = opts || {};
// credit card
target.creditCard = !!opts.creditCard;
target.creditCardStrictMode = !!opts.creditCardStrictMode;
// phone
target.phone = !!opts.phone;
target.phoneRegionCode = opts.phoneRegionCode || 'AU';
target.phoneFormatter = {};
// date
target.date = !!opts.date;
target.datePattern = opts.datePattern || ['d', 'm', 'Y'];
target.dateFormatter = {};
// numeral
target.numeral = !!opts.numeral;
target.numeralDecimalScale = opts.numeralDecimalScale || 2;
target.numeralDecimalMark = opts.numeralDecimalMark || '.';
target.numeralThousandsGroupStyle = opts.numeralThousandsGroupStyle || 'thousand';
// others
target.initValue = opts.initValue || '';
target.numericOnly = target.creditCard || target.date || !!opts.numericOnly;
target.uppercase = !!opts.uppercase;
target.lowercase = !!opts.lowercase;
target.prefix = (target.creditCard || target.phone || target.date) ? '' : (opts.prefix || '');
target.delimiter = opts.delimiter || (target.date ? '/' : (target.numeral ? ',' : ' '));
target.delimiterRE = new RegExp(target.delimiter, 'g');
target.blocks = opts.blocks || [];
target.blocksLength = target.blocks.length;
target.maxLength = 0;
target.backspace = false;
target.result = '';
return target;
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = DefaultProperties;
}
'use strict';
var CreditCardDetector = {
blocks: {
uatp: [4, 5, 6],
amex: [4, 6, 5],
diners: [4, 6, 4],
mastercard: [4, 4, 4, 4],
dankort: [4, 4, 4, 4],
instapayment: [4, 4, 4, 4],
jcb: [4, 4, 4, 4],
generalStrict: [4, 4, 4, 7],
generalLoose: [4, 4, 4, 4]
},
re: {
// starts with 1; 15 digits, not starts with 1800 (jcb card)
uatp: /^(?!1800)1\d{0,14}/,
// starts with 34/37; 15 digits
amex: /^3[47]\d{0,13}/,
// starts with 300-305/309 or 36/38/39; 14 digits
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,
// starts with 51-55 or 22-27; 16 digits
mastercard: /^(5[1-5]|2[2-7])\d{0,14}/,
// starts with 5019/4175/4571; 16 digits
dankort: /^(5019|4175|4571)\d{0,12}/,
// starts with 637-639; 16 digits
instapayment: /^63[7-9]\d{0,13}/,
// starts with 2131/1800/35; 16 digits
jcb: /^(?:2131|1800|35\d{0,2})\d{0,12}/
},
getBlocksByPAN: function (value, strictMode) {
var blocks = CreditCardDetector.blocks,
re = CreditCardDetector.re;
// In theory, credit card can have up to 19 digits number.
// Set strictMode to true will remove the 16 max-length restrain,
// however, I never found any website validate card number like
// this, hence probably you don't need to enable this option.
strictMode = !!strictMode;
if (re.amex.test(value)) {
return blocks.amex;
} else if (re.uatp.test(value)) {
return blocks.uatp;
} else if (re.diners.test(value)) {
return blocks.diners;
} else if (re.mastercard.test(value)) {
return blocks.mastercard;
} else if (re.dankort.test(value)) {
return blocks.dankort;
} else if (re.instapayment.test(value)) {
return blocks.instapayment;
} else if (re.jcb.test(value)) {
return blocks.jcb;
} else if (strictMode) {
return blocks.generalStrict;
} else {
return blocks.generalLoose;
}
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = CreditCardDetector;
}
'use strict';
var DateFormatter = function (datePattern) {
var owner = this;
owner.blocks = [];
owner.datePattern = datePattern;
owner.initBlocks();
};
DateFormatter.prototype = {
initBlocks: function () {
var owner = this;
owner.datePattern.forEach(function (value) {
if (value === 'Y') {
owner.blocks.push(4);
} else {
owner.blocks.push(2);
}
});
},
getBlocks: function () {
return this.blocks;
},
getValidatedDate: function (value) {
var owner = this, result = '';
value = value.replace(/[^\d]/g, '');
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
switch (owner.datePattern[index]) {
case 'd':
if (parseInt(sub, 10) > 31) {
sub = '31';
}
break;
case 'm':
if (parseInt(sub, 10) > 12) {
sub = '12';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return result;
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = DateFormatter;
}
'use strict';
var NumeralFormatter = function (numeralDecimalMark,
numeralDecimalScale,
numeralThousandsGroupStyle,
delimiter) {
var owner = this;
owner.numeralDecimalMark = numeralDecimalMark || '.';
owner.numeralDecimalScale = numeralDecimalScale || 2;
owner.numeralThousandsGroupStyle = numeralThousandsGroupStyle || NumeralFormatter.groupStyle.thousand;
owner.delimiter = delimiter || ',';
};
NumeralFormatter.groupStyle = {
thousand: 'thousand',
lakh: 'lakh',
wan: 'wan'
};
NumeralFormatter.prototype = {
format: function (value) {
var owner = this, parts, partInteger, partDecimal = '';
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(owner.numeralDecimalMark, 'M')
// strip the non numeric letters except M
.replace(/[^\dM]/g, '')
// replace mark
.replace('M', owner.numeralDecimalMark)
// strip leading 0
.replace(/^(-)?0+(?=\d)/, '$1');
partInteger = value;
if (value.indexOf(owner.numeralDecimalMark) >= 0) {
parts = value.split(owner.numeralDecimalMark);
partInteger = parts[0];
partDecimal = owner.numeralDecimalMark + parts[1].slice(0, owner.numeralDecimalScale);
}
switch (owner.numeralThousandsGroupStyle) {
case NumeralFormatter.groupStyle.lakh:
partInteger = partInteger.replace(/(\d)(?=(\d\d)+\d$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.wan:
partInteger = partInteger.replace(/(\d)(?=(\d{4})+$)/g, '$1' + owner.delimiter);
break;
default:
partInteger = partInteger.replace(/(\d)(?=(\d{3})+$)/g, '$1' + owner.delimiter);
}
return partInteger.toString() + partDecimal.toString();
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = NumeralFormatter;
}
'use strict';
var PhoneFormatter = function (formatter, delimiter) {
var owner = this;
owner.delimiter = delimiter || ' ';
owner.delimiterRE = new RegExp(owner.delimiter, 'g');
owner.formatter = formatter;
};
PhoneFormatter.prototype = {
setFormatter: function (formatter) {
this.formatter = formatter;
},
format: function (phoneNumber) {
var owner = this;
owner.formatter.clear();
// only keep number and +
phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
// strip delimiter
phoneNumber = phoneNumber.replace(owner.delimiterRE, '');
var result = '', current, validated = false;
for (var i = 0, iMax = phoneNumber.length; i < iMax; i++) {
current = owner.formatter.inputDigit(phoneNumber.charAt(i));
// has ()- or space inside
if (/[\s()-]/g.test(current)) {
result = current;
validated = true;
} else {
if (!validated) {
result = current;
}
// else: over length input
// it turns to invalid number again
}
}
// strip ()
// e.g. US: 7161234567 returns (716) 123-4567
result = result.replace(/[()]/g, '');
// replace library delimiter with user customized delimiter
result = result.replace(/[\s-]/g, owner.delimiter);
return result;
}
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = PhoneFormatter;
}
Cleave.NumeralFormatter = NumeralFormatter;
Cleave.DateFormatter = DateFormatter;
Cleave.PhoneFormatter = PhoneFormatter;
Cleave.CreditCardDetector = CreditCardDetector;
Cleave.Util = Util;
Cleave.DefaultProperties = DefaultProperties;
if (typeof module === 'object' && typeof module.exports === 'object') {
// CommonJS
module.exports = exports = Cleave;
} else if (typeof define === 'function' && define.amd) {
// AMD support
define(function () {
return Cleave;
});
} else if (typeof window === 'object') {
// Normal way
window.Cleave = Cleave;
}
})(window, document);
|
'use strict';
var vlq = require('vlq');
function Chunk ( start, end, content ) {
this.start = start;
this.end = end;
this.original = content;
this.intro = '';
this.outro = '';
this.content = content;
this.storeName = false;
this.edited = false;
// we make these non-enumerable, for sanity while debugging
Object.defineProperties( this, {
previous: { writable: true, value: null },
next: { writable: true, value: null }
});
}
Chunk.prototype = {
append: function append ( content ) {
this.outro += content;
},
clone: function clone () {
var chunk = new Chunk( this.start, this.end, this.original );
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
},
contains: function contains ( index ) {
return this.start < index && index < this.end;
},
eachNext: function eachNext ( fn ) {
var chunk = this;
while ( chunk ) {
fn( chunk );
chunk = chunk.next;
}
},
eachPrevious: function eachPrevious ( fn ) {
var chunk = this;
while ( chunk ) {
fn( chunk );
chunk = chunk.previous;
}
},
edit: function edit ( content, storeName ) {
this.content = content;
this.intro = '';
this.outro = '';
this.storeName = storeName;
this.edited = true;
return this;
},
prepend: function prepend ( content ) {
this.intro = content + this.intro;
},
split: function split ( index ) {
var sliceIndex = index - this.start;
var originalBefore = this.original.slice( 0, sliceIndex );
var originalAfter = this.original.slice( sliceIndex );
this.original = originalBefore;
var newChunk = new Chunk( index, this.end, originalAfter );
newChunk.outro = this.outro;
this.outro = '';
this.end = index;
if ( this.edited ) {
// TODO is this block necessary?...
newChunk.edit( '', false );
this.content = '';
} else {
this.content = originalBefore;
}
newChunk.next = this.next;
if ( newChunk.next ) newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
},
toString: function toString () {
return this.intro + this.content + this.outro;
},
trimEnd: function trimEnd ( rx ) {
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) return true;
var trimmed = this.content.replace( rx, '' );
if ( trimmed.length ) {
if ( trimmed !== this.content ) {
this.split( this.start + trimmed.length ).edit( '', false );
}
return true;
} else {
this.edit( '', false );
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) return true;
}
},
trimStart: function trimStart ( rx ) {
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) return true;
var trimmed = this.content.replace( rx, '' );
if ( trimmed.length ) {
if ( trimmed !== this.content ) {
this.split( this.end - trimmed.length );
this.edit( '', false );
}
return true;
} else {
this.edit( '', false );
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) return true;
}
}
};
var _btoa;
if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) {
_btoa = window.btoa;
} else if ( typeof Buffer === 'function' ) {
_btoa = function (str) { return new Buffer( str ).toString( 'base64' ); };
} else {
_btoa = function () {
throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' );
};
}
var btoa = _btoa;
function SourceMap ( properties ) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = properties.mappings;
}
SourceMap.prototype = {
toString: function toString () {
return JSON.stringify( this );
},
toUrl: function toUrl () {
return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() );
}
};
function guessIndent ( code ) {
var lines = code.split( '\n' );
var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } );
var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } );
if ( tabbed.length === 0 && spaced.length === 0 ) {
return null;
}
// More lines tabbed than spaced? Assume tabs, and
// default to tabs in the case of a tie (or nothing
// to go on)
if ( tabbed.length >= spaced.length ) {
return '\t';
}
// Otherwise, we need to guess the multiple
var min = spaced.reduce( function ( previous, current ) {
var numSpaces = /^ +/.exec( current )[0].length;
return Math.min( numSpaces, previous );
}, Infinity );
return new Array( min + 1 ).join( ' ' );
}
function getSemis ( str ) {
return new Array( str.split( '\n' ).length ).join( ';' );
}
function getLocator ( source ) {
var originalLines = source.split( '\n' );
var start = 0;
var lineRanges = originalLines.map( function ( line, i ) {
var end = start + line.length + 1;
var range = { start: start, end: end, line: i };
start = end;
return range;
});
var i = 0;
function rangeContains ( range, index ) {
return range.start <= index && index < range.end;
}
function getLocation ( range, index ) {
return { line: range.line, column: index - range.start };
}
return function locate ( index ) {
var range = lineRanges[i];
var d = index >= range.end ? 1 : -1;
while ( range ) {
if ( rangeContains( range, index ) ) return getLocation( range, index );
i += d;
range = lineRanges[i];
}
};
}
var nonWhitespace = /\S/;
function encodeMappings ( original, intro, outro, chunk, hires, sourcemapLocations, sourceIndex, offsets, names ) {
var rawLines = [];
var generatedCodeLine = intro.split( '\n' ).length - 1;
var rawSegments = rawLines[ generatedCodeLine ] = [];
var generatedCodeColumn = 0;
var locate = getLocator( original );
function addEdit ( content, original, loc, nameIndex, i ) {
if ( i || ( content.length && nonWhitespace.test( content ) ) ) {
rawSegments.push({
generatedCodeLine: generatedCodeLine,
generatedCodeColumn: generatedCodeColumn,
sourceCodeLine: loc.line,
sourceCodeColumn: loc.column,
sourceCodeName: nameIndex,
sourceIndex: sourceIndex
});
}
var lines = content.split( '\n' );
var lastLine = lines.pop();
if ( lines.length ) {
generatedCodeLine += lines.length;
rawLines[ generatedCodeLine ] = rawSegments = [];
generatedCodeColumn = lastLine.length;
} else {
generatedCodeColumn += lastLine.length;
}
lines = original.split( '\n' );
lastLine = lines.pop();
if ( lines.length ) {
loc.line += lines.length;
loc.column = lastLine.length;
} else {
loc.column += lastLine.length;
}
}
function addUneditedChunk ( chunk, loc ) {
var originalCharIndex = chunk.start;
var first = true;
while ( originalCharIndex < chunk.end ) {
if ( hires || first || sourcemapLocations[ originalCharIndex ] ) {
rawSegments.push({
generatedCodeLine: generatedCodeLine,
generatedCodeColumn: generatedCodeColumn,
sourceCodeLine: loc.line,
sourceCodeColumn: loc.column,
sourceCodeName: -1,
sourceIndex: sourceIndex
});
}
if ( original[ originalCharIndex ] === '\n' ) {
loc.line += 1;
loc.column = 0;
generatedCodeLine += 1;
rawLines[ generatedCodeLine ] = rawSegments = [];
generatedCodeColumn = 0;
} else {
loc.column += 1;
generatedCodeColumn += 1;
}
originalCharIndex += 1;
first = false;
}
}
var hasContent = false;
while ( chunk ) {
var loc = locate( chunk.start );
if ( chunk.intro.length ) {
addEdit( chunk.intro, '', loc, -1, hasContent );
}
if ( chunk.edited ) {
addEdit( chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1, hasContent );
} else {
addUneditedChunk( chunk, loc );
}
if ( chunk.outro.length ) {
addEdit( chunk.outro, '', loc, -1, hasContent );
}
if ( chunk.content || chunk.intro || chunk.outro ) hasContent = true;
var nextChunk = chunk.next;
chunk = nextChunk;
}
offsets.sourceIndex = offsets.sourceIndex || 0;
offsets.sourceCodeLine = offsets.sourceCodeLine || 0;
offsets.sourceCodeColumn = offsets.sourceCodeColumn || 0;
offsets.sourceCodeName = offsets.sourceCodeName || 0;
return rawLines.map( function (segments) {
var generatedCodeColumn = 0;
return segments.map( function (segment) {
var arr = [
segment.generatedCodeColumn - generatedCodeColumn,
segment.sourceIndex - offsets.sourceIndex,
segment.sourceCodeLine - offsets.sourceCodeLine,
segment.sourceCodeColumn - offsets.sourceCodeColumn
];
generatedCodeColumn = segment.generatedCodeColumn;
offsets.sourceIndex = segment.sourceIndex;
offsets.sourceCodeLine = segment.sourceCodeLine;
offsets.sourceCodeColumn = segment.sourceCodeColumn;
if ( ~segment.sourceCodeName ) {
arr.push( segment.sourceCodeName - offsets.sourceCodeName );
offsets.sourceCodeName = segment.sourceCodeName;
}
return vlq.encode( arr );
}).join( ',' );
}).join( ';' ) + getSemis(outro);
}
function getRelativePath ( from, to ) {
var fromParts = from.split( /[\/\\]/ );
var toParts = to.split( /[\/\\]/ );
fromParts.pop(); // get dirname
while ( fromParts[0] === toParts[0] ) {
fromParts.shift();
toParts.shift();
}
if ( fromParts.length ) {
var i = fromParts.length;
while ( i-- ) fromParts[i] = '..';
}
return fromParts.concat( toParts ).join( '/' );
}
var toString = Object.prototype.toString;
function isObject ( thing ) {
return toString.call( thing ) === '[object Object]';
}
function MagicString ( string, options ) {
if ( options === void 0 ) options = {};
var chunk = new Chunk( 0, string.length, string );
Object.defineProperties( this, {
original: { writable: true, value: string },
outro: { writable: true, value: '' },
intro: { writable: true, value: '' },
firstChunk: { writable: true, value: chunk },
lastChunk: { writable: true, value: chunk },
lastSearchedChunk: { writable: true, value: chunk },
byStart: { writable: true, value: {} },
byEnd: { writable: true, value: {} },
filename: { writable: true, value: options.filename },
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
sourcemapLocations: { writable: true, value: {} },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: guessIndent( string ) }
});
if ( false ) {}
this.byStart[ 0 ] = chunk;
this.byEnd[ string.length ] = chunk;
}
MagicString.prototype = {
addSourcemapLocation: function addSourcemapLocation ( char ) {
this.sourcemapLocations[ char ] = true;
},
append: function append ( content ) {
if ( typeof content !== 'string' ) throw new TypeError( 'outro content must be a string' );
this.outro += content;
return this;
},
clone: function clone () {
var cloned = new MagicString( this.original, { filename: this.filename });
var originalChunk = this.firstChunk;
var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while ( originalChunk ) {
cloned.byStart[ clonedChunk.start ] = clonedChunk;
cloned.byEnd[ clonedChunk.end ] = clonedChunk;
var nextOriginalChunk = originalChunk.next;
var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if ( nextClonedChunk ) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if ( this.indentExclusionRanges ) {
cloned.indentExclusionRanges = typeof this.indentExclusionRanges[0] === 'number' ?
[ this.indentExclusionRanges[0], this.indentExclusionRanges[1] ] :
this.indentExclusionRanges.map( function (range) { return [ range.start, range.end ]; } );
}
Object.keys( this.sourcemapLocations ).forEach( function (loc) {
cloned.sourcemapLocations[ loc ] = true;
});
return cloned;
},
generateMap: function generateMap ( options ) {
options = options || {};
var names = Object.keys( this.storedNames );
if ( false ) {}
var map = new SourceMap({
file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ],
sourcesContent: options.includeContent ? [ this.original ] : [ null ],
names: names,
mappings: this.getMappings( options.hires, 0, {}, names )
});
if ( false ) {}
return map;
},
getIndentString: function getIndentString () {
return this.indentStr === null ? '\t' : this.indentStr;
},
getMappings: function getMappings ( hires, sourceIndex, offsets, names ) {
return encodeMappings( this.original, this.intro, this.outro, this.firstChunk, hires, this.sourcemapLocations, sourceIndex, offsets, names );
},
indent: function indent ( indentStr, options ) {
var this$1 = this;
var pattern = /^[^\r\n]/gm;
if ( isObject( indentStr ) ) {
options = indentStr;
indentStr = undefined;
}
indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' );
if ( indentStr === '' ) return this; // noop
options = options || {};
// Process exclusion ranges
var isExcluded = {};
if ( options.exclude ) {
var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude;
exclusions.forEach( function (exclusion) {
for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) {
isExcluded[i] = true;
}
});
}
var shouldIndentNextCharacter = options.indentStart !== false;
var replacer = function (match) {
if ( shouldIndentNextCharacter ) return ("" + indentStr + match);
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace( pattern, replacer );
var charIndex = 0;
var chunk = this.firstChunk;
while ( chunk ) {
var end = chunk.end;
if ( chunk.edited ) {
if ( !isExcluded[ charIndex ] ) {
chunk.content = chunk.content.replace( pattern, replacer );
if ( chunk.content.length ) {
shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n';
}
}
} else {
charIndex = chunk.start;
while ( charIndex < end ) {
if ( !isExcluded[ charIndex ] ) {
var char = this$1.original[ charIndex ];
if ( char === '\n' ) {
shouldIndentNextCharacter = true;
} else if ( char !== '\r' && shouldIndentNextCharacter ) {
shouldIndentNextCharacter = false;
if ( charIndex === chunk.start ) {
chunk.prepend( indentStr );
} else {
var rhs = chunk.split( charIndex );
rhs.prepend( indentStr );
this$1.byStart[ charIndex ] = rhs;
this$1.byEnd[ charIndex ] = chunk;
chunk = rhs;
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace( pattern, replacer );
return this;
},
insert: function insert () {
throw new Error( 'magicString.insert(...) is deprecated. Use insertRight(...) or insertLeft(...)' );
},
insertLeft: function insertLeft ( index, content ) {
if ( typeof content !== 'string' ) throw new TypeError( 'inserted content must be a string' );
if ( false ) {}
this._split( index );
var chunk = this.byEnd[ index ];
if ( chunk ) {
chunk.append( content );
} else {
this.intro += content;
}
if ( false ) {}
return this;
},
insertRight: function insertRight ( index, content ) {
if ( typeof content !== 'string' ) throw new TypeError( 'inserted content must be a string' );
if ( false ) {}
this._split( index );
var chunk = this.byStart[ index ];
if ( chunk ) {
chunk.prepend( content );
} else {
this.outro += content;
}
if ( false ) {}
return this;
},
move: function move ( start, end, index ) {
if ( index >= start && index <= end ) throw new Error( 'Cannot move a selection inside itself' );
if ( false ) {}
this._split( start );
this._split( end );
this._split( index );
var first = this.byStart[ start ];
var last = this.byEnd[ end ];
var oldLeft = first.previous;
var oldRight = last.next;
var newRight = this.byStart[ index ];
if ( !newRight && last === this.lastChunk ) return this;
var newLeft = newRight ? newRight.previous : this.lastChunk;
if ( oldLeft ) oldLeft.next = oldRight;
if ( oldRight ) oldRight.previous = oldLeft;
if ( newLeft ) newLeft.next = first;
if ( newRight ) newRight.previous = last;
if ( !first.previous ) this.firstChunk = last.next;
if ( !last.next ) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight;
if ( !newLeft ) this.firstChunk = first;
if ( !newRight ) this.lastChunk = last;
if ( false ) {}
return this;
},
overwrite: function overwrite ( start, end, content, storeName ) {
var this$1 = this;
if ( typeof content !== 'string' ) throw new TypeError( 'replacement content must be a string' );
while ( start < 0 ) start += this$1.original.length;
while ( end < 0 ) end += this$1.original.length;
if ( end > this.original.length ) throw new Error( 'end is out of bounds' );
if ( start === end ) throw new Error( 'Cannot overwrite a zero-length range – use insertLeft or insertRight instead' );
if ( false ) {}
this._split( start );
this._split( end );
if ( storeName ) {
var original = this.original.slice( start, end );
this.storedNames[ original ] = true;
}
var first = this.byStart[ start ];
var last = this.byEnd[ end ];
if ( first ) {
first.edit( content, storeName );
if ( first !== last ) {
var chunk = first.next;
while ( chunk !== last ) {
chunk.edit( '', false );
chunk = chunk.next;
}
chunk.edit( '', false );
}
}
else {
// must be inserting at the end
var newChunk = new Chunk( start, end, '' ).edit( content, storeName );
// TODO last chunk in the array may not be the last chunk, if it's moved...
last.next = newChunk;
newChunk.previous = last;
}
if ( false ) {}
return this;
},
prepend: function prepend ( content ) {
if ( typeof content !== 'string' ) throw new TypeError( 'outro content must be a string' );
this.intro = content + this.intro;
return this;
},
remove: function remove ( start, end ) {
var this$1 = this;
while ( start < 0 ) start += this$1.original.length;
while ( end < 0 ) end += this$1.original.length;
if ( start === end ) return this;
if ( start < 0 || end > this.original.length ) throw new Error( 'Character is out of bounds' );
if ( start > end ) throw new Error( 'end must be greater than start' );
return this.overwrite( start, end, '', false );
},
slice: function slice ( start, end ) {
var this$1 = this;
if ( start === void 0 ) start = 0;
if ( end === void 0 ) end = this.original.length;
while ( start < 0 ) start += this$1.original.length;
while ( end < 0 ) end += this$1.original.length;
var result = '';
// find start chunk
var chunk = this.firstChunk;
while ( chunk && ( chunk.start > start || chunk.end <= start ) ) {
// found end chunk before start
if ( chunk.start < end && chunk.end >= end ) {
return result;
}
chunk = chunk.next;
}
if ( chunk && chunk.edited && chunk.start !== start ) throw new Error(("Cannot use replaced character " + start + " as slice start anchor."));
var startChunk = chunk;
while ( chunk ) {
if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) {
result += chunk.intro;
}
var containsEnd = chunk.start < end && chunk.end >= end;
if ( containsEnd && chunk.edited && chunk.end !== end ) throw new Error(("Cannot use replaced character " + end + " as slice end anchor."));
var sliceStart = startChunk === chunk ? start - chunk.start : 0;
var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice( sliceStart, sliceEnd );
if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) {
result += chunk.outro;
}
if ( containsEnd ) {
break;
}
chunk = chunk.next;
}
return result;
},
// TODO deprecate this? not really very useful
snip: function snip ( start, end ) {
var clone = this.clone();
clone.remove( 0, start );
clone.remove( end, clone.original.length );
return clone;
},
_split: function _split ( index ) {
var this$1 = this;
if ( this.byStart[ index ] || this.byEnd[ index ] ) return;
if ( false ) {}
var chunk = this.lastSearchedChunk;
var searchForward = index > chunk.end;
while ( true ) {
if ( chunk.contains( index ) ) return this$1._splitChunk( chunk, index );
chunk = searchForward ?
this$1.byStart[ chunk.end ] :
this$1.byEnd[ chunk.start ];
}
},
_splitChunk: function _splitChunk ( chunk, index ) {
if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements)
var loc = getLocator( this.original )( index );
throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") );
}
var newChunk = chunk.split( index );
this.byEnd[ index ] = chunk;
this.byStart[ index ] = newChunk;
this.byEnd[ newChunk.end ] = newChunk;
if ( chunk === this.lastChunk ) this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
if ( false ) {}
return true;
},
toString: function toString () {
var str = this.intro;
var chunk = this.firstChunk;
while ( chunk ) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
},
trimLines: function trimLines () {
return this.trim('[\\r\\n]');
},
trim: function trim ( charType ) {
return this.trimStart( charType ).trimEnd( charType );
},
trimEnd: function trimEnd ( charType ) {
var this$1 = this;
var rx = new RegExp( ( charType || '\\s' ) + '+$' );
this.outro = this.outro.replace( rx, '' );
if ( this.outro.length ) return this;
var chunk = this.lastChunk;
do {
var end = chunk.end;
var aborted = chunk.trimEnd( rx );
// if chunk was trimmed, we have a new lastChunk
if ( chunk.end !== end ) {
this$1.lastChunk = chunk.next;
this$1.byEnd[ chunk.end ] = chunk;
this$1.byStart[ chunk.next.start ] = chunk.next;
}
if ( aborted ) return this$1;
chunk = chunk.previous;
} while ( chunk );
return this;
},
trimStart: function trimStart ( charType ) {
var this$1 = this;
var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
this.intro = this.intro.replace( rx, '' );
if ( this.intro.length ) return this;
var chunk = this.firstChunk;
do {
var end = chunk.end;
var aborted = chunk.trimStart( rx );
if ( chunk.end !== end ) {
// special case...
if ( chunk === this$1.lastChunk ) this$1.lastChunk = chunk.next;
this$1.byEnd[ chunk.end ] = chunk;
this$1.byStart[ chunk.next.start ] = chunk.next;
}
if ( aborted ) return this$1;
chunk = chunk.next;
} while ( chunk );
return this;
}
};
var hasOwnProp = Object.prototype.hasOwnProperty;
function Bundle ( options ) {
if ( options === void 0 ) options = {};
this.intro = options.intro || '';
this.separator = options.separator !== undefined ? options.separator : '\n';
this.sources = [];
this.uniqueSources = [];
this.uniqueSourceIndexByFilename = {};
}
Bundle.prototype = {
addSource: function addSource ( source ) {
if ( source instanceof MagicString ) {
return this.addSource({
content: source,
filename: source.filename,
separator: this.separator
});
}
if ( !isObject( source ) || !source.content ) {
throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' );
}
[ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) {
if ( !hasOwnProp.call( source, option ) ) source[ option ] = source.content[ option ];
});
if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up
source.separator = this.separator;
}
if ( source.filename ) {
if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) {
this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length;
this.uniqueSources.push({ filename: source.filename, content: source.content.original });
} else {
var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ];
if ( source.content.original !== uniqueSource.content ) {
throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") );
}
}
}
this.sources.push( source );
return this;
},
append: function append ( str, options ) {
this.addSource({
content: new MagicString( str ),
separator: ( options && options.separator ) || ''
});
return this;
},
clone: function clone () {
var bundle = new Bundle({
intro: this.intro,
separator: this.separator
});
this.sources.forEach( function (source) {
bundle.addSource({
filename: source.filename,
content: source.content.clone(),
separator: source.separator
});
});
return bundle;
},
generateMap: function generateMap ( options ) {
var this$1 = this;
options = options || {};
var offsets = {};
var names = [];
this.sources.forEach( function (source) {
Object.keys( source.content.storedNames ).forEach( function (name) {
if ( !~names.indexOf( name ) ) names.push( name );
});
});
var encoded = (
getSemis( this.intro ) +
this.sources.map( function ( source, i ) {
var prefix = ( i > 0 ) ? ( getSemis( source.separator ) || ',' ) : '';
var mappings;
// we don't bother encoding sources without a filename
if ( !source.filename ) {
mappings = getSemis( source.content.toString() );
} else {
var sourceIndex = this$1.uniqueSourceIndexByFilename[ source.filename ];
mappings = source.content.getMappings( options.hires, sourceIndex, offsets, names );
}
return prefix + mappings;
}).join( '' )
);
return new SourceMap({
file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
sources: this.uniqueSources.map( function (source) {
return options.file ? getRelativePath( options.file, source.filename ) : source.filename;
}),
sourcesContent: this.uniqueSources.map( function (source) {
return options.includeContent ? source.content : null;
}),
names: names,
mappings: encoded
});
},
getIndentString: function getIndentString () {
var indentStringCounts = {};
this.sources.forEach( function (source) {
var indentStr = source.content.indentStr;
if ( indentStr === null ) return;
if ( !indentStringCounts[ indentStr ] ) indentStringCounts[ indentStr ] = 0;
indentStringCounts[ indentStr ] += 1;
});
return ( Object.keys( indentStringCounts ).sort( function ( a, b ) {
return indentStringCounts[a] - indentStringCounts[b];
})[0] ) || '\t';
},
indent: function indent ( indentStr ) {
var this$1 = this;
if ( !arguments.length ) {
indentStr = this.getIndentString();
}
if ( indentStr === '' ) return this; // noop
var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n';
this.sources.forEach( function ( source, i ) {
var separator = source.separator !== undefined ? source.separator : this$1.separator;
var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) );
source.content.indent( indentStr, {
exclude: source.indentExclusionRanges,
indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
});
// TODO this is a very slow way to determine this
trailingNewline = source.content.toString().slice( 0, -1 ) === '\n';
});
if ( this.intro ) {
this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) {
return index > 0 ? indentStr + match : match;
});
}
return this;
},
prepend: function prepend ( str ) {
this.intro = str + this.intro;
return this;
},
toString: function toString () {
var this$1 = this;
var body = this.sources.map( function ( source, i ) {
var separator = source.separator !== undefined ? source.separator : this$1.separator;
var str = ( i > 0 ? separator : '' ) + source.content.toString();
return str;
}).join( '' );
return this.intro + body;
},
trimLines: function trimLines () {
return this.trim('[\\r\\n]');
},
trim: function trim ( charType ) {
return this.trimStart( charType ).trimEnd( charType );
},
trimStart: function trimStart ( charType ) {
var this$1 = this;
var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
this.intro = this.intro.replace( rx, '' );
if ( !this.intro ) {
var source;
var i = 0;
do {
source = this$1.sources[i];
if ( !source ) {
break;
}
source.content.trimStart( charType );
i += 1;
} while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
}
return this;
},
trimEnd: function trimEnd ( charType ) {
var this$1 = this;
var rx = new RegExp( ( charType || '\\s' ) + '+$' );
var source;
var i = this.sources.length - 1;
do {
source = this$1.sources[i];
if ( !source ) {
this$1.intro = this$1.intro.replace( rx, '' );
break;
}
source.content.trimEnd( charType );
i -= 1;
} while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
return this;
}
};
MagicString.Bundle = Bundle;
module.exports = MagicString;
//# sourceMappingURL=magic-string.cjs.js.map |
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("uicolor","az",{title:"Panellərin rəng seçimi",options:"Color Options",highlight:"Highlight",selected:"Selected Color",predefined:"Öncədən təyin edilmiş rənglərin yığımları",config:"Bu sətri sizin config.js faylına əlavə edin"}); |
/**
* @author mrdoob / http://mrdoob.com/
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author julianwa / https://github.com/julianwa
*/
THREE.RenderableObject = function () {
this.id = 0;
this.object = null;
this.z = 0;
this.renderOrder = 0;
};
//
THREE.RenderableFace = function () {
this.id = 0;
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.v3 = new THREE.RenderableVertex();
this.normalModel = new THREE.Vector3();
this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
this.vertexNormalsLength = 0;
this.color = new THREE.Color();
this.material = null;
this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
this.z = 0;
this.renderOrder = 0;
};
//
THREE.RenderableVertex = function () {
this.position = new THREE.Vector3();
this.positionWorld = new THREE.Vector3();
this.positionScreen = new THREE.Vector4();
this.visible = true;
};
THREE.RenderableVertex.prototype.copy = function ( vertex ) {
this.positionWorld.copy( vertex.positionWorld );
this.positionScreen.copy( vertex.positionScreen );
};
//
THREE.RenderableLine = function () {
this.id = 0;
this.v1 = new THREE.RenderableVertex();
this.v2 = new THREE.RenderableVertex();
this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
this.material = null;
this.z = 0;
this.renderOrder = 0;
};
//
THREE.RenderableSprite = function () {
this.id = 0;
this.object = null;
this.x = 0;
this.y = 0;
this.z = 0;
this.rotation = 0;
this.scale = new THREE.Vector2();
this.material = null;
this.renderOrder = 0;
};
//
THREE.Projector = function () {
var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
_vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
_face, _faceCount, _facePool = [], _facePoolLength = 0,
_line, _lineCount, _linePool = [], _linePoolLength = 0,
_sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
_renderData = { objects: [], lights: [], elements: [] },
_vector3 = new THREE.Vector3(),
_vector4 = new THREE.Vector4(),
_clipBox = new THREE.Box3( new THREE.Vector3( - 1, - 1, - 1 ), new THREE.Vector3( 1, 1, 1 ) ),
_boundingBox = new THREE.Box3(),
_points3 = new Array( 3 ),
_points4 = new Array( 4 ),
_viewMatrix = new THREE.Matrix4(),
_viewProjectionMatrix = new THREE.Matrix4(),
_modelMatrix,
_modelViewProjectionMatrix = new THREE.Matrix4(),
_normalMatrix = new THREE.Matrix3(),
_frustum = new THREE.Frustum(),
_clippedVertex1PositionScreen = new THREE.Vector4(),
_clippedVertex2PositionScreen = new THREE.Vector4();
//
this.projectVector = function ( vector, camera ) {
console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
vector.project( camera );
};
this.unprojectVector = function ( vector, camera ) {
console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
vector.unproject( camera );
};
this.pickingRay = function ( vector, camera ) {
console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
};
//
var RenderList = function () {
var normals = [];
var uvs = [];
var object = null;
var material = null;
var normalMatrix = new THREE.Matrix3();
function setObject( value ) {
object = value;
material = object.material;
normalMatrix.getNormalMatrix( object.matrixWorld );
normals.length = 0;
uvs.length = 0;
}
function projectVertex( vertex ) {
var position = vertex.position;
var positionWorld = vertex.positionWorld;
var positionScreen = vertex.positionScreen;
positionWorld.copy( position ).applyMatrix4( _modelMatrix );
positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
var invW = 1 / positionScreen.w;
positionScreen.x *= invW;
positionScreen.y *= invW;
positionScreen.z *= invW;
vertex.visible = positionScreen.x >= - 1 && positionScreen.x <= 1 &&
positionScreen.y >= - 1 && positionScreen.y <= 1 &&
positionScreen.z >= - 1 && positionScreen.z <= 1;
}
function pushVertex( x, y, z ) {
_vertex = getNextVertexInPool();
_vertex.position.set( x, y, z );
projectVertex( _vertex );
}
function pushNormal( x, y, z ) {
normals.push( x, y, z );
}
function pushUv( x, y ) {
uvs.push( x, y );
}
function checkTriangleVisibility( v1, v2, v3 ) {
if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
_points3[ 0 ] = v1.positionScreen;
_points3[ 1 ] = v2.positionScreen;
_points3[ 2 ] = v3.positionScreen;
return _clipBox.intersectsBox( _boundingBox.setFromPoints( _points3 ) );
}
function checkBackfaceCulling( v1, v2, v3 ) {
return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
( v2.positionScreen.y - v1.positionScreen.y ) -
( v3.positionScreen.y - v1.positionScreen.y ) *
( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
}
function pushLine( a, b ) {
var v1 = _vertexPool[ a ];
var v2 = _vertexPool[ b ];
_line = getNextLineInPool();
_line.id = object.id;
_line.v1.copy( v1 );
_line.v2.copy( v2 );
_line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
_line.renderOrder = object.renderOrder;
_line.material = object.material;
_renderData.elements.push( _line );
}
function pushTriangle( a, b, c ) {
var v1 = _vertexPool[ a ];
var v2 = _vertexPool[ b ];
var v3 = _vertexPool[ c ];
if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
_face = getNextFaceInPool();
_face.id = object.id;
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
_face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
_face.renderOrder = object.renderOrder;
// use first vertex normal as face normal
_face.normalModel.fromArray( normals, a * 3 );
_face.normalModel.applyMatrix3( normalMatrix ).normalize();
for ( var i = 0; i < 3; i ++ ) {
var normal = _face.vertexNormalsModel[ i ];
normal.fromArray( normals, arguments[ i ] * 3 );
normal.applyMatrix3( normalMatrix ).normalize();
var uv = _face.uvs[ i ];
uv.fromArray( uvs, arguments[ i ] * 2 );
}
_face.vertexNormalsLength = 3;
_face.material = object.material;
_renderData.elements.push( _face );
}
}
return {
setObject: setObject,
projectVertex: projectVertex,
checkTriangleVisibility: checkTriangleVisibility,
checkBackfaceCulling: checkBackfaceCulling,
pushVertex: pushVertex,
pushNormal: pushNormal,
pushUv: pushUv,
pushLine: pushLine,
pushTriangle: pushTriangle
}
};
var renderList = new RenderList();
this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
_faceCount = 0;
_lineCount = 0;
_spriteCount = 0;
_renderData.elements.length = 0;
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
if ( camera.parent === null ) camera.updateMatrixWorld();
_viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
_viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
_frustum.setFromMatrix( _viewProjectionMatrix );
//
_objectCount = 0;
_renderData.objects.length = 0;
_renderData.lights.length = 0;
function addObject( object ) {
_object = getNextObjectInPool();
_object.id = object.id;
_object.object = object;
_vector3.setFromMatrixPosition( object.matrixWorld );
_vector3.applyMatrix4( _viewProjectionMatrix );
_object.z = _vector3.z;
_object.renderOrder = object.renderOrder;
_renderData.objects.push( _object );
}
scene.traverseVisible( function ( object ) {
if ( object instanceof THREE.Light ) {
_renderData.lights.push( object );
} else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
if ( object.material.visible === false ) return;
if ( object.frustumCulled === true && _frustum.intersectsObject( object ) === false ) return;
addObject( object );
} else if ( object instanceof THREE.Sprite ) {
if ( object.material.visible === false ) return;
if ( object.frustumCulled === true && _frustum.intersectsSprite( object ) === false ) return;
addObject( object );
}
} );
if ( sortObjects === true ) {
_renderData.objects.sort( painterSort );
}
//
for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
var object = _renderData.objects[ o ].object;
var geometry = object.geometry;
renderList.setObject( object );
_modelMatrix = object.matrixWorld;
_vertexCount = 0;
if ( object instanceof THREE.Mesh ) {
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
var groups = geometry.groups;
if ( attributes.position === undefined ) continue;
var positions = attributes.position.array;
for ( var i = 0, l = positions.length; i < l; i += 3 ) {
renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
}
if ( attributes.normal !== undefined ) {
var normals = attributes.normal.array;
for ( var i = 0, l = normals.length; i < l; i += 3 ) {
renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
}
}
if ( attributes.uv !== undefined ) {
var uvs = attributes.uv.array;
for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
}
}
if ( geometry.index !== null ) {
var indices = geometry.index.array;
if ( groups.length > 0 ) {
for ( var g = 0; g < groups.length; g ++ ) {
var group = groups[ g ];
for ( var i = group.start, l = group.start + group.count; i < l; i += 3 ) {
renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
}
} else {
for ( var i = 0, l = indices.length; i < l; i += 3 ) {
renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
}
} else {
for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
renderList.pushTriangle( i, i + 1, i + 2 );
}
}
} else if ( geometry instanceof THREE.Geometry ) {
var vertices = geometry.vertices;
var faces = geometry.faces;
var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
_normalMatrix.getNormalMatrix( _modelMatrix );
var material = object.material;
var isFaceMaterial = material instanceof THREE.MultiMaterial;
var objectMaterials = isFaceMaterial === true ? object.material : null;
for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
var vertex = vertices[ v ];
_vector3.copy( vertex );
if ( material.morphTargets === true ) {
var morphTargets = geometry.morphTargets;
var morphInfluences = object.morphTargetInfluences;
for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
var influence = morphInfluences[ t ];
if ( influence === 0 ) continue;
var target = morphTargets[ t ];
var targetVertex = target.vertices[ v ];
_vector3.x += ( targetVertex.x - vertex.x ) * influence;
_vector3.y += ( targetVertex.y - vertex.y ) * influence;
_vector3.z += ( targetVertex.z - vertex.z ) * influence;
}
}
renderList.pushVertex( _vector3.x, _vector3.y, _vector3.z );
}
for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
var face = faces[ f ];
material = isFaceMaterial === true
? objectMaterials.materials[ face.materialIndex ]
: object.material;
if ( material === undefined ) continue;
var side = material.side;
var v1 = _vertexPool[ face.a ];
var v2 = _vertexPool[ face.b ];
var v3 = _vertexPool[ face.c ];
if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
if ( side !== THREE.DoubleSide ) {
if ( side === THREE.FrontSide && visible === false ) continue;
if ( side === THREE.BackSide && visible === true ) continue;
}
_face = getNextFaceInPool();
_face.id = object.id;
_face.v1.copy( v1 );
_face.v2.copy( v2 );
_face.v3.copy( v3 );
_face.normalModel.copy( face.normal );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
_face.normalModel.negate();
}
_face.normalModel.applyMatrix3( _normalMatrix ).normalize();
var faceVertexNormals = face.vertexNormals;
for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
var normalModel = _face.vertexNormalsModel[ n ];
normalModel.copy( faceVertexNormals[ n ] );
if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
normalModel.negate();
}
normalModel.applyMatrix3( _normalMatrix ).normalize();
}
_face.vertexNormalsLength = faceVertexNormals.length;
var vertexUvs = faceVertexUvs[ f ];
if ( vertexUvs !== undefined ) {
for ( var u = 0; u < 3; u ++ ) {
_face.uvs[ u ].copy( vertexUvs[ u ] );
}
}
_face.color = face.color;
_face.material = material;
_face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
_face.renderOrder = object.renderOrder;
_renderData.elements.push( _face );
}
}
} else if ( object instanceof THREE.Line ) {
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
if ( attributes.position !== undefined ) {
var positions = attributes.position.array;
for ( var i = 0, l = positions.length; i < l; i += 3 ) {
renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
}
if ( geometry.index !== null ) {
var indices = geometry.index.array;
for ( var i = 0, l = indices.length; i < l; i += 2 ) {
renderList.pushLine( indices[ i ], indices[ i + 1 ] );
}
} else {
var step = object instanceof THREE.LineSegments ? 2 : 1;
for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i += step ) {
renderList.pushLine( i, i + 1 );
}
}
}
} else if ( geometry instanceof THREE.Geometry ) {
_modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
var vertices = object.geometry.vertices;
if ( vertices.length === 0 ) continue;
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
var step = object instanceof THREE.LineSegments ? 2 : 1;
for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
v1 = getNextVertexInPool();
v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
if ( ( v + 1 ) % step > 0 ) continue;
v2 = _vertexPool[ _vertexCount - 2 ];
_clippedVertex1PositionScreen.copy( v1.positionScreen );
_clippedVertex2PositionScreen.copy( v2.positionScreen );
if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
// Perform the perspective divide
_clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
_clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
_line = getNextLineInPool();
_line.id = object.id;
_line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
_line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
_line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
_line.renderOrder = object.renderOrder;
_line.material = object.material;
if ( object.material.vertexColors === THREE.VertexColors ) {
_line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
_line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
}
_renderData.elements.push( _line );
}
}
}
} else if ( object instanceof THREE.Sprite ) {
_vector4.set( _modelMatrix.elements[ 12 ], _modelMatrix.elements[ 13 ], _modelMatrix.elements[ 14 ], 1 );
_vector4.applyMatrix4( _viewProjectionMatrix );
var invW = 1 / _vector4.w;
_vector4.z *= invW;
if ( _vector4.z >= - 1 && _vector4.z <= 1 ) {
_sprite = getNextSpriteInPool();
_sprite.id = object.id;
_sprite.x = _vector4.x * invW;
_sprite.y = _vector4.y * invW;
_sprite.z = _vector4.z;
_sprite.renderOrder = object.renderOrder;
_sprite.object = object;
_sprite.rotation = object.rotation;
_sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[ 0 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 12 ] ) );
_sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[ 5 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 13 ] ) );
_sprite.material = object.material;
_renderData.elements.push( _sprite );
}
}
}
if ( sortElements === true ) {
_renderData.elements.sort( painterSort );
}
return _renderData;
};
// Pools
function getNextObjectInPool() {
if ( _objectCount === _objectPoolLength ) {
var object = new THREE.RenderableObject();
_objectPool.push( object );
_objectPoolLength ++;
_objectCount ++;
return object;
}
return _objectPool[ _objectCount ++ ];
}
function getNextVertexInPool() {
if ( _vertexCount === _vertexPoolLength ) {
var vertex = new THREE.RenderableVertex();
_vertexPool.push( vertex );
_vertexPoolLength ++;
_vertexCount ++;
return vertex;
}
return _vertexPool[ _vertexCount ++ ];
}
function getNextFaceInPool() {
if ( _faceCount === _facePoolLength ) {
var face = new THREE.RenderableFace();
_facePool.push( face );
_facePoolLength ++;
_faceCount ++;
return face;
}
return _facePool[ _faceCount ++ ];
}
function getNextLineInPool() {
if ( _lineCount === _linePoolLength ) {
var line = new THREE.RenderableLine();
_linePool.push( line );
_linePoolLength ++;
_lineCount ++;
return line;
}
return _linePool[ _lineCount ++ ];
}
function getNextSpriteInPool() {
if ( _spriteCount === _spritePoolLength ) {
var sprite = new THREE.RenderableSprite();
_spritePool.push( sprite );
_spritePoolLength ++;
_spriteCount ++;
return sprite;
}
return _spritePool[ _spriteCount ++ ];
}
//
function painterSort( a, b ) {
if ( a.renderOrder !== b.renderOrder ) {
return a.renderOrder - b.renderOrder;
} else if ( a.z !== b.z ) {
return b.z - a.z;
} else if ( a.id !== b.id ) {
return a.id - b.id;
} else {
return 0;
}
}
function clipLine( s1, s2 ) {
var alpha1 = 0, alpha2 = 1,
// Calculate the boundary coordinate of each vertex for the near and far clip planes,
// Z = -1 and Z = +1, respectively.
bc1near = s1.z + s1.w,
bc2near = s2.z + s2.w,
bc1far = - s1.z + s1.w,
bc2far = - s2.z + s2.w;
if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
// Both vertices lie entirely within all clip planes.
return true;
} else if ( ( bc1near < 0 && bc2near < 0 ) || ( bc1far < 0 && bc2far < 0 ) ) {
// Both vertices lie entirely outside one of the clip planes.
return false;
} else {
// The line segment spans at least one clip plane.
if ( bc1near < 0 ) {
// v1 lies outside the near plane, v2 inside
alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
} else if ( bc2near < 0 ) {
// v2 lies outside the near plane, v1 inside
alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
}
if ( bc1far < 0 ) {
// v1 lies outside the far plane, v2 inside
alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
} else if ( bc2far < 0 ) {
// v2 lies outside the far plane, v2 inside
alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
}
if ( alpha2 < alpha1 ) {
// The line segment spans two boundaries, but is outside both of them.
// (This can't happen when we're only clipping against just near/far but good
// to leave the check here for future usage if other clip planes are added.)
return false;
} else {
// Update the s1 and s2 vertices to match the clipped line segment.
s1.lerp( s2, alpha1 );
s2.lerp( s1, 1 - alpha2 );
return true;
}
}
}
};
|
var buckets={};
(function(){buckets.defaultCompare=function(a,b){return a<b?-1:a===b?0:1};buckets.defaultEquals=function(a,b){return a===b};buckets.defaultToString=function(a){return null===a?"BUCKETS_NULL":buckets.isUndefined(a)?"BUCKETS_UNDEFINED":buckets.isString(a)?a:a.toString()};buckets.isFunction=function(a){return"function"===typeof a};buckets.isUndefined=function(a){return"undefined"===typeof a};buckets.isString=function(a){return"[object String]"===Object.prototype.toString.call(a)};buckets.reverseCompareFunction=function(a){return buckets.isFunction(a)?
function(b,c){return-1*a(b,c)}:function(a,c){return a<c?1:a===c?0:-1}};buckets.compareToEquals=function(a){return function(b,c){return 0===a(b,c)}};buckets.arrays={};buckets.arrays.indexOf=function(a,b,c){c=c||buckets.defaultEquals;for(var d=a.length,e=0;e<d;e++)if(c(a[e],b))return e;return-1};buckets.arrays.lastIndexOf=function(a,b,c){c=c||buckets.defaultEquals;for(var d=a.length-1;0<=d;d--)if(c(a[d],b))return d;return-1};buckets.arrays.contains=function(a,b,c){return 0<=buckets.arrays.indexOf(a,
b,c)};buckets.arrays.remove=function(a,b,c){b=buckets.arrays.indexOf(a,b,c);if(0>b)return!1;a.splice(b,1);return!0};buckets.arrays.frequency=function(a,b,c){c=c||buckets.defaultEquals;for(var d=a.length,e=0,f=0;f<d;f++)c(a[f],b)&&e++;return e};buckets.arrays.equals=function(a,b,c){c=c||buckets.defaultEquals;if(a.length!==b.length)return!1;for(var d=a.length,e=0;e<d;e++)if(!c(a[e],b[e]))return!1;return!0};buckets.arrays.copy=function(a){return a.concat()};buckets.arrays.swap=function(a,b,c){if(0>b||
b>=a.length||0>c||c>=a.length)return!1;var d=a[b];a[b]=a[c];a[c]=d;return!0};buckets.arrays.forEach=function(a,b){for(var c=a.length,d=0;d<c&&!1!==b(a[d]);d++);};buckets.LinkedList=function(){this.lastNode=this.firstNode=null;this.nElements=0};buckets.LinkedList.prototype.add=function(a,b){buckets.isUndefined(b)&&(b=this.nElements);if(0>b||b>this.nElements||buckets.isUndefined(a))return!1;var c=this.createNode(a);if(0===this.nElements)this.lastNode=this.firstNode=c;else if(b===this.nElements)this.lastNode=
this.lastNode.next=c;else if(0===b)c.next=this.firstNode,this.firstNode=c;else{var d=this.nodeAtIndex(b-1);c.next=d.next;d.next=c}this.nElements++;return!0};buckets.LinkedList.prototype.first=function(){if(null!==this.firstNode)return this.firstNode.element};buckets.LinkedList.prototype.last=function(){if(null!==this.lastNode)return this.lastNode.element};buckets.LinkedList.prototype.elementAtIndex=function(a){a=this.nodeAtIndex(a);return null===a?void 0:a.element};buckets.LinkedList.prototype.indexOf=
function(a,b){var c=b||buckets.defaultEquals;if(buckets.isUndefined(a))return-1;for(var d=this.firstNode,e=0;null!==d;){if(c(d.element,a))return e;e++;d=d.next}return-1};buckets.LinkedList.prototype.contains=function(a,b){return 0<=this.indexOf(a,b)};buckets.LinkedList.prototype.remove=function(a,b){var c=b||buckets.defaultEquals;if(1>this.nElements||buckets.isUndefined(a))return!1;for(var d=null,e=this.firstNode;null!==e;){if(c(e.element,a))return e===this.firstNode?(this.firstNode=this.firstNode.next,
e===this.lastNode&&(this.lastNode=null)):(e===this.lastNode&&(this.lastNode=d),d.next=e.next,e.next=null),this.nElements--,!0;d=e;e=e.next}return!1};buckets.LinkedList.prototype.clear=function(){this.lastNode=this.firstNode=null;this.nElements=0};buckets.LinkedList.prototype.equals=function(a,b){var c=b||buckets.defaultEquals;return a instanceof buckets.LinkedList&&this.size()===a.size()?this.equalsAux(this.firstNode,a.firstNode,c):!1};buckets.LinkedList.prototype.equalsAux=function(a,b,c){for(;null!==
a;){if(!c(a.element,b.element))return!1;a=a.next;b=b.next}return!0};buckets.LinkedList.prototype.removeElementAtIndex=function(a){if(!(0>a||a>=this.nElements)){var b;1===this.nElements?(b=this.firstNode.element,this.lastNode=this.firstNode=null):(a=this.nodeAtIndex(a-1),null===a?(b=this.firstNode.element,this.firstNode=this.firstNode.next):a.next===this.lastNode&&(b=this.lastNode.element,this.lastNode=a),null!==a&&(b=a.next.element,a.next=a.next.next));this.nElements--;return b}};buckets.LinkedList.prototype.forEach=
function(a){for(var b=this.firstNode;null!==b&&!1!==a(b.element);)b=b.next};buckets.LinkedList.prototype.reverse=function(){for(var a=null,b=this.firstNode,c=null;null!==b;)c=b.next,b.next=a,a=b,b=c;c=this.firstNode;this.firstNode=this.lastNode;this.lastNode=c};buckets.LinkedList.prototype.toArray=function(){for(var a=[],b=this.firstNode;null!==b;)a.push(b.element),b=b.next;return a};buckets.LinkedList.prototype.size=function(){return this.nElements};buckets.LinkedList.prototype.isEmpty=function(){return 0>=
this.nElements};buckets.LinkedList.prototype.nodeAtIndex=function(a){if(0>a||a>=this.nElements)return null;if(a===this.nElements-1)return this.lastNode;for(var b=this.firstNode,c=0;c<a;c++)b=b.next;return b};buckets.LinkedList.prototype.createNode=function(a){return{element:a,next:null}};buckets.Dictionary=function(a){this.table={};this.nElements=0;this.toStr=a||buckets.defaultToString};buckets.Dictionary.prototype.get=function(a){a=this.table[this.toStr(a)];return buckets.isUndefined(a)?void 0:a.value};
buckets.Dictionary.prototype.set=function(a,b){if(!buckets.isUndefined(a)&&!buckets.isUndefined(b)){var c,d=this.toStr(a);c=this.table[d];buckets.isUndefined(c)?(this.nElements++,c=void 0):c=c.value;this.table[d]={key:a,value:b};return c}};buckets.Dictionary.prototype.remove=function(a){a=this.toStr(a);var b=this.table[a];if(!buckets.isUndefined(b))return delete this.table[a],this.nElements--,b.value};buckets.Dictionary.prototype.keys=function(){var a=[],b;for(b in this.table)this.table.hasOwnProperty(b)&&
a.push(this.table[b].key);return a};buckets.Dictionary.prototype.values=function(){var a=[],b;for(b in this.table)this.table.hasOwnProperty(b)&&a.push(this.table[b].value);return a};buckets.Dictionary.prototype.forEach=function(a){for(var b in this.table)if(this.table.hasOwnProperty(b)){var c=this.table[b];if(!1===a(c.key,c.value))break}};buckets.Dictionary.prototype.containsKey=function(a){return!buckets.isUndefined(this.get(a))};buckets.Dictionary.prototype.clear=function(){this.table={};this.nElements=
0};buckets.Dictionary.prototype.size=function(){return this.nElements};buckets.Dictionary.prototype.isEmpty=function(){return 0>=this.nElements};buckets.MultiDictionary=function(a,b){this.parent=new buckets.Dictionary(a);this.equalsF=b||buckets.defaultEquals};buckets.MultiDictionary.prototype.get=function(a){a=this.parent.get(a);return buckets.isUndefined(a)?[]:buckets.arrays.copy(a)};buckets.MultiDictionary.prototype.set=function(a,b){if(buckets.isUndefined(a)||buckets.isUndefined(b))return!1;if(!this.containsKey(a))return this.parent.set(a,
[b]),!0;var c=this.parent.get(a);if(buckets.arrays.contains(c,b,this.equalsF))return!1;c.push(b);return!0};buckets.MultiDictionary.prototype.remove=function(a,b){if(buckets.isUndefined(b)){var c=this.parent.remove(a);return buckets.isUndefined(c)?!1:!0}c=this.parent.get(a);return buckets.arrays.remove(c,b,this.equalsF)?(0===c.length&&this.parent.remove(a),!0):!1};buckets.MultiDictionary.prototype.keys=function(){return this.parent.keys()};buckets.MultiDictionary.prototype.values=function(){for(var a=
this.parent.values(),b=[],c=0;c<a.length;c++)for(var d=a[c],e=0;e<d.length;e++)b.push(d[e]);return b};buckets.MultiDictionary.prototype.containsKey=function(a){return this.parent.containsKey(a)};buckets.MultiDictionary.prototype.clear=function(){return this.parent.clear()};buckets.MultiDictionary.prototype.size=function(){return this.parent.size()};buckets.MultiDictionary.prototype.isEmpty=function(){return this.parent.isEmpty()};buckets.Heap=function(a){this.data=[];this.compare=a||buckets.defaultCompare};
buckets.Heap.prototype.leftChildIndex=function(a){return 2*a+1};buckets.Heap.prototype.rightChildIndex=function(a){return 2*a+2};buckets.Heap.prototype.parentIndex=function(a){return Math.floor((a-1)/2)};buckets.Heap.prototype.minIndex=function(a,b){return b>=this.data.length?a>=this.data.length?-1:a:0>=this.compare(this.data[a],this.data[b])?a:b};buckets.Heap.prototype.siftUp=function(a){for(var b=this.parentIndex(a);0<a&&0<this.compare(this.data[b],this.data[a]);)buckets.arrays.swap(this.data,b,
a),a=b,b=this.parentIndex(a)};buckets.Heap.prototype.siftDown=function(a){for(var b=this.minIndex(this.leftChildIndex(a),this.rightChildIndex(a));0<=b&&0<this.compare(this.data[a],this.data[b]);)buckets.arrays.swap(this.data,b,a),a=b,b=this.minIndex(this.leftChildIndex(a),this.rightChildIndex(a))};buckets.Heap.prototype.peek=function(){if(0<this.data.length)return this.data[0]};buckets.Heap.prototype.add=function(a){if(!buckets.isUndefined(a))return this.data.push(a),this.siftUp(this.data.length-
1),!0};buckets.Heap.prototype.removeRoot=function(){if(0<this.data.length){var a=this.data[0];this.data[0]=this.data[this.data.length-1];this.data.splice(this.data.length-1,1);0<this.data.length&&this.siftDown(0);return a}};buckets.Heap.prototype.contains=function(a){var b=buckets.compareToEquals(this.compare);return buckets.arrays.contains(this.data,a,b)};buckets.Heap.prototype.size=function(){return this.data.length};buckets.Heap.prototype.isEmpty=function(){return 0>=this.data.length};buckets.Heap.prototype.clear=
function(){this.data.length=0};buckets.Heap.prototype.forEach=function(a){buckets.arrays.forEach(this.data,a)};buckets.Stack=function(){this.list=new buckets.LinkedList};buckets.Stack.prototype.push=function(a){return this.list.add(a,0)};buckets.Stack.prototype.add=function(a){return this.list.add(a,0)};buckets.Stack.prototype.pop=function(){return this.list.removeElementAtIndex(0)};buckets.Stack.prototype.peek=function(){return this.list.first()};buckets.Stack.prototype.size=function(){return this.list.size()};
buckets.Stack.prototype.contains=function(a,b){return this.list.contains(a,b)};buckets.Stack.prototype.isEmpty=function(){return this.list.isEmpty()};buckets.Stack.prototype.clear=function(){this.list.clear()};buckets.Stack.prototype.forEach=function(a){this.list.forEach(a)};buckets.Queue=function(){this.list=new buckets.LinkedList};buckets.Queue.prototype.enqueue=function(a){return this.list.add(a)};buckets.Queue.prototype.add=function(a){return this.list.add(a)};buckets.Queue.prototype.dequeue=
function(){if(0!==this.list.size()){var a=this.list.first();this.list.removeElementAtIndex(0);return a}};buckets.Queue.prototype.peek=function(){if(0!==this.list.size())return this.list.first()};buckets.Queue.prototype.size=function(){return this.list.size()};buckets.Queue.prototype.contains=function(a,b){return this.list.contains(a,b)};buckets.Queue.prototype.isEmpty=function(){return 0>=this.list.size()};buckets.Queue.prototype.clear=function(){this.list.clear()};buckets.Queue.prototype.forEach=
function(a){this.list.forEach(a)};buckets.PriorityQueue=function(a){this.heap=new buckets.Heap(buckets.reverseCompareFunction(a))};buckets.PriorityQueue.prototype.enqueue=function(a){return this.heap.add(a)};buckets.PriorityQueue.prototype.add=function(a){return this.heap.add(a)};buckets.PriorityQueue.prototype.dequeue=function(){if(0!==this.heap.size()){var a=this.heap.peek();this.heap.removeRoot();return a}};buckets.PriorityQueue.prototype.peek=function(){return this.heap.peek()};buckets.PriorityQueue.prototype.contains=
function(a){return this.heap.contains(a)};buckets.PriorityQueue.prototype.isEmpty=function(){return this.heap.isEmpty()};buckets.PriorityQueue.prototype.size=function(){return this.heap.size()};buckets.PriorityQueue.prototype.clear=function(){this.heap.clear()};buckets.PriorityQueue.prototype.forEach=function(a){this.heap.forEach(a)};buckets.Set=function(a){this.dictionary=new buckets.Dictionary(a)};buckets.Set.prototype.contains=function(a){return this.dictionary.containsKey(a)};buckets.Set.prototype.add=
function(a){if(this.contains(a)||buckets.isUndefined(a))return!1;this.dictionary.set(a,a);return!0};buckets.Set.prototype.intersection=function(a){var b=this;this.forEach(function(c){a.contains(c)||b.remove(c)})};buckets.Set.prototype.union=function(a){var b=this;a.forEach(function(a){b.add(a)})};buckets.Set.prototype.difference=function(a){var b=this;a.forEach(function(a){b.remove(a)})};buckets.Set.prototype.isSubsetOf=function(a){if(this.size()>a.size())return!1;var b=!0;this.forEach(function(c){if(!a.contains(c))return b=
!1});return b};buckets.Set.prototype.remove=function(a){return this.contains(a)?(this.dictionary.remove(a),!0):!1};buckets.Set.prototype.forEach=function(a){this.dictionary.forEach(function(b,c){return a(c)})};buckets.Set.prototype.toArray=function(){return this.dictionary.values()};buckets.Set.prototype.isEmpty=function(){return this.dictionary.isEmpty()};buckets.Set.prototype.size=function(){return this.dictionary.size()};buckets.Set.prototype.clear=function(){this.dictionary.clear()};buckets.Bag=
function(a){this.toStrF=a||buckets.defaultToString;this.dictionary=new buckets.Dictionary(this.toStrF);this.nElements=0};buckets.Bag.prototype.add=function(a,b){if(isNaN(b)||buckets.isUndefined(b))b=1;if(buckets.isUndefined(a)||0>=b)return!1;this.contains(a)?this.dictionary.get(a).copies+=b:this.dictionary.set(a,{value:a,copies:b});this.nElements+=b;return!0};buckets.Bag.prototype.count=function(a){return this.contains(a)?this.dictionary.get(a).copies:0};buckets.Bag.prototype.contains=function(a){return this.dictionary.containsKey(a)};
buckets.Bag.prototype.remove=function(a,b){if(isNaN(b)||buckets.isUndefined(b))b=1;if(buckets.isUndefined(a)||0>=b||!this.contains(a))return!1;var c=this.dictionary.get(a);this.nElements=b>c.copies?this.nElements-c.copies:this.nElements-b;c.copies-=b;0>=c.copies&&this.dictionary.remove(a);return!0};buckets.Bag.prototype.toArray=function(){for(var a=[],b=this.dictionary.values(),c=b.length,d=0;d<c;d++)for(var e=b[d],f=e.value,e=e.copies,g=0;g<e;g++)a.push(f);return a};buckets.Bag.prototype.toSet=function(){for(var a=
new buckets.Set(this.toStrF),b=this.dictionary.values(),c=b.length,d=0;d<c;d++)a.add(b[d].value);return a};buckets.Bag.prototype.forEach=function(a){this.dictionary.forEach(function(b,c){for(var d=c.value,e=c.copies,f=0;f<e;f++)if(!1===a(d))return!1;return!0})};buckets.Bag.prototype.size=function(){return this.nElements};buckets.Bag.prototype.isEmpty=function(){return 0===this.nElements};buckets.Bag.prototype.clear=function(){this.nElements=0;this.dictionary.clear()};buckets.BSTree=function(a){this.root=
null;this.compare=a||buckets.defaultCompare;this.nElements=0};buckets.BSTree.prototype.add=function(a){return buckets.isUndefined(a)?!1:null!==this.insertNode(this.createNode(a))?(this.nElements++,!0):!1};buckets.BSTree.prototype.clear=function(){this.root=null;this.nElements=0};buckets.BSTree.prototype.isEmpty=function(){return 0===this.nElements};buckets.BSTree.prototype.size=function(){return this.nElements};buckets.BSTree.prototype.contains=function(a){return buckets.isUndefined(a)?!1:null!==
this.searchNode(this.root,a)};buckets.BSTree.prototype.remove=function(a){a=this.searchNode(this.root,a);if(null===a)return!1;this.removeNode(a);this.nElements--;return!0};buckets.BSTree.prototype.inorderTraversal=function(a){this.inorderTraversalAux(this.root,a,{stop:!1})};buckets.BSTree.prototype.preorderTraversal=function(a){this.preorderTraversalAux(this.root,a,{stop:!1})};buckets.BSTree.prototype.postorderTraversal=function(a){this.postorderTraversalAux(this.root,a,{stop:!1})};buckets.BSTree.prototype.levelTraversal=
function(a){this.levelTraversalAux(this.root,a)};buckets.BSTree.prototype.minimum=function(){return this.isEmpty()?void 0:this.minimumAux(this.root).element};buckets.BSTree.prototype.maximum=function(){return this.isEmpty()?void 0:this.maximumAux(this.root).element};buckets.BSTree.prototype.forEach=function(a){this.inorderTraversal(a)};buckets.BSTree.prototype.toArray=function(){var a=[];this.inorderTraversal(function(b){a.push(b)});return a};buckets.BSTree.prototype.height=function(){return this.heightAux(this.root)};
buckets.BSTree.prototype.searchNode=function(a,b){for(var c=null;null!==a&&0!==c;)c=this.compare(b,a.element),0>c?a=a.leftCh:0<c&&(a=a.rightCh);return a};buckets.BSTree.prototype.transplant=function(a,b){null===a.parent?this.root=b:a===a.parent.leftCh?a.parent.leftCh=b:a.parent.rightCh=b;null!==b&&(b.parent=a.parent)};buckets.BSTree.prototype.removeNode=function(a){if(null===a.leftCh)this.transplant(a,a.rightCh);else if(null===a.rightCh)this.transplant(a,a.leftCh);else{var b=this.minimumAux(a.rightCh);
b.parent!==a&&(this.transplant(b,b.rightCh),b.rightCh=a.rightCh,b.rightCh.parent=b);this.transplant(a,b);b.leftCh=a.leftCh;b.leftCh.parent=b}};buckets.BSTree.prototype.inorderTraversalAux=function(a,b,c){null===a||c.stop||(this.inorderTraversalAux(a.leftCh,b,c),c.stop||(c.stop=!1===b(a.element),c.stop||this.inorderTraversalAux(a.rightCh,b,c)))};buckets.BSTree.prototype.levelTraversalAux=function(a,b){var c=new buckets.Queue;for(null!==a&&c.enqueue(a);!c.isEmpty();){a=c.dequeue();if(!1===b(a.element))break;
null!==a.leftCh&&c.enqueue(a.leftCh);null!==a.rightCh&&c.enqueue(a.rightCh)}};buckets.BSTree.prototype.preorderTraversalAux=function(a,b,c){null===a||c.stop||(c.stop=!1===b(a.element),c.stop||(this.preorderTraversalAux(a.leftCh,b,c),c.stop||this.preorderTraversalAux(a.rightCh,b,c)))};buckets.BSTree.prototype.postorderTraversalAux=function(a,b,c){null===a||c.stop||(this.postorderTraversalAux(a.leftCh,b,c),c.stop||(this.postorderTraversalAux(a.rightCh,b,c),c.stop||(c.stop=!1===b(a.element))))};buckets.BSTree.prototype.minimumAux=
function(a){for(;null!==a.leftCh;)a=a.leftCh;return a};buckets.BSTree.prototype.maximumAux=function(a){for(;null!==a.rightCh;)a=a.rightCh;return a};buckets.BSTree.prototype.successorNode=function(a){if(null!==a.rightCh)return this.minimumAux(a.rightCh);for(var b=a.parent;null!==b&&a===b.rightCh;)a=b,b=a.parent;return b};buckets.BSTree.prototype.heightAux=function(a){return null===a?-1:Math.max(this.heightAux(a.leftCh),this.heightAux(a.rightCh))+1};buckets.BSTree.prototype.insertNode=function(a){for(var b=
null,c=this.root,d=null;null!==c;){d=this.compare(a.element,c.element);if(0===d)return null;0>d?(b=c,c=c.leftCh):(b=c,c=c.rightCh)}a.parent=b;null===b?this.root=a:0>this.compare(a.element,b.element)?b.leftCh=a:b.rightCh=a;return a};buckets.BSTree.prototype.createNode=function(a){return{element:a,leftCh:null,rightCh:null,parent:null}};"undefined"!==typeof module&&(module.exports=buckets)})();
|
IntlMessageFormat.__addLocaleData({"locale":"os","pluralRuleFunction":function (n) {n=Math.floor(n);if(n===1)return"one";return"other";}}); |
/**
* API Bound Models for AngularJS
* @version v1.1.5 - 2014-12-10
* @link https://github.com/angular-platanus/restmod
* @author Ignacio Baixas <ignacio@platan.us>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function(angular, undefined) {
'use strict';
/**
* Angular inflection library
* @version v0.2.0 - 2014-08-22
* @link https://github.com/platanus/angular-inflector
* @author Ignacio Baixas <ignacio@platan.us>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function(angular, undefined) {
angular.module('platanus.inflector', [])
/**
* @class inflectorProvider
*
* @description
*
* The inflectorProvider exposes inflector configuration options, mainly related to locales.
*/
.provider('inflector', [function () {
var activeLocale = 'en', localeMap = {
/**
* English transformation rules.
*
* Taken from https://code.google.com/p/inflection-js/source/browse/trunk/inflection.js
*/
en: {
uncountable: [
'music', 'art', 'love', 'happiness', 'advice', 'furniture', 'luggage',
'sugar', 'butter', 'water', 'electricity', 'gas', 'power', 'currency',
'equipment', 'information', 'rice', 'money', 'species', 'series',
'fish', 'sheep', 'moose', 'deer', 'news'
],
plural: [
[new RegExp('(m)an$', 'gi'), '$1en'],
[new RegExp('(pe)rson$', 'gi'), '$1ople'],
[new RegExp('(child)$', 'gi'), '$1ren'],
[new RegExp('^(ox)$', 'gi'), '$1en'],
[new RegExp('(ax|test)is$', 'gi'), '$1es'],
[new RegExp('(octop|vir)us$', 'gi'), '$1i'],
[new RegExp('(alias|status)$', 'gi'), '$1es'],
[new RegExp('(bu)s$', 'gi'), '$1ses'],
[new RegExp('(buffal|tomat|potat)o$', 'gi'), '$1oes'],
[new RegExp('([ti])um$', 'gi'), '$1a'],
[new RegExp('sis$', 'gi'), 'ses'],
[new RegExp('(?:([^f])fe|([lr])f)$', 'gi'), '$1$2ves'],
[new RegExp('(hive)$', 'gi'), '$1s'],
[new RegExp('([^aeiouy]|qu)y$', 'gi'), '$1ies'],
[new RegExp('(x|ch|ss|sh)$', 'gi'), '$1es'],
[new RegExp('(matr|vert|ind)ix|ex$', 'gi'), '$1ices'],
[new RegExp('([m|l])ouse$', 'gi'), '$1ice'],
[new RegExp('(quiz)$', 'gi'), '$1zes'],
[new RegExp('s$', 'gi'), 's'],
[new RegExp('$', 'gi'), 's']
],
singular: [
[new RegExp('(m)en$', 'gi'), '$1an'],
[new RegExp('(pe)ople$', 'gi'), '$1rson'],
[new RegExp('(child)ren$', 'gi'), '$1'],
[new RegExp('([ti])a$', 'gi'), '$1um'],
[new RegExp('((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$','gi'), '$1$2sis'],
[new RegExp('(hive)s$', 'gi'), '$1'],
[new RegExp('(tive)s$', 'gi'), '$1'],
[new RegExp('(curve)s$', 'gi'), '$1'],
[new RegExp('([lr])ves$', 'gi'), '$1f'],
[new RegExp('([^fo])ves$', 'gi'), '$1fe'],
[new RegExp('([^aeiouy]|qu)ies$', 'gi'), '$1y'],
[new RegExp('(s)eries$', 'gi'), '$1eries'],
[new RegExp('(m)ovies$', 'gi'), '$1ovie'],
[new RegExp('(x|ch|ss|sh)es$', 'gi'), '$1'],
[new RegExp('([m|l])ice$', 'gi'), '$1ouse'],
[new RegExp('(bus)es$', 'gi'), '$1'],
[new RegExp('(o)es$', 'gi'), '$1'],
[new RegExp('(shoe)s$', 'gi'), '$1'],
[new RegExp('(cris|ax|test)es$', 'gi'), '$1is'],
[new RegExp('(octop|vir)i$', 'gi'), '$1us'],
[new RegExp('(alias|status)es$', 'gi'), '$1'],
[new RegExp('^(ox)en', 'gi'), '$1'],
[new RegExp('(vert|ind)ices$', 'gi'), '$1ex'],
[new RegExp('(matr)ices$', 'gi'), '$1ix'],
[new RegExp('(quiz)zes$', 'gi'), '$1'],
[new RegExp('s$', 'gi'), '']
]
}
};
// helper function used by singularize and pluralize
function applyRules(_string, _ruleSet, _skip) {
if(_skip.indexOf(_string.toLowerCase()) === -1) {
var i = 0, rule;
while(rule = _ruleSet[i++]) {
if(_string.match(rule[0])) {
return _string.replace(rule[0], rule[1]);
}
}
}
return _string;
}
return {
/**
* @memberof inflectorProvider#
*
* @description
*
* Registers a new locale, see the default english locale implementation for information about the required structure.
*
* @param {string} _locale Locale name
* @param {object} _def Locale definition
*/
registerLocale: function(_locale, _def) {
localeMap[_locale] = _def;
},
/**
* @memberof inflectorProvider#
*
* @description
*
* Sets the default locale, defaults to 'en'
*
* @param {string} _locale Locale name
*/
setLocale: function(_locale) {
activeLocale = _locale;
},
/**
* @class inflector
*
* @description
*
* The inflector service provides a set of string transformation methods.
*/
$get: ['$log', function($log) {
function loadRulesFor(_locale) {
_locale = _locale || activeLocale;
var rules = localeMap[_locale];
if(!rules) $log.warn('Invalid inflector locale ' + _locale);
return rules;
}
return {
/**
* @memberof inflector#
*
* @description
*
* Transform a string to camelcase, removing every space, dash and underscore
*
* @param {string} _string String to transform
* @param {boolean} _constant If set to false, first letter is not uppercased, defaults to false.
* @return {string} The transformed string
*/
camelize: function(_string, _constant) {
if (typeof _string !== 'string') return _string;
return _string.replace(/(?:^[-_\s]*|[-_\s]+)([A-Z\d])/gi, function (match, _first, _index) {
return (!_constant && _index === 0) ? _first : _first.toUpperCase();
});
},
/**
* @memberof inflector#
*
* @description
*
* Transforms a camelcase string to a snakecase string
*
* @param {string} _string String to transform
* @param {string} _sep Separator, defaults to '-'
* @return {string} The transformed string
*/
parameterize: function(_string, _sep) {
if (typeof _string !== 'string') return _string;
return _string.replace(/(?:[A-Z]+|[0-9]+)/g, function (_match, _index) {
return _index === 0 ? _match : (_sep || '-') + _match;
}).toLowerCase();
},
/**
* @memberof inflector#
*
* @description
*
* Transforms a string to snakecase, replaces every space, dash and undercore by the provided separator.
*
* @param {string} _string String to transform
* @param {string} _sep Separator, defaults to '-'
* @return {string} The transformed string
*/
dasherize: function(_string, _sep) {
return _string.replace(/[-_\s]+/g, _sep || '-');
},
/**
* @memberof inflector#
*
* @description
*
* Transforms a string to its singular form.
*
* @param {string} _string String to transform
* @param {string} _locale) Locale to use, defaults to the default locale
* @return {string} The transformed string
*/
singularize: function(_string, _locale) {
var rules = loadRulesFor(_locale);
return rules ? applyRules(_string, rules.singular, rules.uncountable) : _string;
},
/**
* @memberof inflector#
*
* @description
*
* Transforms a string to its plural form.
*
* @param {string} _string String to transform
* @param {string} _locale) Locale to use, defaults to the default locale
* @return {string} The transformed string
*/
pluralize: function(_string, _locale) {
var rules = loadRulesFor(_locale);
return rules ? applyRules(_string, rules.plural, rules.uncountable) : _string;
}
};
}]
};
}]);
})(angular);
// Preload some angular stuff
var RMModule = angular.module('restmod', ['ng', 'platanus.inflector']);
/**
* @class restmodProvider
*
* @description
*
* The restmodProvider exposes restmod configuration methods
*/
RMModule.provider('restmod', [function() {
var BASE_CHAIN = ['RMBuilderExt', 'RMBuilderRelations', 'RMBuilderComputed'];
function wrapInInvoke(_mixin) {
return function(_injector) {
_injector.invoke(_mixin, this, { $builder: this });
};
}
return {
/**
* @memberof restmodProvider#
*
* @description
*
* Adds base mixins for every generated model.
*
* **ATTENTION** Model names should NOT be added to this chain.
*
* All mixins added to the chain are prepended to every generated model.
*
* Usage:
*
* ```javascript
* $provider.rebase('ChangeModel', 'LazyRelations', 'ThrottledModel')
* ```
*/
rebase: function(/* _mix_names */) {
var mixin, i, l = arguments.length;
for(i = 0; i < l; i++) {
mixin = arguments[i];
if(angular.isArray(mixin) || angular.isFunction(mixin)) {
mixin = wrapInInvoke(mixin);
}
BASE_CHAIN.push(mixin);
}
return this;
},
/**
* @class restmod
*
* @description
*
* The restmod service provides factory methods for the different restmod consumables.
*/
$get: ['RMModelFactory', '$log', function(buildModel, $log) {
var arraySlice = Array.prototype.slice;
var restmod = {
/**
* @memberOf restmod#
*
* @description
*
* The model factory is used to generate new restmod model types. It's recommended to put models inside factories,
* this is usefull later when defining relations and inheritance, since the angular $injector is used by
* these features. It's also the angular way of doing things.
*
* A simple model can be built like this:
*
* ```javascript
* angular.module('bike-app').factory('Bike', function(restmod) {
* return restmod.model('/bikes');
* });
*```
*
* The `_url` parameter is the resource url the generated model will be bound to, if `null` is given then
* the model is *nested* and can only be used in another model context.
*
* The model also accepts one or more definition providers as one or more arguments after the _url parameter,
* posible definition providers are:
*
* * A definition object (more on this at the {@link BuilderApi}):
*
* ```javascript
* restmod.model('/bikes', {
* viewed: { init: false },
* parts: { hasMany: 'Part' },
* '~afterCreate': function() {
* alert('Bike created!!');
* }
* });
*```
*
* * A definition function (more on this at the {@link BuilderApi}):
*
* ```javascript
* restmod.model('/bikes', function() {
* this.attrDefault('viewed', false);
* this.attrMask('id', 'CU');
* });
*```
*
* * A mixin (generated using the mixin method) or model factory name:
*
* ```javascript
* restmod.model('/bikes', 'BaseModel', 'PagedModel');
*```
*
* * A mixin (generated using the mixin method) or model object:
*
* ```javascript
* restmod.model('/bikes', BaseModel, PagedModel);
* ```
*
* @param {string} _url Resource url.
* @param {mixed} _mix One or more mixins, description objects or description blocks.
* @return {StaticApi} The new model.
*/
model: function(_baseUrl/* , _mix */) {
var model = buildModel(_baseUrl, BASE_CHAIN);
if(arguments.length > 1) {
model.mix(arraySlice.call(arguments, 1));
$log.warn('Passing mixins and difinitions in the model method will be deprecated in restmod 1.2, use restmod.model().mix() instead.');
}
return model;
},
/**
* @memberOf restmod#
*
* @description
*
* The mixin factory is used to pack model behaviors without the overload of generating a new
* model. The mixin can then be passed as argument to a call to {@link restmod#model#model}
* to extend the model capabilities.
*
* A mixin can also be passed to the {@link restmodProvider#rebase} method to provide
* a base behavior for all generated models.
*
* @param {mixed} _mix One or more mixins, description objects or description blocks.
* @return {object} The mixin
*/
mixin: function(/* _mix */) {
return { $isAbstract: true, $$chain: arraySlice.call(arguments, 0) };
},
/**
* @memberOf restmod#
*
* @description
*
* Shorcut method used to create singleton resources.
*
* Same as calling `restmod.model(null).$single(_url)`
*
* Check the {@link StaticApi#$single} documentation for more information.
*
* @param {string} _url Resource url,
* @param {mixed} _mix Mixin chain.
* @return {RecordApi} New resource instance.
*/
singleton: function(_url/*, _mix */) {
return restmod.model.apply(this, arguments).single(_url);
}
};
return restmod;
}]
};
}])
.factory('model', ['restmod', function(restmod) {
return restmod.model;
}])
.factory('mixin', ['restmod', function(restmod) {
return restmod.mixin;
}]);
RMModule.factory('RMCollectionApi', ['RMUtils', function(Utils) {
var extend = angular.extend;
/**
* @class CollectionApi
*
* @extends ScopeApi
* @extends CommonApi
*
* @description
*
* A restmod collection is an extended array type bound REST resource route.
*
* Every time a new restmod model is created, an associated collection type is created too.
*
* TODO: talk about fetch/refresh behaviour, lifecycles, collection scopes, adding/removing
*
* For `$fetch` on a collection:
*
* * before-fetch-many
* * before-request
* * after-request[-error]
* * after-feed (called for every record if no errors)
* * after-feed-many (only called if no errors)
* * after-fetch-many[-error]
*
* @property {boolean} $isCollection Helper flag to separate collections from the main type
* @property {object} $scope The collection scope (hierarchical scope, not angular scope)
* @property {object} $params The collection query parameters
*
*/
return {
$isCollection: true,
/**
* @memberof CollectionApi#
*
* @description Called by collection constructor on initialization.
*
* Note: Is better to add a hook on after-init than overriding this method.
*/
$initialize: function() {
// after initialization hook
this.$dispatch('after-collection-init');
},
/**
* @memberof CollectionApi#
*
* @description Feeds raw collection data into the collection.
*
* This method is for use in collections only.
*
* @param {array} _raw Data to add
* @param {string} _mask 'CRU' mask
* @return {CollectionApi} self
*/
$decode: function(_raw, _mask) {
Utils.assert(_raw && angular.isArray(_raw), 'Collection $decode expected array');
for(var i = 0, l = _raw.length; i < l; i++) {
this.$buildRaw(_raw[i], _mask).$reveal(); // build and disclose every item.
}
this.$dispatch('after-feed-many', [_raw]);
return this;
},
/**
* @memberof CollectionApi#
*
* @description Encodes array data into a its serialized version.
*
* @param {string} _mask 'CRU' mask
* @return {CollectionApi} self
*/
$encode: function(_mask) {
var raw = [];
for(var i = 0, l = this.length; i < l; i++) {
raw.push(this[i].$encode(_mask));
}
this.$dispatch('before-render-many', [raw]);
return raw;
},
/**
* @memberof CollectionApi#
*
* @description Resets the collection's contents
*
* @return {CollectionApi} self
*/
$clear: function() {
return this.$always(function() {
this.length = 0; // reset the collection contents
});
},
/**
* @memberof CollectionApi#
*
* @description Begin a server request to populate collection. This method does not
* clear the collection contents by default, use `$refresh` to reset and fetch.
*
* This method is for use in collections only.
*
* @param {object|function} _params Additional request parameters, not stored in collection,
* if a function is given, then it will be called with the request object to allow requet customization.
* @return {CollectionApi} self
*/
$fetch: function(_params) {
return this.$action(function() {
var request = { method: 'GET', url: this.$url('fetchMany'), params: this.$params };
if(_params) {
request.params = request.params ? extend(request.params, _params) : _params;
}
// TODO: check that collection is bound.
this
.$dispatch('before-fetch-many', [request])
.$send(request, function(_response) {
this
.$unwrap(_response.data)
.$dispatch('after-fetch-many', [_response]);
}, function(_response) {
this.$dispatch('after-fetch-many-error', [_response]);
});
});
},
/**
* @memberof CollectionApi#
*
* @description Adds an item to the back of the collection. This method does not attempt to send changes
* to the server. To create a new item and add it use $create or $build.
*
* Triggers after-add callbacks.
*
* @param {RecordApi} _obj Item to be added
* @return {CollectionApi} self
*/
$add: function(_obj, _idx) {
Utils.assert(_obj.$type && _obj.$type === this.$type, 'Collection $add expects record of the same $type');
return this.$action(function() {
if(_obj.$position === undefined) {
if(_idx !== undefined) {
this.splice(_idx, 0, _obj);
} else {
this.push(_obj);
}
_obj.$position = true; // use true for now, keeping position updated can be expensive
this.$dispatch('after-add', [_obj]);
}
});
},
/**
* @memberof CollectionApi#
*
* @description Removes an item from the collection.
*
* This method does not send a DELETE request to the server, it just removes the
* item locally. To remove an item AND send a DELETE use the item's $destroy method.
*
* Triggers after-remove callbacks.
*
* @param {RecordApi} _obj Item to be removed
* @return {CollectionApi} self
*/
$remove: function(_obj) {
return this.$action(function() {
var idx = this.$indexOf(_obj);
if(idx !== -1) {
this.splice(idx, 1);
_obj.$position = undefined;
this.$dispatch('after-remove', [_obj]);
}
});
},
/**
* @memberof CollectionApi#
*
* @description Finds the location of an object in the array.
*
* If a function is provided then the index of the first item for which the function returns true is returned.
*
* @param {RecordApi|function} _obj Object to find
* @return {number} Object index or -1 if not found
*/
$indexOf: function(_obj) {
var accept = typeof _obj === 'function' ? _obj : false;
for(var i = 0, l = this.length; i < l; i++) {
if(accept ? accept(this[i]) : this[i] === _obj) return i;
}
return -1;
}
};
}]);
RMModule.factory('RMCommonApi', ['$http', 'RMFastQ', '$log', function($http, $q, $log) {
var EMPTY_ARRAY = [];
function wrapPromise(_ctx, _fun) {
var dsp = _ctx.$dispatcher();
return function(_last) {
// save and reset promise
var oldPromise = _ctx.$promise;
_ctx.$promise = undefined;
try {
_ctx.$last = _last;
var result = dsp ? _ctx.$decorate(dsp, _fun, [_ctx]) : _fun.call(_ctx, _ctx);
return result === undefined ? _ctx.$promise : result;
} finally {
_ctx.$promise = oldPromise; // restore old promise
}
};
}
/**
* @class CommonApi
*
* @description
*
* Provides a common framework for restmod resources.
*
* This API is included in {@link RecordApi} and {@link CollectionApi}.
* making its methods available in every structure generated by restmod.
*
* TODO: Describe hook mechanism, promise mechanism and send lifecycle.
*
* @property {promise} $promise The last operation promise (undefined if no promise has been created yet)
* @property {array} $pending Pending requests associated to this resource (undefined if no request has been initiated)
* @property {object} $$cb Scope call backs (undefined if no callbacks have been defined, private api)
* @property {function} $$dsp The current event dispatcher (private api)
*/
var CommonApi = {
/**
* @memberof CommonApi#
*
* @description Gets this resource url.
*
* @param {string} _for Intended usage for the url (optional)
* @return {string} The resource url.
*/
$url: function(_for) {
if(_for) {
_for = '$' + _for + 'UrlFor';
if(this.$scope[_for]) return this.$scope[_for](this);
} else if(this.$scope.$cannonicalUrlFor) {
return this.$scope.$cannonicalUrlFor(this);
}
return this.$scope.$urlFor(this);
},
// Hooks API
/**
* @memberof CommonApi#
*
* @description Executes a given hook callbacks using the current dispatcher context.
*
* This method can be used to provide custom object lifecycle hooks.
*
* Usage:
*
* ```javascript
* var mixin = restmod.mixin({
* triggerDummy: function(_param) {
* this.$dispatch('dummy-hook', _param);
* }
* });
*
* // Then hook can be used at model definition to provide type-level customization:
* var Bike $resmod.model('/api/bikes', mixin, {
* '~dummy-hook': function() {
* alert('This is called for every bike');
* }
* };
*
* // or at instance level:
* var myBike = Bike.$build();
* myBike.$on('dummy-hook', function() {
* alert('This is called for myBike only');
* });
*
* // or event at decorated context level
* myBike.$decorate({
* 'dummy-hook': function() {
* alert('This is called for myBike only inside the decorated context');
* }
* }, fuction() {
* // decorated context
* });
* ```
*
* @param {string} _hook Hook name
* @param {array} _args Hook arguments
* @param {object} _ctx Hook execution context override
*
* @return {CommonApi} self
*/
$dispatch: function(_hook, _args, _ctx) {
var cbs, i, cb, dsp = this.$$dsp;
if(!_ctx) _ctx = this;
// context callbacks
if(dsp) {
this.$$dsp = undefined; // disable dsp for hooks
dsp(_hook, _args, _ctx);
}
// instance callbacks
if(this.$$cb && (cbs = this.$$cb[_hook])) {
for(i = 0; !!(cb = cbs[i]); i++) {
cb.apply(_ctx, _args || EMPTY_ARRAY);
}
}
// bubble up the object scope, bubble to type only if there isnt a viable parent scope.
if(this.$scope && this.$scope.$dispatch) {
this.$scope.$dispatch(_hook, _args, _ctx);
} else if(this.$type) {
this.$type.$dispatch(_hook, _args, _ctx);
}
this.$$dsp = dsp; // reenable dsp.
return this;
},
/**
* @memberof CommonApi#
*
* @description Registers an instance hook.
*
* An instance hook is called only for events generated by the calling object.
*
* ```javascript
* var bike = Model.$build(), bike2 = Model.$build();
* bike.$on('before-save', function() { alert('saved!'); });
*
* bike.$save(); // 'saved!' alert is shown after bike is saved
* bike2.$save(); // no alert is shown after bike2 is saved
* ```
*
* @param {string} _hook Hook name
* @param {function} _fun Callback
* @return {CommonApi} self
*/
$on: function(_hook, _fun) {
var hooks = (this.$$cb || (this.$$cb = {}))[_hook] || (this.$$cb[_hook] = []);
hooks.push(_fun);
return this;
},
/**
* @memberof CommonApi#
*
* @description Registers hooks to be used only inside the given function (decorated context).
*
* ```javascript
* // special fetch method that sends a special token header.
* restmod.mixin({
* $fetchWithToken: function(_token) {
* return this.$decorate({
* 'before-fetch': function(_req) {
* _req.headers = _req.headers || {};
* _req.headers['Token'] = _token;
* }
* ), function() {
* return this.$fetch();
* })
* }
* });
* ```
*
* @param {object|function} _hooks Hook mapping object or hook execution method.
* @param {function} _fun Function to be executed in with decorated context, this function is executed in the callee object context.
* @return {CommonApi} self
*/
$decorate: function(_hooks, _fun, _args) {
var oldDispatcher = this.$$dsp;
// set new dispatcher
this.$$dsp = (typeof _hooks === 'function' || !_hooks) ? _hooks : function(_hook, _args, _ctx) {
if(oldDispatcher) oldDispatcher.apply(null, arguments);
var extraCb = _hooks[_hook];
if(extraCb) extraCb.apply(_ctx, _args || EMPTY_ARRAY);
};
try {
return _fun.apply(this, _args);
} finally {
// reset dispatcher with old value
this.$$dsp = oldDispatcher;
}
},
/**
* @memberof CommonApi#
*
* @description Retrieves the current object's event dispatcher function.
*
* This method can be used in conjuction with `$decorate` to provide a consistent hook context
* during async operations. This is important when building extensions that want to support the
* contextual hook system in asynchronic operations.
*
* For more information aboout contextual hooks, see the {@link CommonApi#decorate} documentation.
*
* Usage:
*
* ```javascript
* restmod.mixin({
* $saveAndTrack: function() {
* var dsp = this.$dispatcher(), // capture the current dispatcher function.
* self = this;
* this.$save().$then(function() {
* this.$send({ path: '/traces', data: 'ble' }, function() {
* this.$decorate(dsp, function() {
* // the event is dispatched using the dispatcher function available when $saveAndTrack was called.
* this.$dispatch('trace-stored');
* });
* });
* });
* }
* })
* ```
*
* @return {function} Dispatcher evaluator
*/
$dispatcher: function() {
return this.$$dsp;
},
// Promise API
/**
* @memberof CommonApi#
*
* @description Returns this object last promise.
*
* If promise does not exist, then a new one is generated that resolves to the object itsef. The
* new promise is not set as the current object promise, for that use `$then`.
*
* Usage:
*
* ```javascript
* col.$fetch().$asPromise();
* ```
*
* @return {promise} $q promise
*/
$asPromise: function() {
var _this = this;
return this.$promise ? this.$promise.then(
function() { return _this; },
function() { return $q.reject(_this); }
) : $q.when(this);
},
/**
* @memberof CommonApi#
*
* @description Promise chaining method, keeps the model instance as the chain context.
*
* Calls `$q.then` on the model's last promise.
*
* Usage:
*
* ```javascript
* col.$fetch().$then(function() { });
* ```
*
* @param {function} _success success callback
* @param {function} _error error callback
* @return {CommonApi} self
*/
$then: function(_success, _error) {
if(!this.$promise) {
this.$promise = $q.when(wrapPromise(this, _success)(this));
} else {
this.$promise = this.$promise.then(
_success ? wrapPromise(this, _success) : _success,
_error ? wrapPromise(this, _error) : _error
);
}
return this;
},
/**
* @memberof CommonApi#
*
* @description Promise chaining method, similar to then but executes same callback in success or error.
*
* Usage:
*
* ```javascript
* col.$fetch().$always(function() { });
* ```
*
* @param {function} _fun success/error callback
* @return {CommonApi} self
*/
$always: function(_fun) {
return this.$then(_fun, _fun);
},
/**
* @memberof CommonApi#
*
* @description Promise chaining, keeps the model instance as the chain context.
*
* Calls ´$q.finally´ on the collection's last promise, updates last promise with finally result.
*
* Usage:
*
* ```javascript
* col.$fetch().$finally(function() { });
* ```
*
* @param {function} _cb callback
* @return {CommonApi} self
*/
$finally: function(_cb) {
this.$promise = this.$promise['finally'](wrapPromise(this, _cb));
return this;
},
// Communication API
/**
* @memberof CommonApi#
*
* @description Low level communication method, wraps the $http api.
*
* * You can access last request promise using the `$asPromise` method.
* * Pending requests will be available at the $pending property (array).
* * Current request execution status can be queried using the $status property (current request, not last).
* * The $status property refers to the current request inside $send `_success` and `_error` callbacks.
*
* @param {object} _options $http options
* @param {function} _success sucess callback (sync)
* @param {function} _error error callback (sync)
* @return {CommonApi} self
*/
$send: function(_options, _success, _error) {
// make sure a style base was selected for the model
if(!this.$type.getProperty('style')) {
$log.warn('No API style base was selected, see the Api Integration FAQ for more information on this warning');
}
var action = this.$$action;
return this.$always(function() {
this.$response = null;
this.$status = 'pending';
this.$dispatch('before-request', [_options]);
return $http(_options).then(wrapPromise(this, function() {
if(action && action.canceled) {
// if request was canceled during request, ignore post request actions.
this.$status = 'canceled';
} else {
this.$status = 'ok';
this.$response = this.$last;
this.$dispatch('after-request', [this.$last]);
if(_success) _success.call(this, this.$last);
}
}), wrapPromise(this, function() {
if(action && action.canceled) {
// if request was canceled during request, ignore error handling
this.$status = 'canceled';
} else {
this.$status = 'error';
this.$response = this.$last;
// IDEA: Consider flushing pending request in case of an error. Also continue ignoring requests
// until the error flag is reset by user.
this.$dispatch('after-request-error', [this.$last]);
if(_error) _error.call(this, this.$last);
return $q.reject(this); // TODO: this will step over any promise generated in _error!!
}
}));
});
},
// Actions API
/**
* @memberof CommonApi#
*
* @description Registers a new action to be executed in the promise queue.
*
* Registered pending actions can be canceled using `$cancel`
*
* `$cancel` will also cancel any ongoing call to `$send` (will not abort it yet though...)
*
* @return {CommonApi} self
*/
$action: function(_fun) {
var status = {
canceled: false
}, pending = this.$pending || (this.$pending = []);
pending.push(status);
return this.$always(function() {
var oldAction = this.$$action;
try {
if(!status.canceled) {
this.$$action = status;
return _fun.call(this);
} else {
return $q.reject(this);
}
} finally {
// restore object state and pending actions
this.$$action = oldAction;
}
}).$finally(function() {
// after action and related async code finishes, remove status from pending list
pending.splice(pending.indexOf(status), 1);
});
},
/**
* @memberof CommonApi#
*
* @description Cancels all pending actions registered with $action.
*
* @return {CommonApi} self
*/
$cancel: function() {
// cancel every pending request.
if(this.$pending) {
angular.forEach(this.$pending, function(_status) {
_status.canceled = true;
});
}
return this;
},
/**
* @memberof CommonApi#
*
* @description Returns true if object has queued actions
*
* @return {Boolean} Object request pending status.
*/
$hasPendingActions: function() {
var pendingCount = 0;
if(this.$pending) {
angular.forEach(this.$pending, function(_status) {
if(!_status.canceled) pendingCount++;
});
}
return pendingCount > 0;
}
};
return CommonApi;
}]);
RMModule.factory('RMExtendedApi', ['$q', 'RMPackerCache', function($q, packerCache) {
/**
* @class ExtendedApi
*
* @description
*
* Provides a common framework **on top** of the {@link RecordApi} and {@link CollectionApi}.
*
* @property {boolean} $resolved The collection resolve status, is undefined on intialization
*/
return {
// override decode to detect resolution of resource
$decode: function(_raw, _mask) {
if(this.$resolved === false && this.$clear) this.$clear(); // clear if not resolved.
this.$super(_raw, _mask);
this.$resolved = true;
return this;
},
/// Misc common methods
/**
* @memberof ExtendedApi#
*
* @description
*
* Unpacks and decode raw data from a server generated structure.
*
* ATTENTION: do not override this method to change the object wrapping strategy,
* instead, override the static {@link Model.$unpack} method.
*
* @param {mixed} _raw Raw server data
* @param {string} _mask 'CRU' mask
* @return {ExtendedApi} this
*/
$unwrap: function(_raw, _mask) {
try {
packerCache.prepare();
_raw = this.$type.unpack(this, _raw);
return this.$decode(_raw, _mask);
} finally {
packerCache.clear();
}
},
/**
* @memberof ExtendedApi#
*
* @description
*
* Encode and packs object into a server compatible structure that can be used for PUT/POST operations.
*
* ATTENTION: do not override this method to change the object wrapping strategy,
* instead, override the static {@link Model.$pack} method.
*
* @param {string} _mask 'CRU' mask
* @return {string} raw data
*/
$wrap: function(_mask) {
var raw = this.$encode(_mask);
raw = this.$type.pack(this, raw);
return raw;
},
/**
* @memberof ExtendedApi#
*
* @description Resets the resource's $resolved status.
*
* After being reset, calls to `$resolve` will execute a new $fetch.
*
* Also, if reset, resource will be cleared on new data.
*
* @return {ExtendedApi} self
*/
$reset: function() {
// cancel outside promise chain
// TODO: find a way of only ignoring requests that will lead to resolution, maybe using action metadata
return this.$cancel().$action(function() {
this.$resolved = false;
});
},
/**
* @memberof ExtendedApi#
*
* @description Resolves the resource's contents.
*
* If already resolved then this method will return a resolved promise, if not then
* it will initiate a `$fetch` operation and return the operation promise.
*
* This method will trigger a `before-resolve` event before checking the resolve status.
*
* @param {object} _params `$fetch` params
* @return {promise} Promise that resolves to the resource.
*/
$resolve: function(_params) {
return this.$action(function() { // chain resolution in request promise chain
this.$dispatch('before-resolve', []);
if(!this.$resolved) this.$fetch(_params);
});
},
/**
* @memberof ExtendedApi#
*
* @description Resets and fetches the resource contents.
*
* @param {object} _params `$fetch` params
* @return {ExtendedApi} self
*/
$refresh: function(_params) {
return this.$reset().$fetch(_params);
}
};
}]);
RMModule.factory('RMListApi', [function() {
/**
* @class ListApi
*
* @description Common methods for Lists and Collections.
*/
return {
/**
* @memberof ListApi#
*
* @description Generates a new list from this one.
*
* If called without arguments, the list is popupated with the same contents as this list.
*
* If there is a pending async operation on the host collection/list, then this method will
* return an empty list and fill it when the async operation finishes. If you don't need the async behavior
* then use `$type.list` directly to generate a new list.
*
* @param {function} _filter A filter function that should return the list contents as an array.
* @return {ListApi} list
*/
$asList: function(_filter) {
var list = this.$type.list(),
promise = this.$asPromise();
// set the list initial promise to the resolution of the parent promise.
list.$promise = promise.then(function(_this) {
list.push.apply(list, _filter ? _filter(_this) : _this);
});
return list;
}
};
}]);
RMModule.factory('RMRecordApi', ['RMUtils', function(Utils) {
/**
* @class RelationScope
*
* @description
*
* Special scope a record provides to resources related via hasMany or hasOne relation.
*/
var RelationScope = function(_scope, _target, _partial) {
this.$scope = _scope;
this.$target = _target;
this.$partial = Utils.cleanUrl(_partial);
};
RelationScope.prototype = {
$nestedUrl: function() {
return Utils.joinUrl(this.$scope.$url(), this.$partial);
},
// url is nested for collections and nested records
$urlFor: function(_resource) {
if(_resource.$isCollection || this.$target.isNested()) {
return this.$nestedUrl();
} else {
return this.$target.$urlFor(_resource);
}
},
// a record's fetch url is always nested
$fetchUrlFor: function(/* _resource */) {
return this.$nestedUrl();
},
// create is not posible in nested members
$createUrlFor: function() {
return null;
}
};
/**
* @class RecordApi
* @extends CommonApi
*
* @property {object} $scope The record's scope (see {@link ScopeApi})
* @property {mixed} $pk The record's primary key
*
* @description
*
* Provides record synchronization and manipulation methods. This is the base API for every restmod record.
*
* TODO: Talk about the object lifecycle.
*
* ### Object lifecycle hooks
*
* For `$fetch`:
*
* * before-fetch
* * before-request
* * after-request[-error]
* * after-feed (only called if no errors)
* * after-fetch[-error]
*
* For `$save` when creating:
*
* * before-render
* * before-save
* * before-create
* * before-request
* * after-request[-error]
* * after-feed (only called if no errors)
* * after-create[-error]
* * after-save[-error]
*
* For `$save` when updating:
*
* * before-render
* * before-save
* * before-update
* * before-request
* * after-request[-error]
* * after-feed (only called if no errors)
* * after-update[-error]
* * after-save[-error]
*
* For `$destroy`:
*
* * before-destroy
* * before-request
* * after-request[-error]
* * after-destroy[-error]
*
* @property {mixed} $pk The record primary key
* @property {object} $scope The collection scope (hierarchical scope, not angular scope)
*/
return {
/**
* @memberof RecordApi#
*
* @description Called by record constructor on initialization.
*
* Note: Is better to add a hook to after-init than overriding this method.
*/
$initialize: function() {
// apply defaults
this.$super();
// after initialization hook
// TODO: put this on $new so it can use stacked DSP?
this.$dispatch('after-init');
},
/**
* @memberof RecordApi#
*
* @description Called the resource's scope $urlFor method to build the url for the record using the proper scope.
*
* By default the resource partial url is just its `$pk` property. This can be overriden to provide other routing approaches.
*
* @return {string} The resource partial url
*/
$buildUrl: function(_scope) {
return (this.$pk === undefined || this.$pk === null) ? null : Utils.joinUrl(_scope.$url(), this.$pk + '');
},
/**
* @memberof RecordApi#
*
* @description Default item child scope factory.
*
* By default, no create url is provided and the update/destroy url providers
* attempt to first use the unscoped resource url.
*
* // TODO: create special api to hold scope (so it is not necessary to recreate the whole object every time.)
*
* @param {mixed} _for Scope target type, accepts any model class.
* @param {string} _partial Partial route.
* @return {RelationScope} New scope.
*/
$buildScope: function(_for, _partial) {
if(_for.$buildOwnScope) {
// TODO
} else {
return new RelationScope(this, _for, _partial);
}
},
/**
* @memberof RecordApi#
*
* @description Iterates over the object non-private properties
*
* @param {function} _fun Function to call for each
* @return {RecordApi} self
*/
$each: function(_fun, _ctx) {
for(var key in this) {
if(this.hasOwnProperty(key) && key[0] !== '$') {
_fun.call(_ctx || this[key], this[key], key);
}
}
return this;
},
/**
* @memberof RecordApi#
*
* @description Feed raw data to this instance.
*
* @param {object} _raw Raw data to be fed
* @param {string} _mask 'CRU' mask
* @return {RecordApi} this
*/
$decode: function(_raw, _mask) {
// IDEA: let user override serializer
this.$type.decode(this, _raw, _mask || Utils.READ_MASK);
if(this.$pk === undefined || this.$pk === null) this.$pk = this.$type.inferKey(_raw); // TODO: warn if key changes
this.$dispatch('after-feed', [_raw]);
return this;
},
/**
* @memberof RecordApi#
*
* @description Generate data to be sent to the server when creating/updating the resource.
*
* @param {string} _mask 'CRU' mask
* @return {string} raw data
*/
$encode: function(_mask) {
var raw = this.$type.encode(this, _mask || Utils.CREATE_MASK);
this.$dispatch('before-render', [raw]);
return raw;
},
/**
* @memberof RecordApi#
*
* @description Begin a server request for updated resource data.
*
* The request's promise can be accessed using the `$asPromise` method.
*
* @param {object} _params Optional list of params to be passed to object request.
* @return {RecordApi} this
*/
$fetch: function(_params) {
return this.$action(function() {
var url = this.$url('fetch');
Utils.assert(!!url, 'Cant $fetch if resource is not bound');
var request = { method: 'GET', url: url, params: _params };
this.$dispatch('before-fetch', [request]);
this.$send(request, function(_response) {
this.$unwrap(_response.data);
this.$dispatch('after-fetch', [_response]);
}, function(_response) {
this.$dispatch('after-fetch-error', [_response]);
});
});
},
/**
* @memberof RecordApi#
*
* @description Copyies another object's non-private properties.
*
* This method runs inside the promise chain, so calling
*
* ```javascript
* Bike.$find(1).$extend({ size: "L" }).$save();
* ```
* Will first fetch the bike data and after it is loaded the new size will be applied and then the
* updated model saved.
*
* @param {object} _other Object to merge.
* @return {RecordApi} self
*/
$extend: function(_other) {
return this.$action(function() {
for(var tmp in _other) {
if (_other.hasOwnProperty(tmp) && tmp[0] !== '$') {
this[tmp] = _other[tmp];
}
}
});
},
/**
* @memberof RecordApi#
*
* @description Shortcut method used to extend and save a model.
*
* This method will not force a PUT, if object is new `$update` will attempt to POST.
*
* @param {object} _other Data to change
* @return {RecordApi} self
*/
$update: function(_other) {
return this.$extend(_other).$save();
},
/**
* @memberof RecordApi#
*
* @description Begin a server request to create/update/patch resource.
*
* A patch is only executed if model is identified and a patch property list is given. It is posible to
* change the method used for PATCH operations by setting the `patchMethod` configuration.
*
* If resource is new and it belongs to a collection and it hasnt been revealed, then it will be revealed.
*
* The request's promise can be accessed using the `$asPromise` method.
*
* @param {array} _patch Optional list of properties to send in update operation.
* @return {RecordApi} this
*/
$save: function(_patch) {
return this.$action(function() {
var url = this.$url('update'), request;
if(url) {
// If bound, update
if(_patch) {
request = {
method: this.$type.getProperty('patchMethod', 'PATCH'), // allow user to override patch method
url: url,
// Use special mask for patches, mask everything that is not in the patch list.
data: this.$wrap(function(_name) {
for(var i = 0, l = _patch.length; i < l; i++) {
if(_name === _patch[i] ||
_name.indexOf(_patch[i] + '.') === 0 ||
_patch[i].indexOf(_name + '.') === 0
) { return false; }
}
return true;
})
};
} else {
request = { method: 'PUT', url: url, data: this.$wrap(Utils.UPDATE_MASK) };
}
this
.$dispatch('before-update', [request, !!_patch])
.$dispatch('before-save', [request])
.$send(request, function(_response) {
this
.$unwrap(_response.data)
.$dispatch('after-update', [_response, !!_patch])
.$dispatch('after-save', [_response]);
}, function(_response) {
this
.$dispatch('after-update-error', [_response, !!_patch])
.$dispatch('after-save-error', [_response]);
});
} else {
// If not bound create.
url = this.$url('create') || this.$scope.$url();
Utils.assert(!!url, 'Cant $create if parent scope is not bound');
request = { method: 'POST', url: url, data: this.$wrap(Utils.CREATE_MASK) };
this
.$dispatch('before-save', [request])
.$dispatch('before-create', [request])
.$send(request, function(_response) {
this.$unwrap(_response.data);
// reveal item (if not yet positioned)
if(this.$scope.$isCollection && this.$position === undefined && !this.$preventReveal) {
this.$scope.$add(this, this.$revealAt);
}
this
.$dispatch('after-create', [_response])
.$dispatch('after-save', [_response]);
}, function(_response) {
this
.$dispatch('after-create-error', [_response])
.$dispatch('after-save-error', [_response]);
});
}
});
},
/**
* @memberof RecordApi#
*
* @description Begin a server request to destroy the resource.
*
* The request's promise can be accessed using the `$asPromise` method.
*
* @return {RecordApi} this
*/
$destroy: function() {
return this.$action(function() {
var url = this.$url('destroy');
if(url)
{
var request = { method: 'DELETE', url: url };
this
.$dispatch('before-destroy', [request])
.$send(request, function(_response) {
// remove from scope
if(this.$scope.$remove) {
this.$scope.$remove(this);
}
this.$dispatch('after-destroy', [_response]);
}, function(_response) {
this.$dispatch('after-destroy-error', [_response]);
});
}
else
{
// If not yet bound, just remove from parent
if(this.$scope.$remove) this.$scope.$remove(this);
}
});
},
// Collection related methods.
/**
* @memberof RecordApi#
*
* @description Changes the location of the object in the bound collection.
*
* If object hasn't been revealed, then this method will change the index where object will be revealed at.
*
* @param {integer} _to New object position (index)
* @return {RecordApi} this
*/
$moveTo: function(_to) {
if(this.$position !== undefined) {
// TODO: move item to given index.
// TODO: callback
} else {
this.$revealAt = _to;
}
return this;
},
/**
* @memberof RecordApi#
*
* @description Reveal in collection
*
* If instance is bound to a collection and it hasnt been revealed (because it's new and hasn't been saved),
* then calling this method without parameters will force the object to be added to the collection.
*
* If this method is called with **_show** set to `false`, then the object wont be revealed by a save operation.
*
* @param {boolean} _show Whether to reveal inmediatelly or prevent automatic reveal.
* @return {RecordApi} this
*/
$reveal: function(_show) {
if(_show === undefined || _show) {
this.$scope.$add(this, this.$revealAt);
} else {
this.$preventReveal = true;
}
return this;
}
};
}]);
RMModule.factory('RMScopeApi', ['RMUtils', function(Utils) {
/**
* @class ScopeApi
*
* @description Common behaviour for record scopes.
*
* Record scopes are starting points for record operations (like base type or a collection)
*
* TODO: Talk about record building here
*/
return {
/**
* @memberof ScopeApi#
*
* @description provides urls for scope's resources.
*
* @param {mixed} _resource The target resource.
* @return {string|null} The url or nill if resource does not meet the url requirements.
*/
$urlFor: function(_resource) {
// force item unscoping if model is not nested (maybe make this optional)
var scope = this.$type.isNested() ? this : this.$type;
return typeof _resource.$buildUrl === 'function' ? _resource.$buildUrl(scope) : scope.$url();
},
/**
* @memberof ScopeApi#
*
* @description Builds a new instance of this model, bound to this instance scope, sets its primary key.
*
* @param {mixed} _pk object private key
* @param {object} _scope scope override (optional)
* @return {RecordApi} New model instance
*/
$new: function(_pk, _scope) {
return this.$super(_pk, _scope);
},
/**
* @memberof ScopeApi#
*
* @description Builds a new instance of this model, does not assign a pk to the created object.
*
* ATTENTION: item will not show in collection until `$save` is called. To reveal item before than call `$reveal`.
*
* @param {object} _init Initial values
* @return {RecordApi} single record
*/
$build: function(_init) {
return this.$new().$extend(_init);
},
/**
* @memberof ScopeApi#
*
* @description Builds a new instance of this model using undecoded data.
*
* ATTENTION: does not automatically reveal item in collection, chain a call to $reveal to do so.
*
* @param {object} _raw Undecoded data
* @return {RecordApi} single record
*/
$buildRaw: function(_raw, _mask) {
var obj = this.$new(this.$type.inferKey(_raw));
obj.$decode(_raw, _mask);
return obj;
},
/**
* @memberof ScopeApi#
*
* @description Attempts to resolve a resource using provided private key.
*
* @param {mixed} _pk Private key
* @param {object} _params Additional query parameters
* @return {RecordApi} single record
*/
$find: function(_pk, _params) {
return this.$new(_pk).$resolve(_params);
},
/**
* @memberof ScopeApi#
*
* @description Builds and saves a new instance of this model
*
* @param {object} _attr Data to be saved
* @return {RecordApi} single record
*/
$create: function(_attr) {
return this.$build(_attr).$save();
},
/**
* @memberof ScopeApi#
*
* @description Builds a new collection bound to this scope.
*
* If scope is another collection then it will inherit its parameters
*
* Collections are bound to an api resource.
*
* @param {object} _params Additional query string parameters
* @param {object} _scope Scope override (optional)
* @return {CollectionApi} Model Collection
*/
$collection: function(_params, _scope) {
return this.$super(_params, _scope);
},
/**
* @memberof ScopeApi#
*
* @description Generates a new collection bound to this context and url and calls $fetch on it.
*
* @param {object} _params Collection parameters
* @return {CollectionApi} record collection
*/
$search: function(_params) {
return this.$collection(_params).$fetch();
}
};
}]);
RMModule.factory('RMBuilder', ['$injector', 'inflector', '$log', 'RMUtils', function($injector, inflector, $log, Utils) {
// TODO: add urlPrefix option
var forEach = angular.forEach,
isObject = angular.isObject,
isArray = angular.isArray,
isFunction = angular.isFunction,
extend = angular.extend,
VAR_RGX = /^[A-Z]+[A-Z_0-9]*$/;
/**
* @class BuilderApi
*
* @description
*
* Provides the DSL for model generation, it supports to modes of model definitions:
*
* ## Definition object
*
* This is the preferred way of describing a model behavior.
*
* A model description object looks like this:
*
* ```javascript
* restmod.model({
*
* // MODEL CONFIGURATION
*
* $config: {
* name: 'resource',
* primaryKey: '_id'
* },
*
* // ATTRIBUTE MODIFIERS AND RELATIONS
*
* propWithDefault: { init: 20 },
* propWithDecoder: { decode: 'date', chain: true },
* hasManyRelation: { hasMany: 'Other' },
* hasOneRelation: { hasOne: 'Other' },
*
* // HOOKS
*
* $hooks: {
* 'after-create': function() {
* }
* },
*
* // METHODS
*
* $extend: {
* Record: {
* instanceMethod: function() {
* }
* },
* Model: {
* scopeMethod: function() {
* }
* }
* }
* });
* ```
*
* Special model configuration variables can be set by using a `$config` block:
*
* ```javascript
* restmod.model({
*
* $config: {
* name: 'resource',
* primaryKey: '_id'
* }
*
* });
* ```
*
* With the exception of model configuration variables and properties starting with a special character (**@** or **~**),
* each property in the definition object asigns a behavior to the same named property in a model's record.
*
* To modify a property behavior assign an object with the desired modifiers to a
* definition property with the same name. Builtin modifiers are:
*
* The following built in property modifiers are provided (see each mapped-method docs for usage information):
*
* * `init` sets an attribute default value, see {@link BuilderApi#attrDefault}
* * `mask` and `ignore` sets an attribute mask, see {@link BuilderApi#attrMask}
* * `map` sets an explicit server attribute mapping, see {@link BuilderApi#attrMap}
* * `decode` sets how an attribute is decoded after being fetch, maps to {@link BuilderApi#attrDecoder}
* * `encode` sets how an attribute is encoded before being sent, maps to {@link BuilderApi#attrEncoder}
* * `volatile` sets the attribute volatility, maps to {@link BuilderApi#attrVolatile}
*
* **For relations modifiers take a look at {@link RelationBuilderApi}**
*
* **For other extended bundled methods check out the {@link ExtendedBuilderApi}**
*
* If other kind of value (different from object or function) is passed to a definition property,
* then it is considered to be a default value. (same as calling {@link BuilderApi#define} at a definition function)
*
* ```javascript
* var Model = restmod.model('/', {
* im20: 20 // same as { init: 20 }
* })
*
* // then say hello is available for use at model records
* Model.$new().im20; // 20
* ```
*
* To add/override methods from the record api, use the `$extend` block:
*
* ```javascript
* var Model = restmod.model('/', {
* $extend: {
* sayHello: function() { alert('hello!'); }
* }
* })
*
* // then say hello is available for use at model records
* Model.$new().sayHello();
* ```
*
* To add a static method or a collection method, you must specify the method scope: , prefix the definition key with **^**, to add it to the model collection prototype,
* prefix it with ***** static/collection methods to the Model, prefix the definition property name with **@**
* (same as calling {@link BuilderApi#scopeDefine} at a definition function).
*
* ```javascript
* var Model = restmod.model('/', {
* $extend: {
* 'Collection.count': function() { return this.length; }, // scope is set using a prefix
*
* Model: {
* sayHello: function() { alert('hello!'); } // scope is set using a block
* }
* })
*
* // then the following call will be valid.
* Model.sayHello();
* Model.$collection().count();
* ```
*
* More information about method scopes can be found in {@link BuilderApi#define}
*
* To add hooks to the Model lifecycle events use the `$hooks` block:
*
* ```javascript
* var Model = restmod.model('/', {
* $hooks: {
* 'after-init': function() { alert('hello!'); }
* }
* })
*
* // the after-init hook is called after every record initialization.
* Model.$new(); // alerts 'hello!';
* ```
*
* ## Definition function
*
* The definition function gives complete access to the model builder api, every model builder function described
* in this page can be called from the definition function by referencing *this*.
*
* ```javascript
* restmod.model('', function() {
* this.attrDefault('propWithDefault', 20)
* .attrAsCollection('hasManyRelation', 'ModelName')
* .on('after-create', function() {
* // do something after create.
* });
* });
* ```
*
*/
function Builder(_baseDsl) {
var mappings = {
init: ['attrDefault'],
mask: ['attrMask'],
ignore: ['attrMask'],
map: ['attrMap', 'force'],
decode: ['attrDecoder', 'param', 'chain'],
encode: ['attrEncoder', 'param', 'chain'],
'volatile': ['attrVolatile']
};
// DSL core functions.
this.dsl = extend(_baseDsl, {
/**
* @memberof BuilderApi#
*
* @description Parses a description object, calls the proper builder method depending
* on each property description type.
*
* @param {object} _description The description object
* @return {BuilderApi} self
*/
describe: function(_description) {
forEach(_description, function(_desc, _attr) {
switch(_attr.charAt(0)) {
case '@':
$log.warn('Usage of @ in description objects will be removed in 1.2, use a $extend block instead');
this.define('Scope.' + _attr.substring(1), _desc); // set static method
break;
case '~':
_attr = inflector.parameterize(_attr.substring(1));
$log.warn('Usage of ~ in description objects will be removed in 1.2, use a $hooks block instead');
this.on(_attr, _desc);
break;
default:
if(_attr === '$config') { // configuration block
for(var key in _desc) {
if(_desc.hasOwnProperty(key)) this.setProperty(key, _desc[key]);
}
} else if(_attr === '$extend') { // extension block
for(var key in _desc) {
if(_desc.hasOwnProperty(key)) this.define(key, _desc[key]);
}
} else if(_attr === '$hooks') { // hooks block
for(var key in _desc) {
if(_desc.hasOwnProperty(key)) this.on(key, _desc[key]);
}
} else if(VAR_RGX.test(_attr)) {
$log.warn('Usage of ~ in description objects will be removed in 1.2, use a $config block instead');
_attr = inflector.camelize(_attr.toLowerCase());
this.setProperty(_attr, _desc);
}
else if(isObject(_desc)) this.attribute(_attr, _desc);
else if(isFunction(_desc)) this.define(_attr, _desc);
else this.attrDefault(_attr, _desc);
}
}, this);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Extends the builder DSL
*
* Adds a function to de builder and alternatively maps the function to an
* attribute definition keyword that can be later used when calling
* `define` or `attribute`.
*
* Mapping works as following:
*
* // Given the following call
* builder.extend('testAttr', function(_attr, _test, _param1, param2) {
* // wharever..
* }, ['test', 'testP1', 'testP2']);
*
* // A call to
* builder.attribute('chapter', { test: 'hello', testP1: 'world' });
*
* // Its equivalent to
* builder.testAttr('chapter', 'hello', 'world');
*
* The method can also be passed an object with various methods to be added.
*
* @param {string|object} _name function name or object to merge
* @param {function} _fun function
* @param {array} _mapping function mapping definition
* @return {BuilderApi} self
*/
extend: function(_name, _fun, _mapping) {
if(typeof _name === 'string') {
this[_name] = Utils.override(this[name], _fun);
if(_mapping) {
mappings[_mapping[0]] = _mapping;
_mapping[0] = _name;
}
} else Utils.extendOverriden(this, _name);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets an attribute properties.
*
* This method uses the attribute modifiers mapping to call proper
* modifiers on the argument.
*
* For example, using the following description on the createdAt attribute
*
* { decode: 'date', param; 'YY-mm-dd' }
*
* Is the same as calling
*
* builder.attrDecoder('createdAt', 'date', 'YY-mm-dd')
*
* @param {string} _name Attribute name
* @param {object} _description Description object
* @return {BuilderApi} self
*/
attribute: function(_name, _description) {
var key, map, args, i;
for(key in _description) {
if(_description.hasOwnProperty(key)) {
map = mappings[key];
if(map) {
args = [_name, _description[key]];
for(i = 1; i < map.length; i++) {
args.push(_description[map[i]]);
}
args.push(_description);
this[map[0]].apply(this, args);
}
}
}
return this;
}
});
}
Builder.prototype = {
// use the builder to process a mixin chain
chain: function(_chain) {
for(var i = 0, l = _chain.length; i < l; i++) {
this.mixin(_chain[i]);
}
},
// use the builder to process a single mixin
mixin: function(_mix) {
if(_mix.$$chain) {
this.chain(_mix.$$chain);
} else if(typeof _mix === 'string') {
this.mixin($injector.get(_mix));
} else if(isArray(_mix)) {
this.chain(_mix);
} else if(isFunction(_mix)) {
_mix.call(this.dsl, $injector);
} else {
this.dsl.describe(_mix);
}
}
};
return Builder;
}]);
RMModule.factory('RMBuilderComputed', ['restmod',
function(restmod) {
/**
* @class RMBuilderComputedApi
*
* @description
*
* Builder DSL extension to build computed properties.
*
* A computed property is a "virtual" property which is created using
* other model properties. For example, a user has a firstName and lastName,
* A computed property, fullName, is generated from the two.
*
* Adds the following property modifiers:
* * `computed` function will be assigned as getter to Model, maps to {@link RMBuilderComputedApi#attrAsComputed}
*
*/
var EXT = {
/**
* @memberof RMBuilderComputedApi#
*
* @description Registers a model computed property
*
* @param {string} _attr Attribute name
* @param {function} _fn Function that returns the desired attribute value when run.
* @return {BuilderApi} self
*/
attrAsComputed: function(_attr, _fn) {
this.attrComputed(_attr, _fn);
return this;
}
};
return restmod.mixin(function() {
this.extend('attrAsComputed', EXT.attrAsComputed, ['computed']);
});
}
]);
RMModule.factory('RMBuilderExt', ['$injector', '$parse', 'inflector', '$log', 'restmod', function($injector, $parse, inflector, $log, restmod) {
var bind = angular.bind,
isFunction = angular.isFunction;
/**
* @class ExtendedBuilderApi
*
* @description
*
* Non-core builder extensions
*
* Adds the following property modifiers:
* * `serialize` sets the encoder and decoder beaviour for an attribute, maps to {@link BuilderApi#attrSerializer}
*
*/
var EXT = {
/**
* @memberof ExtendedBuilderApi#
*
* @description Sets an url prefix to be added to every url generated by the model.
*
* This applies even to objects generated by the `$single` method.
*
* This method is intended to be used in a base model mixin so everymodel that extends from it
* gets the same url prefix.
*
* Usage:
*
* ```javascript
* var BaseModel = restmod.mixin(function() {
* this.setUrlPrefix('/api');
* })
*
* var bike = restmod.model('/bikes', BaseModel).$build({ id: 1 });
* console.log(bike.$url()) // outputs '/api/bikes/1'
* ```
*
* @param {string} _prefix url portion
* @return {BuilderApi} self
*/
setUrlPrefix: function(_prefix) {
return this.setProperty('urlPrefix', _prefix);
},
/**
* @memberof ExtendedBuilderApi#
*
* @description Changes the model's primary key.
*
* Primary keys are passed to scope's url methods to generate urls. The default primary key is 'id'.
*
* **ATTENTION** Primary keys are extracted from raw data, so _key must use raw api naming.
*
* @param {string|function} _key New primary key.
* @return {BuilderApi} self
*/
setPrimaryKey: function(_key) {
return this.setProperty('primaryKey', _key);
},
/**
* @memberof ExtendedBuilderApi#
*
* @description Assigns a serializer to a given attribute.
*
* A _serializer is:
* * an object that defines both a `decode` and a `encode` method
* * a function that when called returns an object that matches the above description.
* * a string that represents an injectable that matches any of the above descriptions.
*
* @param {string} _name Attribute name
* @param {string|object|function} _serializer The serializer
* @return {BuilderApi} self
*/
attrSerializer: function(_name, _serializer, _opt) {
if(typeof _serializer === 'string') {
_serializer = $injector.get(inflector.camelize(_serializer, true) + 'Serializer');
}
if(isFunction(_serializer)) _serializer = _serializer(_opt);
if(_serializer.decode) this.attrDecoder(_name, bind(_serializer, _serializer.decode));
if(_serializer.encode) this.attrEncoder(_name, bind(_serializer, _serializer.encode));
return this;
},
/// Experimental modifiers
/**
* @memberof ExtendedBuilderApi#
*
* @description Expression attributes are evaluated every time new data is fed to the model.
*
* @param {string} _name Attribute name
* @param {string} _expr Angular expression to evaluate
* @return {BuilderApi} self
*/
attrExpression: function(_name, _expr) {
var filter = $parse(_expr);
return this.on('after-feed', function() {
this[_name] = filter(this);
});
}
};
return restmod.mixin(function() {
this.extend('setUrlPrefix', EXT.setUrlPrefix)
.extend('setPrimaryKey', EXT.setPrimaryKey)
.extend('attrSerializer', EXT.attrSerializer, ['serialize']);
});
}]);
RMModule.factory('RMBuilderRelations', ['$injector', 'inflector', '$log', 'RMUtils', 'restmod', 'RMPackerCache', function($injector, inflector, $log, Utils, restmod, packerCache) {
// wraps a hook callback to give access to the $owner object
function wrapHook(_fun, _owner) {
return function() {
var oldOwner = this.$owner;
this.$owner = _owner;
try {
return _fun.apply(this, arguments);
} finally {
this.$owner = oldOwner;
}
};
}
// wraps a bunch of hooks
function applyHooks(_target, _hooks, _owner) {
for(var key in _hooks) {
if(_hooks.hasOwnProperty(key)) {
_target.$on(key, wrapHook(_hooks[key], _owner));
}
}
}
/**
* @class RelationBuilderApi
*
* @description
*
* Builder DSL extension to build model relations
*
* Adds the following property modifiers:
* * `hasMany` sets a one to many hierarchical relation under the attribute name, maps to {@link RelationBuilderApi#attrAsCollection}
* * `hasOne` sets a one to one hierarchical relation under the attribute name, maps to {@link RelationBuilderApi#attrAsResource}
* * `belongsTo` sets a one to one reference relation under the attribute name, maps to {@link RelationBuilderApi#attrAsReference}
* * `belongsToMany` sets a one to many reference relation under the attribute name, maps to {@link RelationBuilderApi#attrAsReferenceToMany}
*
*/
var EXT = {
/**
* @memberof RelationBuilderApi#
*
* @description Registers a model **resources** relation
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _url Partial url
* @param {string} _source Inline resource alias (optional)
* @param {string} _inverseOf Inverse property name (optional)
* @param {object} _params Generated collection default parameters
* @param {object} _hooks Hooks to be applied just to the generated collection
* @return {BuilderApi} self
*/
attrAsCollection: function(_attr, _model, _url, _source, _inverseOf, _params, _hooks) {
var options, globalHooks; // global relation configuration
this.attrDefault(_attr, function() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
// retrieve global options
options = _model.getProperty('hasMany', {});
globalHooks = options.hooks;
if(_inverseOf) {
var desc = _model.$$getDescription(_inverseOf);
if(!desc || desc.relation !== 'belongs_to') {
$log.warn('Must define an inverse belongsTo relation for inverseOf to work');
_inverseOf = false; // disable the inverse if no inverse relation is found.
}
}
}
var scope = this.$buildScope(_model, _url || inflector.parameterize(_attr)), col; // TODO: name to url transformation should be a Model strategy
// setup collection
col = _model.$collection(_params || null, scope);
if(globalHooks) applyHooks(col, globalHooks, this);
if(_hooks) applyHooks(col, _hooks, this);
col.$dispatch('after-has-many-init');
// set inverse property if required.
if(_inverseOf) {
var self = this;
col.$on('after-add', function(_obj) {
_obj[_inverseOf] = self;
});
}
return col;
});
if(_source || _url) this.attrMap(_attr, _source || _url);
this.attrDecoder(_attr, function(_raw) {
this[_attr].$reset().$decode(_raw);
})
.attrMask(_attr, Utils.WRITE_MASK)
.attrMeta(_attr, { relation: 'has_many' });
return this;
},
/**
* @memberof RelationBuilderApi#
*
* @description Registers a model **resource** relation
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _url Partial url (optional)
* @param {string} _source Inline resource alias (optional)
* @param {string} _inverseOf Inverse property name (optional)
* @param {object} _hooks Hooks to be applied just to the instantiated record
* @return {BuilderApi} self
*/
attrAsResource: function(_attr, _model, _url, _source, _inverseOf, _hooks) {
var options, globalHooks; // global relation configuration
this.attrDefault(_attr, function() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
// retrieve global options
options = _model.getProperty('hasOne', {});
globalHooks = options.hooks;
if(_inverseOf) {
var desc = _model.$$getDescription(_inverseOf);
if(!desc || desc.relation !== 'belongs_to') {
$log.warn('Must define an inverse belongsTo relation for inverseOf to work');
_inverseOf = false; // disable the inverse if no inverse relation is found.
}
}
}
var scope = this.$buildScope(_model, _url || inflector.parameterize(_attr)), inst;
// setup record
inst = _model.$new(null, scope);
if(globalHooks) applyHooks(inst, globalHooks, this);
if(_hooks) applyHooks(inst, _hooks, this);
inst.$dispatch('after-has-one-init');
if(_inverseOf) {
inst[_inverseOf] = this;
}
return inst;
});
if(_source || _url) this.attrMap(_attr, _source || _url);
this.attrDecoder(_attr, function(_raw) {
this[_attr].$decode(_raw);
})
.attrMask(_attr, Utils.WRITE_MASK)
.attrMeta(_attr, { relation: 'has_one' });
return this;
},
/**
* @memberof RelationBuilderApi#
*
* @description Registers a model **reference** relation.
*
* A reference relation expects the host object to provide the primary key of the referenced object or the referenced object itself (including its key).
*
* For example, given the following resource structure with a foreign key:
*
* ```json
* {
* user_id: 20
* }
* ```
*
* Or this other structure with inlined data:
*
* ```json
* {
* user: {
* id: 30,
* name: 'Steve'
* }
* }
* ```
*
* You should define the following model:
*
* ```javascript
* restmod.model('/bikes', {
* user: { belongsTo: 'User' } // works for both cases detailed above
* })
* ```
*
* The object generated by the relation is not scoped to the host object, but to it's base class instead (not like hasOne),
* so the type should not be nested.
*
* Its also posible to override the **foreign key name**.
*
* When a object containing a belongsTo reference is encoded for a server request, only the primary key value is sent using the
* same **foreign key name** that was using on decoding. (`user_id` in the above example).
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _key foreign key property name (optional, defaults to _attr + '_id').
* @param {bool} _prefetch if set to true, $fetch will be automatically called on relation object load.
* @return {BuilderApi} self
*/
attrAsReference: function(_attr, _model, _key, _prefetch) {
this.attrDefault(_attr, null)
.attrMask(_attr, Utils.WRITE_MASK)
.attrMeta(_attr, { relation: 'belongs_to' });
function loadModel() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
}
}
// TODO: the following code assumes that attribute is at root level! (when uses this[_attr] or this[_attr + 'Id'])
// inline data handling
this.attrDecoder(_attr, function(_raw) {
if(_raw === null) return null;
loadModel();
if(!this[_attr] || this[_attr].$pk !== _model.inferKey(_raw)) {
this[_attr] = _model.$buildRaw(_raw);
} else {
this[_attr].$decode(_raw);
}
});
// foreign key handling
if(_key !== false) {
this.attrMap(_attr + 'Id', _key || '*', true) // set a forced mapping to always generate key
.attrDecoder(_attr + 'Id', function(_value) {
if(_value === undefined) return;
if(!this[_attr] || this[_attr].$pk !== _value) {
if(_value !== null && _value !== false) {
loadModel();
this[_attr] = packerCache.resolve(_model.$new(_value)); // resolve inmediatelly if cached
if(_prefetch) this[_attr].$fetch();
} else {
this[_attr] = null;
}
}
})
.attrEncoder(_attr + 'Id', function() {
return this[_attr] ? this[_attr].$pk : null;
});
}
return this;
},
/**
* @memberof RelationBuilderApi#
*
* @description Registers a model **reference** relation.
*
* A reference relation expects the host object to provide the primary key of the referenced objects or the referenced objects themselves (including its key).
*
* For example, given the following resource structure with a foreign key array:
*
* ```json
* {
* users_ids: [20, 30]
* }
* ```
*
* Or this other structure with inlined data:
*
* ```json
* {
* users: [{
* id: 20,
* name: 'Steve'
* },{
* id: 30,
* name: 'Pili'
* }]
* }
* ```
*
* You should define the following model:
*
* ```javascript
* restmod.model('/bikes', {
* users: { belongsToMany: 'User' } // works for both cases detailed above
* })
* ```
*
* The object generated by the relation is not scoped to the host object, but to it's base class instead (unlike hasMany),
* so the referenced type should not be nested.
*
* When a object containing a belongsToMany reference is encoded for a server request, only the primary key value is sent for each object.
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _keys Server name for the property that holds the referenced keys in response and request.
* @return {BuilderApi} self
*/
attrAsReferenceToMany: function(_attr, _model, _keys) {
this.attrDefault(_attr, function() { return []; })
.attrMask(_attr, Utils.WRITE_MASK)
.attrMeta(_attr, { relation: 'belongs_to_many' });
// TODO: the following code assumes that attribute is at root level! (when uses this[_attr])
function loadModel() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
}
}
function processInbound(_raw, _ref) {
loadModel();
_ref.length = 0;
// TODO: reuse objects that do not change (compare $pks)
for(var i = 0, l = _raw.length; i < l; i++) {
if(typeof _raw[i] === 'object') {
_ref.push(_model.$buildRaw(_raw[i]));
} else {
_ref.push(packerCache.resolve(_model.$new(_raw[i])));
}
}
}
// inline data handling
this.attrDecoder(_attr, function(_raw) {
// TODO: if _keys == _attr then inbound data will be processed twice!
if(_raw) processInbound(_raw, this[_attr]);
});
// foreign key handling
if(_keys !== false) {
var attrIds = inflector.singularize(_attr) + 'Ids';
this.attrMap(attrIds, _keys || '*', true)
.attrDecoder(attrIds, function(_raw) {
if(_raw) processInbound(_raw, this[_attr]);
})
.attrEncoder(attrIds, function() {
var result = [], others = this[_attr];
for(var i = 0, l = others.length; i < l; i++) {
result.push(others[i].$pk);
}
return result;
});
}
return this;
}
};
return restmod.mixin(function() {
this.extend('attrAsCollection', EXT.attrAsCollection, ['hasMany', 'path', 'source', 'inverseOf', 'params', 'hooks']) // TODO: rename source to map, but disable attrMap if map is used here...
.extend('attrAsResource', EXT.attrAsResource, ['hasOne', 'path', 'source', 'inverseOf', 'hooks'])
.extend('attrAsReference', EXT.attrAsReference, ['belongsTo', 'key', 'prefetch'])
.extend('attrAsReferenceToMany', EXT.attrAsReferenceToMany, ['belongsToMany', 'keys']);
});
}]);
RMModule.factory('RMModelFactory', ['$injector', 'inflector', 'RMUtils', 'RMScopeApi', 'RMCommonApi', 'RMRecordApi', 'RMListApi', 'RMCollectionApi', 'RMExtendedApi', 'RMSerializer', 'RMBuilder',
function($injector, inflector, Utils, ScopeApi, CommonApi, RecordApi, ListApi, CollectionApi, ExtendedApi, Serializer, Builder) {
var NAME_RGX = /(.*?)([^\/]+)\/?$/,
extend = Utils.extendOverriden;
return function(_baseUrl, _baseChain) {
// IDEA: make constructor inaccessible, use separate type for records?
// * Will ensure proper usage.
// * Will lose type checking
function Model(_scope, _pk) {
this.$scope = _scope || Model;
this.$pk = _pk;
this.$initialize();
}
_baseUrl = Utils.cleanUrl(_baseUrl);
var config = {
primaryKey: 'id',
urlPrefix: null
},
serializer = new Serializer(Model),
defaults = [], // attribute defaults as an array of [key, value]
computes = [], // computed attributes
meta = {}, // atribute metadata
hooks = {},
builder; // the model builder
// make sure the resource name and plural name are available if posible:
if(!config.name && _baseUrl) {
config.name = inflector.singularize(_baseUrl.replace(NAME_RGX, '$2'));
}
if(!config.plural && config.name) {
config.plural = inflector.pluralize(config.name);
}
var Collection = Utils.buildArrayType(),
List = Utils.buildArrayType(),
Dummy = function(_asCollection) {
this.$isCollection = _asCollection;
this.$initialize(); // TODO: deprecate this
};
// Collection factory
function newCollection(_params, _scope) {
var col = new Collection();
col.$scope = _scope || Model;
col.$params = _params;
col.$initialize();
return col;
}
///// Setup static api
/**
* @class StaticApi
* @extends ScopeApi
* @extends CommonApi
*
* @description
*
* The restmod type API, every generated restmod model type exposes this API.
*
* @property {object} $type Reference to the type itself, for compatibility with the {@link ScopeApi}
*
* #### About object creation
*
* Direct construction of object instances using `new` is not recommended. A collection of
* static methods are available to generate new instances of a model, for more information
* read the {@link ModelCollection} documentation.
*/
extend(Model, {
// gets an attribute description (metadata)
$$getDescription: function(_attribute) {
return meta[_attribute];
},
// definition chain
$$chain: [],
// keep a reference to type itself for scope api compatibility
$type: Model,
// creates a new model bound by default to the static scope
$new: function(_pk, _scope) {
return new Model(_scope || Model, _pk);
},
// creates a new collection bound by default to the static scope
$collection: newCollection,
// gets scope url
$url: function() {
return config.urlPrefix ? Utils.joinUrl(config.urlPrefix, _baseUrl) : _baseUrl;
},
// bubbles events comming from related resources
$dispatch: function(_hook, _args, _ctx) {
var cbs = hooks[_hook], i, cb;
if(cbs) {
for(i = 0; !!(cb = cbs[i]); i++) {
cb.apply(_ctx || this, _args || []);
}
}
return this;
},
/**
* @memberof StaticApi#
*
* @description
*
* Extracts the primary key from raw record data.
*
* Uses the key configured in the PRIMARY_KEY variable or 'id' by default.
*
* Some considerations:
* * This method can be overriden to handle other scenarios.
* * This method should not change the raw data passed to it.
* * The primary key value extracted by this method should be comparable using the == operator.
*
* @param {string} _rawData Raw object data (before it goes into decode)
* @return {mixed} The primary key value.
*/
inferKey: function(_rawData) {
if(!_rawData || typeof _rawData[config.primaryKey] === 'undefined') return null;
return _rawData[config.primaryKey];
},
/**
* @memberof StaticApi#
*
* @description
*
* Gets a model's internal property value.
*
* Some builtin properties:
* * url
* * urlPrefix
* * primaryKey
*
* @param {string} _key Property name
* @param {mixed} _default Value to return if property is not defined
* @return {mixed} value
*/
getProperty: function(_key, _default) {
var val = config[_key];
return val !== undefined ? val : _default;
},
/**
* @memberof StaticApi#
*
* @description Returns true if model is nested.
*
* An nested model can only be used as a nested resource (using hasMany or hasOne relations)
*
* @return {boolean} true if model is nested.
*/
isNested: function() {
return !_baseUrl;
},
/**
* @memberof StaticApi#
*
* @description Returns a resource bound to a given url, with no parent scope.
*
* This can be used to create singleton resources:
*
* ```javascript
* module('BikeShop', []).factory('Status', function(restmod) {
* return restmod.model(null).$single('/api/status');
* };)
* ```
*
* @param {string} _url Url to bound resource to.
* @return {Model} new resource instance.
*/
single: function(_url) {
return new Model({
$urlFor: function() {
return config.urlPrefix ? Utils.joinUrl(config.urlPrefix, _url) : _url;
}
}, '');
},
/**
* Builds a new dummy resource, the dummy resource can be used to execute random queries
* using the same infrastructure as records and collections.
*
* @return {Dummy} the dummy object
*/
dummy: function(_asCollection) {
return new Dummy(_asCollection);
},
/**
* Creates a new record list.
*
* A list is a ordered set of records not bound to a particular scope.
*
* Contained records can belong to any scope.
*
* @return {List} the new list
*/
list: function(_items) {
var list = new List();
if(_items) list.push.apply(list, _items);
return list;
},
/**
* @memberof StaticApi#
*
* @description Returns the model API name.
*
* This name should match the one used throughout the API. It's only used by some extended
* functionality, like the default packer.
*
* By default model name is infered from the url, but for nested models and special cases
* it should be manually set by writing the name and plural properties:
*
* ```javascript
* restmod.model(null, {
* __name__: 'resource',
* __plural__: 'resourciness' // set only if inflector cant properly gess the name.
* });
* ```
*
* @return {boolean} If true, return plural name
* @return {string} The base url.
*/
identity: function(_plural) {
return _plural ? config.plural : config.name;
},
/**
* @memberof StaticApi#
*
* @description Modifies model behavior.
*
* @params {mixed} _mixins One or more mixins or model definitions.
* @return {Model} The model
*/
mix: function(/* mixins */) {
builder.chain(arguments);
this.$$chain.push.apply(this.$$chain, arguments);
return this;
},
// Strategies
/**
* @memberof StaticApi#
*
* @description The model unpacking strategy
*
* This method is called to extract record data from a request response, its also
* responsible of handling the response metadata.
*
* Override this method to change the metadata processing strategy, by default its a noop
*
* @params {mixed} _resource Related resource instance
* @params {mixed} _raw Response raw data
* @return {mixed} Resource raw data
*/
unpack: function(_resource, _raw) { return _raw; },
/**
* @memberof StaticApi#
*
* @description The model packing strategy
*
* This method is called to wrap raw record data to be sent in a request.
*
* Override this method to change the request packing strategy, by default its a noop
*
* @params {mixed} _resource Related resource instance
* @params {mixed} _raw Record data to be sent (can be an array if resource is collection)
* @return {mixed} Wrapped data
*/
pack: function(_record, _raw) { return _raw; },
/**
* @memberof StaticApi#
*
* @description The model decoding strategy
*
* This method is called to populate a record from raw data (unppacked)
*/
decode: serializer.decode,
/**
* @memberof StaticApi#
*
* @description The model encoding strategy
*
* This method is called to extract raw data from a record to be sent to server (before packing)
*/
encode: serializer.encode,
/**
* @memberof StaticApi#
*
* @description The model name decoding strategy
*
* This method is called on every raw record data property to rename it, by default is not defined.
*
* Override this method to change the property renaming strategy.
*
* @params {string} _name Response (raw) name
* @return {string} Record name
*/
decodeName: null,
/**
* @memberof StaticApi#
*
* @description The model name encoding strategy
*
* This method is called when encoding a record to rename the record properties into the raw data properties,
* by default is not defined.
*
* Override this method to change the property renaming strategy
*
* @params {string} _name Record name
* @return {string} Response (raw) name
*/
encodeName: null
}, ScopeApi);
///// Setup record api
extend(Model.prototype, {
$type: Model,
// default initializer: loads the default parameter values
$initialize: function() {
var tmp, i, self = this;
for(i = 0; (tmp = defaults[i]); i++) {
this[tmp[0]] = (typeof tmp[1] === 'function') ? tmp[1].apply(this) : tmp[1];
}
for(i = 0; (tmp = computes[i]); i++) {
Object.defineProperty(self, tmp[0], {
enumerable: true,
get: tmp[1]
});
}
}
}, CommonApi, RecordApi, ExtendedApi);
///// Setup collection api
extend(Collection.prototype, {
$type: Model,
// provide record contructor
$new: function(_pk, _scope) {
return Model.$new(_pk, _scope || this);
},
// provide collection constructor
$collection: function(_params, _scope) {
_params = this.$params ? angular.extend({}, this.$params, _params) : _params;
return newCollection(_params, _scope || this.$scope);
}
}, ListApi, ScopeApi, CommonApi, CollectionApi, ExtendedApi);
///// Setup list api
extend(List.prototype, {
$type: Model
}, ListApi, CommonApi);
///// Setup dummy api
extend(Dummy.prototype, {
$type: Model,
$initialize: function() {
// Nothing by default
}
}, CommonApi);
///// Setup builder
var APIS = {
Model: Model,
Record: Model.prototype,
Collection: Collection.prototype,
List: List.prototype,
Dummy: Dummy.prototype
};
// helper used to extend api's
function helpDefine(_api, _name, _fun) {
var api = APIS[_api];
Utils.assert(!!api, 'Invalid api name $1', _api);
if(_name) {
api[_name] = Utils.override(api[_name], _fun);
} else {
Utils.extendOverriden(api, _fun);
}
}
// load the builder
builder = new Builder(angular.extend(serializer.dsl(), {
/**
* @memberof BuilderApi#
*
* Sets one of the model's configuration properties.
*
* The following configuration parameters are available by default:
* * primaryKey: The model's primary key, defaults to **id**. Keys must use server naming convention!
* * urlPrefix: Url prefix to prepend to resource url, usefull to use in a base mixin when multiples models have the same prefix.
* * url: The resource base url, null by default. If not given resource is considered nested.
*
* @param {string} _key The configuration key to set.
* @param {mixed} _value The configuration value.
* @return {BuilderApi} self
*/
setProperty: function (_key, _value) {
config[_key] = _value;
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets the default value for an attribute.
*
* Defaults values are set only on object construction phase.
*
* if `_init` is a function, then its evaluated every time the
* default value is required.
*
* @param {string} _attr Attribute name
* @param {mixed} _init Defaulf value / iniline function
* @return {BuilderApi} self
*/
attrDefault: function(_attr, _init) {
defaults.push([_attr, _init]);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets a computed value for an attribute.
*
* Computed values are set only on object construction phase.
* Computed values are always masked
*
* @param {string} _attr Attribute name
* @param {function} _fn Function that returns value
* @return {BuilderApi} self
*/
attrComputed: function(_attr, _fn) {
computes.push([_attr, _fn]);
this.attrMask(_attr, true);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers attribute metadata.
*
* @param {string} _name Attribute name
* @param {object} _metadata Attribute metadata
* @return {BuilderApi} self
*/
attrMeta: function(_name, _metadata) {
meta[_name] = extend(meta[_name] || {}, _metadata);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Adds methods to the model
*
* This method allows to extend the different model API's.
*
* The following API's can be extended using this method:
* * Model: The static API, affects the Model object itself.
* * Record: Affects each record generated by the model.
* * Collection: Affects each collection generated by the model.
* * Scope: Affects both the static API and collections.
* * Resource: Affects records and collections.
*
* If no api is given
*
*
* If no scope is given,
* By default this method extends the **Record** prototype.
* If called with an object
* instead of a function it can be used to extend the collection and the type with
* specific implementations.
*
* Usage:
*
* ```javascript
* restmod.mixin(function() {
* this.define('myRecordMethod', function() {})
* .define('Model.myStaticMethod', function() {})
* .define('Collection', { }); // object to extend collection api with
* });
* ```
*
* It is posible to override an existing method using define, if overriden,
* the old method can be called using `this.$super` inside de new method.
*
* @param {string} _where
* @param {function} _fun Function to define or object with particular implementations
* @param {string} _api One of the api names listed above, if not given defaults to 'Record'
* @return {BuilderApi} self
*/
define: function(_where, _fun) {
var name = false, api = 'Record';
if(typeof _fun === 'object' && _fun) {
api = _where;
} else {
name = _where.split('.');
if(name.length === 1) {
name = name[0];
} else {
api = name[0];
name = name[1];
}
}
switch(api) {
// Virtual API's
case 'List':
helpDefine('Collection', name, _fun);
helpDefine('List', name, _fun);
break;
case 'Scope':
helpDefine('Model', name, _fun);
helpDefine('Collection', name, _fun);
break;
case 'Resource':
helpDefine('Record', name, _fun);
helpDefine('Collection', name, _fun);
helpDefine('List', name, _fun);
helpDefine('Dummy', name, _fun);
break;
default:
helpDefine(api, name, _fun);
}
return this;
},
/**
* @memberof BuilderApi#
*
* @description Adds an event hook
*
* Hooks are used to extend or modify the model behavior, and are not
* designed to be used as an event listening system.
*
* The given function is executed in the hook's context, different hooks
* make different parameters available to callbacks.
*
* @param {string} _hook The hook name, refer to restmod docs for builtin hooks.
* @param {function} _do function to be executed
* @return {BuilderApi} self
*/
on: function(_hook, _do) {
(hooks[_hook] || (hooks[_hook] = [])).push(_do);
return this;
}
}));
builder.chain(_baseChain); // load base chain.
return Model;
};
}]);
/**
* @class FastQ
*
* @description
*
* Synchronous promise implementation (partial)
*
*/
RMModule.factory('RMFastQ', [function() {
var isFunction = angular.isFunction;
function simpleQ(_val, _withError) {
if(_val && isFunction(_val.then)) return wrappedQ(_val);
return {
simple: true,
then: function(_success, _error) {
return simpleQ(_withError ? _error(_val) : _success(_val));
},
'finally': function(_cb) {
var result = _cb();
if(result && isFunction(_val.then)) {
// if finally returns a promise, then
return wrappedQ(_val.then(
function() { return _withError ? simpleQ(_val, true) : _val; },
function() { return _withError ? simpleQ(_val, true) : _val; })
);
} else {
return this;
}
}
};
}
function wrappedQ(_promise) {
if(_promise.simple) return _promise;
var simple;
// when resolved, make $q a simpleQ
_promise.then(function(_val) {
simple = simpleQ(_val);
}, function(_val) {
simple = simpleQ(_val, true);
});
return {
then: function(_success, _error) {
return simple ?
simple.then(_success, _error) :
wrappedQ(_promise.then(_success, _error));
},
'finally': function(_cb) {
return simple ?
simple['finally'](_cb) :
wrappedQ(_promise['finally'](_cb));
}
};
}
return {
reject: function(_reason) {
return simpleQ(_reason, true);
},
// non waiting promise, if resolved executes immediately
when: function(_val) {
return simpleQ(_val, false);
},
wrap: wrappedQ
};
}]);
RMModule.factory('RMPackerCache', [function() {
var packerCache;
/**
* @class PackerCache
*
* @description
*
* The packer cache service enables packing strategies to register raw object data that can be then used by
* supporting relations during the decoding process to preload other related resources.
*
* This is specially useful for apis that include linked objects data in external metadata.
*
* The packer cache is reset on every response unwrapping so it's not supposed to be used as an
* application wide cache.
*
* ### For extension developers:
*
* Use the `feed` method to add new raw data to cache.
*
* ### For relation developers:
*
* Use the `resolve` method to inject cache data into a given identified record.
*
*/
return {
/**
* @memberof PackerCache#
*
* @description Feed data to the cache.
*
* @param {string} _name Resource name (singular)
* @param {array} _rawRecords Raw record data as an array
*/
feed: function(_name, _rawRecords) {
packerCache[_name] = _rawRecords; // TODO: maybe append new record to support extended scenarios.
},
// IDEA: feedSingle: would require two step resolve many -> single
/**
* @memberof PackerCache#
*
* @description Searches for data matching the record's pk, if found data is then fed to the record using $decode.
*
* @param {RecordApi} _record restmod record to resolve, must be identified.
* @return {RecordApi} The record, so call can be nested.
*/
resolve: function(_record) {
if(packerCache) { // make sure this is a packer cache enabled context.
var modelType = _record.$type,
cache = packerCache[modelType.identity(true)];
if(cache && _record.$pk) {
for(var i = 0, l = cache.length; i < l; i++) {
if(_record.$pk === modelType.inferKey(cache[i])) { // this could be sort of slow? nah
_record.$decode(cache[i]);
break;
}
}
}
}
return _record;
},
// private api method used by the unwrapper function.
prepare: function() {
packerCache = {};
},
// private api internal method used by the unwrapper function.
clear: function() {
packerCache = null;
}
};
}]);
RMModule.factory('RMSerializer', ['$injector', 'inflector', '$filter', 'RMUtils', function($injector, inflector, $filter, Utils) {
function extract(_from, _path) {
var node;
for(var i = 0; _from && (node = _path[i]); i++) {
_from = _from[node];
}
return _from;
}
function insert(_into, _path, _value) {
for(var i = 0, l = _path.length-1; i < l; i++) {
var node = _path[i];
_into = _into[node] || (_into[node] = {});
}
_into[_path[_path.length-1]] = _value;
}
return function(_strategies) {
var isArray = angular.isArray;
// Private serializer attributes
var masks = {},
decoders = {},
encoders = {},
mapped = {},
mappings = {},
vol = {};
function isMasked(_name, _mask) {
if(typeof _mask === 'function') return _mask(_name);
var mask = masks[_name];
return (mask && (mask === true || mask.indexOf(_mask) !== -1));
}
function decode(_from, _to, _prefix, _mask, _ctx) {
var key, decodedName, fullName, value, maps, isMapped, i, l,
prefix = _prefix ? _prefix + '.' : '';
// explicit mappings
maps = mappings[_prefix];
if(maps) {
for(i = 0, l = maps.length; i < l; i++) {
fullName = prefix + maps[i].path;
if(isMasked(fullName, _mask)) continue;
if(maps[i].map) {
value = extract(_from, maps[i].map);
} else {
value = _from[_strategies.encodeName ? _strategies.encodeName(maps[i].path) : maps[i].path];
}
if(!maps[i].forced && value === undefined) continue;
value = decodeProp(value, fullName, _mask, _ctx);
if(value !== undefined) _to[maps[i].path] = value;
}
}
// implicit mappings
for(key in _from) {
if(_from.hasOwnProperty(key)) {
decodedName = _strategies.decodeName ? _strategies.decodeName(key) : key;
if(decodedName[0] === '$') continue;
if(maps) {
// ignore already mapped keys
// TODO: ignore nested mappings too.
for(
// is this so much faster than using .some? http://jsperf.com/some-vs-for-loop
isMapped = false, i = 0, l = maps.length;
i < l && !(isMapped = (maps[i].mapPath === key));
i++
);
if(isMapped) continue;
}
fullName = prefix + decodedName;
// prevent masked or already mapped properties to be set
if(mapped[fullName] || isMasked(fullName, _mask)) continue;
value = decodeProp(_from[key], fullName, _mask, _ctx);
if(value !== undefined) _to[decodedName] = value; // ignore value if filter returns undefined
}
}
}
function decodeProp(_value, _name, _mask, _ctx) {
var filter = decoders[_name], result = _value;
if(filter) {
result = filter.call(_ctx, _value);
} else if(typeof _value === 'object') {
// IDEA: make extended decoding/encoding optional, could be a little taxing for some apps
if(isArray(_value)) {
result = [];
for(var i = 0, l = _value.length; i < l; i++) {
result.push(decodeProp(_value[i], _name + '[]', _mask, _ctx));
}
} else if(_value) {
result = {};
decode(_value, result, _name, _mask, _ctx);
}
}
return result;
}
function encode(_from, _to, _prefix, _mask, _ctx) {
var key, fullName, encodedName, value, maps,
prefix = _prefix ? _prefix + '.' : '';
// implicit mappings
for(key in _from) {
if(_from.hasOwnProperty(key) && key[0] !== '$') {
fullName = prefix + key;
// prevent masked or already mapped properties to be copied
if(mapped[fullName] || isMasked(fullName, _mask)) continue;
value = encodeProp(_from[key], fullName, _mask, _ctx);
if(value !== undefined) {
encodedName = _strategies.encodeName ? _strategies.encodeName(key) : key;
_to[encodedName] = value;
}
if(vol[fullName]) delete _from[key];
}
}
// explicit mappings:
maps = mappings[_prefix];
if(maps) {
for(var i = 0, l = maps.length; i < l; i++) {
fullName = prefix + maps[i].path;
if(isMasked(fullName, _mask)) continue;
value = _from[maps[i].path];
if(!maps[i].forced && value === undefined) continue;
value = encodeProp(value, fullName, _mask, _ctx);
if(value !== undefined) {
if(maps[i].map) {
insert(_to, maps[i].map, value);
} else {
_to[_strategies.encodeName ? _strategies.encodeName(maps[i].path) : maps[i].path] = value;
}
}
}
}
}
function encodeProp(_value, _name, _mask, _ctx) {
var filter = encoders[_name], result = _value;
if(filter) {
result = filter.call(_ctx, _value);
} else if(_value !== null && typeof _value === 'object' && typeof _value.toJSON !== 'function') {
// IDEA: make deep decoding/encoding optional, could be a little taxing for some apps
if(isArray(_value)) {
result = [];
for(var i = 0, l = _value.length; i < l; i++) {
result.push(encodeProp(_value[i], _name + '[]', _mask, _ctx));
}
} else if(_value) {
result = {};
encode(_value, result, _name, _mask, _ctx);
}
}
return result;
}
return {
// decodes a raw record into a record
decode: function(_record, _raw, _mask) {
decode(_raw, _record, '', _mask, _record);
},
// encodes a record, returning a raw record
encode: function(_record, _mask) {
var raw = {};
encode(_record, raw, '', _mask, _record);
return raw;
},
// builds a serializerd DSL, is a standalone object that can be extended.
dsl: function() {
return {
/**
* @memberof BuilderApi#
*
* @description Sets an attribute mapping.
*
* Allows a explicit server to model property mapping to be defined.
*
* For example, to map the response property `stats.created_at` to model's `created` property.
*
* ```javascript
* builder.attrMap('created', 'stats.created_at');
* ```
*
* It's also posible to use a wildcard '*' as server name to use the default name decoder as
* server name. This is used to force a property to be processed on decode/encode even if its
* not present on request/record (respectively), by doing this its posible, for example, to define
* a dynamic property that is generated automatically before the object is send to the server.
*
* @param {string} _attr Attribute name
* @param {string} _serverName Server (request/response) property name
* @return {BuilderApi} self
*/
attrMap: function(_attr, _serverPath, _forced) {
// extract parent node from client name:
var index = _attr.lastIndexOf('.'),
node = index !== -1 ? _attr.substr(0, index) : '',
leaf = index !== -1 ? _attr.substr(index + 1) : _attr;
mapped[_attr] = true;
var nodes = (mappings[node] || (mappings[node] = []));
nodes.push({ path: leaf, map: _serverPath === '*' ? null : _serverPath.split('.'), mapPath: _serverPath, forced: _forced });
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets an attribute mask.
*
* An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations.
*
* The attribute mask is a string composed by:
* * C: To prevent attribute from being sent on create
* * R: To prevent attribute from being loaded from server
* * U: To prevent attribute from being sent on update
*
* For example, the following will prevent an attribute to be send on create or update:
*
* ```javascript
* builder.attrMask('readOnly', 'CU');
* ```
*
* If a true boolean value is passed as mask, then 'CRU' will be used
* If a false boolean valus is passed as mask, then mask will be removed
*
* @param {string} _attr Attribute name
* @param {boolean|string} _mask Attribute mask
* @return {BuilderApi} self
*/
attrMask: function(_attr, _mask) {
if(!_mask) {
delete masks[_attr];
} else {
masks[_attr] = _mask;
}
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a decoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrDecoder: function(_attr, _filter, _filterParam, _chain) {
if(typeof _filter === 'string') {
var filter = $filter(_filter);
_filter = function(_value) { return filter(_value, _filterParam); };
}
decoders[_attr] = _chain ? Utils.chain(decoders[_attr], _filter) : _filter;
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a encoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrEncoder: function(_attr, _filter, _filterParam, _chain) {
if(typeof _filter === 'string') {
var filter = $filter(_filter);
_filter = function(_value) { return filter(_value, _filterParam); };
}
encoders[_attr] = _chain ? Utils.chain(encoders[_attr], _filter) : _filter;
return this;
},
/**
* @memberof BuilderApi#
*
* @description Makes an attribute volatile, a volatile attribute is deleted from source after encoding.
*
* @param {string} _name Attribute name
* @param {boolean} _isVolatile defaults to true, if set to false then the attribute is no longer volatile.
* @return {BuilderApi} self
*/
attrVolatile: function(_attr, _isVolatile) {
vol[_attr] = _isVolatile === undefined ? true : _isVolatile;
return this;
}
};
}
};
};
}]);
RMModule.factory('DefaultPacker', ['restmod', 'inflector', 'RMPackerCache', function(restmod, inflector, packerCache) {
function include(_source, _list, _do) {
for(var i = 0, l = _list.length; i < l; i++) {
_do(_list[i], _source[_list[i]]);
}
}
function exclude(_source, _skip, _do) {
for(var key in _source) {
if(_source.hasOwnProperty(key) && _skip.indexOf(key) === -1) {
_do(key, _source[key]);
}
}
}
// process links and stores them in the packer cache
function processFeature(_raw, _name, _feature, _other, _do) {
if(_feature === '.' || _feature === true) {
var skip = [_name];
if(_other) skip.push.apply(skip, angular.isArray(_other) ? _other : [_other]);
exclude(_raw, skip, _do);
} else if(typeof _feature === 'string') {
exclude(_raw[_feature], [], _do);
} else { // links is an array
include(_raw, _feature, _do);
}
}
/**
* @class DefaultPacker
*
* @description
*
* Simple `$unpack` implementation that attempts to cover the standard proposed by
* [active_model_serializers](https://github.com/rails-api/active_model_serializers.
*
* This is a simplified version of the wrapping structure recommented by the jsonapi.org standard,
* it supports side loaded associated resources (via supporting relations) and metadata extraction.
*
* To activate add mixin to model chain
*
* ```javascript
* restmodProvide.rebase('DefaultPacker');
* ```
*
* ### Json root
*
* By default the mixin will use the singular model name as json root for single resource requests
* and pluralized name for collection requests. Make sure the model name is correctly set.
*
* To override the name used by the mixin set the **jsonRootSingle** and **jsonRootMany** variables.
* Or set **jsonRoot** to override both.
*
* ### Side loaded resources
*
* By default the mixin will look for links to other resources in the 'linked' root property, you
* can change this by setting the jsonLinks variable. To use the root element as link source
* use `jsonLinks: '.'`. You can also explicitly select which properties to consider links using an
* array of property names. To skip links processing altogether, set it to false.
*
* Links are expected to use the pluralized version of the name for the referenced model. For example,
* given the following response:
*
* ```json
* {
* bikes: [...],
* links {
* parts: [...]
* }
* }
* ```
*
* Restmod will expect that the Part model plural name is correctly set parts. Only properties declared
* as reference relations (belongsTo and belongsToMany) will be correctly resolved.
*
* ### Metadata
*
* By default metadata is only captured if it comes in the 'meta' root property. Metadata is then
* stored in the $meta property of the resource being unwrapped.
*
* Just like links, to change the metadata source property set the jsonMeta property to the desired name, set
* it to '.' to capture the entire raw response or set it to false to skip metadata and set it to an array of properties
* to be extract selected properties.
*
* @property {mixed} single The expected single resource wrapper property name
* @property {object} plural The expected collection wrapper property name
* @property {mixed} links The links repository property name
* @property {object} meta The metadata repository property name
*
*/
return restmod.mixin(function() {
this.define('Model.unpack', function(_resource, _raw) {
var name = null,
links = this.getProperty('jsonLinks', 'linked'),
meta = this.getProperty('jsonMeta', 'meta');
if(_resource.$isCollection) {
name = this.getProperty('jsonRootMany') || this.getProperty('jsonRoot') || this.getProperty('plural');
} else {
// TODO: use plural for single resource option.
name = this.getProperty('jsonRootSingle') || this.getProperty('jsonRoot') || this.getProperty('name');
}
if(meta) {
_resource.$metadata = {};
processFeature(_raw, name, meta, links, function(_key, _value) {
_resource.$metadata[_key] = _value;
});
}
if(links) {
processFeature(_raw, name, links, meta, function(_key, _value) {
// TODO: check that cache is an array.
packerCache.feed(_key, _value);
});
}
return _raw[name];
});
});
}]);
/**
* @class Utils
*
* @description
*
* Various utilities used across the library.
*
*/
RMModule.factory('RMUtils', ['$log', function($log) {
// determine browser support for object prototype changing
var IFRAME_REF = [];
var PROTO_SETTER = (function() {
var Test = function() {};
if(Object.setPrototypeOf) {
return function(_target, _proto) {
Object.setPrototypeOf(_target, _proto); // Not sure about supporting this...
};
} else if((new Test).__proto__ === Test.prototype) {
return function(_target, _proto) {
_target.__proto__ = _proto;
};
}
})();
var Utils = {
// Ignore Masks
CREATE_MASK: 'C',
UPDATE_MASK: 'U',
READ_MASK: 'R',
WRITE_MASK: 'CU',
FULL_MASK: 'CRU',
/**
* @memberof Utils
*
* @description
*
* Formats a string
*
* @param {string} _str String to format
* @param {array} _args String arguments
* @return {string} Formated string
*/
format: function(_str, _args) {
for(var i = 0; _args && i < _args.length; i++) {
_str = _str.replace('$' + (i+1), _args[i]);
}
return _str;
},
/**
* @memberof Utils
*
* @description
*
* Test for a condition to be met, if not an exception is thrown.
*
* @param {boolean} _condition Condition to assert
* @param {string} _msg Error message
*/
assert: function(_condition, _msg /*, params */) {
if(!_condition) {
var params = Array.prototype.slice.call(arguments, 2);
_msg = Utils.format(_msg, params);
$log.error(_msg); // log error message
throw new Error(_msg);
}
},
/**
* @memberof Utils
*
* @description
*
* Simple url joining, returns null if _head or _tail is null.
*
* @param {string} _head Url prefix
* @param {string} _tail Url suffix
* @return {string} Resulting url
*/
joinUrl: function(_head, _tail) {
if(!_head || !_tail) return null;
return (_head+'').replace(/\/$/, '') + '/' + (_tail+'').replace(/^\//, '');
},
/**
* @memberof Utils
*
* @description
*
* Cleans trailing slashes from an url
*
* @param {string} _url Url to clean
* @return {string} Resulting url
*/
cleanUrl: function(_url) {
return _url ? _url.replace(/\/$/, '') : _url;
},
/**
* @memberof Utils
*
* @description
*
* Chains to filtering functions together
*
* @param {function} _first original function
* @param {function} _fun function to call on the original function result
* @return {mixed} value returned by the last function call
*/
chain: function(_first, _fun) {
if(!_first) return _fun;
return function(_value) {
return _fun.call(this, _first.call(this, _value));
};
},
/**
* @memberof Utils
*
* @description
*
* Override a property value, making overriden function available as this.$super
*
* @param {function} _super Original value
* @param {mixed} _fun New property value
* @return {mixed} Value returned by new function
*/
override: function(_super, _fun) {
if(!_super || typeof _fun !== 'function') return _fun;
return function() {
var oldSuper = this.$super;
try {
this.$super = _super;
return _fun.apply(this, arguments);
} finally {
this.$super = oldSuper;
}
};
},
/**
* @memberof Utils
*
* @description
*
* Extend an object using `Utils.override` instead of just replacing the functions.
*
* @param {object} _target Object to be extended
* @param {object} _other Source object
*/
extendOverriden: function(_target) {
for(var i = 1; i < arguments.length; i++) {
var other = arguments[i];
for(var key in other) {
if(other.hasOwnProperty(key)) {
_target[key] = _target[key] && typeof _target[key] === 'function' ? Utils.override(_target[key], other[key]) : other[key];
}
}
}
return _target;
},
/**
* @memberof Utils
*
* @description
*
* Generates a new array type, handles platform specifics (bag-O-hacks)
*
* @return {object} Independent array type.
*/
buildArrayType: function(_forceIframe) {
var arrayType;
if(PROTO_SETTER && !_forceIframe) {
// Use object prototype override technique
//
// Very nice array subclassing analysis: http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/#why_subclass_an_array
//
var SubArray = function() {
var arr = [ ];
arr.push.apply(arr, arguments);
PROTO_SETTER(arr, SubArray.prototype);
return arr;
};
SubArray.prototype = [];
SubArray.prototype.last = function() {
return this[this.length - 1];
};
arrayType = SubArray;
} else {
// Use iframe hijack technique for IE11<
//
// Based on the awesome blog post of Dean Edwards: http://dean.edwards.name/weblog/2006/11/hooray/
//
// create a hidden <iframe>.
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.height = 0;
iframe.width = 0;
iframe.border = 0;
document.body.appendChild(iframe);
// write a script into the <iframe> and steal its Array object.
window.frames[window.frames.length - 1].document.write('<script>parent.RestmodArray = Array;<\/script>');
// take the array object and move it to local context.
arrayType = window.RestmodArray;
delete window.RestmodArray;
// copy this context Array's extensions to new array type (could be a little slow...)
for(var key in Array.prototype) {
if(typeof Array.prototype[key] === 'function' && !arrayType.prototype[key]) {
arrayType.prototype[key] = Array.prototype[key];
}
}
// remove iframe from DOM.
//
// Even though MS says that removing iframe from DOM will release it's related structures (http://msdn.microsoft.com/en-us/library/ie/gg622929(v=vs.85).aspx),
// actually keeping it referenced has proven to be enough to keep the structures alive. (that includes our array type)
//
document.body.removeChild(iframe);
IFRAME_REF.push(iframe); // keep iframe reference!
}
return arrayType;
}
};
return Utils;
}]);
})(angular); |
/**
* @author sole / http://soledadpenades.com
* @author mrdoob / http://mrdoob.com
* @author Robert Eisele / http://www.xarg.org
* @author Philippe / http://philippe.elsass.me
* @author Robert Penner / http://www.robertpenner.com/easing_terms_of_use.html
* @author Paul Lewis / http://www.aerotwist.com/
* @author lechecacharro
* @author Josh Faul / http://jocafa.com/
* @author egraether / http://egraether.com/
*/
var TWEEN = TWEEN || ( function () {
var _tweens = [];
return {
REVISION: '7',
getAll: function () {
return _tweens;
},
removeAll: function () {
_tweens = [];
},
add: function ( tween ) {
_tweens.push( tween );
},
remove: function ( tween ) {
var i = _tweens.indexOf( tween );
if ( i !== -1 ) {
_tweens.splice( i, 1 );
}
},
update: function ( time ) {
if ( _tweens.length === 0 ) return false;
var i = 0, l = _tweens.length;
time = time !== undefined ? time : Date.now();
while ( i < l ) {
if ( _tweens[ i ].update( time ) ) {
i ++;
} else {
_tweens.splice( i, 1 );
l --;
}
}
return true;
}
};
} )();
TWEEN.Tween = function ( object ) {
var _object = object;
var _valuesStart = {};
var _valuesEnd = {};
var _duration = 1000;
var _delayTime = 0;
var _startTime = null;
var _easingFunction = TWEEN.Easing.Linear.None;
var _interpolationFunction = TWEEN.Interpolation.Linear;
var _chainedTweens = [];
var _onStartCallback = null;
var _onStartCallbackFired = false;
var _onUpdateCallback = null;
var _onCompleteCallback = null;
this.to = function ( properties, duration ) {
if ( duration !== undefined ) {
_duration = duration;
}
_valuesEnd = properties;
return this;
};
this.start = function ( time ) {
TWEEN.add( this );
_onStartCallbackFired = false;
_startTime = time !== undefined ? time : Date.now();
_startTime += _delayTime;
for ( var property in _valuesEnd ) {
// This prevents the engine from interpolating null values
if ( _object[ property ] === null ) {
continue;
}
// check if an Array was provided as property value
if ( _valuesEnd[ property ] instanceof Array ) {
if ( _valuesEnd[ property ].length === 0 ) {
continue;
}
// create a local copy of the Array with the start value at the front
_valuesEnd[ property ] = [ _object[ property ] ].concat( _valuesEnd[ property ] );
}
_valuesStart[ property ] = _object[ property ];
}
return this;
};
this.stop = function () {
TWEEN.remove( this );
return this;
};
this.delay = function ( amount ) {
_delayTime = amount;
return this;
};
this.easing = function ( easing ) {
_easingFunction = easing;
return this;
};
this.interpolation = function ( interpolation ) {
_interpolationFunction = interpolation;
return this;
};
this.chain = function () {
_chainedTweens = arguments;
return this;
};
this.onStart = function ( callback ) {
_onStartCallback = callback;
return this;
};
this.onUpdate = function ( callback ) {
_onUpdateCallback = callback;
return this;
};
this.onComplete = function ( callback ) {
_onCompleteCallback = callback;
return this;
};
this.update = function ( time ) {
if ( time < _startTime ) {
return true;
}
if ( _onStartCallbackFired === false ) {
if ( _onStartCallback !== null ) {
_onStartCallback.call( _object );
}
_onStartCallbackFired = true;
}
var elapsed = ( time - _startTime ) / _duration;
elapsed = elapsed > 1 ? 1 : elapsed;
var value = _easingFunction( elapsed );
for ( var property in _valuesStart ) {
var start = _valuesStart[ property ];
var end = _valuesEnd[ property ];
if ( end instanceof Array ) {
_object[ property ] = _interpolationFunction( end, value );
} else {
_object[ property ] = start + ( end - start ) * value;
}
}
if ( _onUpdateCallback !== null ) {
_onUpdateCallback.call( _object, value );
}
if ( elapsed == 1 ) {
if ( _onCompleteCallback !== null ) {
_onCompleteCallback.call( _object );
}
for ( var i = 0, l = _chainedTweens.length; i < l; i ++ ) {
_chainedTweens[ i ].start( time );
}
return false;
}
return true;
};
};
TWEEN.Easing = {
Linear: {
None: function ( k ) {
return k;
}
},
Quadratic: {
In: function ( k ) {
return k * k;
},
Out: function ( k ) {
return k * ( 2 - k );
},
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
return - 0.5 * ( --k * ( k - 2 ) - 1 );
}
},
Cubic: {
In: function ( k ) {
return k * k * k;
},
Out: function ( k ) {
return --k * k * k + 1;
},
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
return 0.5 * ( ( k -= 2 ) * k * k + 2 );
}
},
Quartic: {
In: function ( k ) {
return k * k * k * k;
},
Out: function ( k ) {
return 1 - ( --k * k * k * k );
},
InOut: function ( k ) {
if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
}
},
Quintic: {
In: function ( k ) {
return k * k * k * k * k;
},
Out: function ( k ) {
return --k * k * k * k * k + 1;
},
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
}
},
Sinusoidal: {
In: function ( k ) {
return 1 - Math.cos( k * Math.PI / 2 );
},
Out: function ( k ) {
return Math.sin( k * Math.PI / 2 );
},
InOut: function ( k ) {
return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
}
},
Exponential: {
In: function ( k ) {
return k === 0 ? 0 : Math.pow( 1024, k - 1 );
},
Out: function ( k ) {
return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
},
InOut: function ( k ) {
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
}
},
Circular: {
In: function ( k ) {
return 1 - Math.sqrt( 1 - k * k );
},
Out: function ( k ) {
return Math.sqrt( 1 - ( --k * k ) );
},
InOut: function ( k ) {
if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
}
},
Elastic: {
In: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
},
Out: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
},
InOut: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
}
},
Back: {
In: function ( k ) {
var s = 1.70158;
return k * k * ( ( s + 1 ) * k - s );
},
Out: function ( k ) {
var s = 1.70158;
return --k * k * ( ( s + 1 ) * k + s ) + 1;
},
InOut: function ( k ) {
var s = 1.70158 * 1.525;
if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
}
},
Bounce: {
In: function ( k ) {
return 1 - TWEEN.Easing.Bounce.Out( 1 - k );
},
Out: function ( k ) {
if ( k < ( 1 / 2.75 ) ) {
return 7.5625 * k * k;
} else if ( k < ( 2 / 2.75 ) ) {
return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
} else if ( k < ( 2.5 / 2.75 ) ) {
return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
} else {
return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
}
},
InOut: function ( k ) {
if ( k < 0.5 ) return TWEEN.Easing.Bounce.In( k * 2 ) * 0.5;
return TWEEN.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
}
}
};
TWEEN.Interpolation = {
Linear: function ( v, k ) {
var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.Linear;
if ( k < 0 ) return fn( v[ 0 ], v[ 1 ], f );
if ( k > 1 ) return fn( v[ m ], v[ m - 1 ], m - f );
return fn( v[ i ], v[ i + 1 > m ? m : i + 1 ], f - i );
},
Bezier: function ( v, k ) {
var b = 0, n = v.length - 1, pw = Math.pow, bn = TWEEN.Interpolation.Utils.Bernstein, i;
for ( i = 0; i <= n; i++ ) {
b += pw( 1 - k, n - i ) * pw( k, i ) * v[ i ] * bn( n, i );
}
return b;
},
CatmullRom: function ( v, k ) {
var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.CatmullRom;
if ( v[ 0 ] === v[ m ] ) {
if ( k < 0 ) i = Math.floor( f = m * ( 1 + k ) );
return fn( v[ ( i - 1 + m ) % m ], v[ i ], v[ ( i + 1 ) % m ], v[ ( i + 2 ) % m ], f - i );
} else {
if ( k < 0 ) return v[ 0 ] - ( fn( v[ 0 ], v[ 0 ], v[ 1 ], v[ 1 ], -f ) - v[ 0 ] );
if ( k > 1 ) return v[ m ] - ( fn( v[ m ], v[ m ], v[ m - 1 ], v[ m - 1 ], f - m ) - v[ m ] );
return fn( v[ i ? i - 1 : 0 ], v[ i ], v[ m < i + 1 ? m : i + 1 ], v[ m < i + 2 ? m : i + 2 ], f - i );
}
},
Utils: {
Linear: function ( p0, p1, t ) {
return ( p1 - p0 ) * t + p0;
},
Bernstein: function ( n , i ) {
var fc = TWEEN.Interpolation.Utils.Factorial;
return fc( n ) / fc( i ) / fc( n - i );
},
Factorial: ( function () {
var a = [ 1 ];
return function ( n ) {
var s = 1, i;
if ( a[ n ] ) return a[ n ];
for ( i = n; i > 1; i-- ) s *= i;
return a[ n ] = s;
};
} )(),
CatmullRom: function ( p0, p1, p2, p3, t ) {
var v0 = ( p2 - p0 ) * 0.5, v1 = ( p3 - p1 ) * 0.5, t2 = t * t, t3 = t * t2;
return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
}
}
};
|
/*!
* # Semantic UI 2.1.8 - Progress
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.progress = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.progress.settings, parameters)
: $.extend({}, $.fn.progress.settings),
className = settings.className,
metadata = settings.metadata,
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$bar = $(this).find(selector.bar),
$progress = $(this).find(selector.progress),
$label = $(this).find(selector.label),
element = this,
instance = $module.data(moduleNamespace),
animating = false,
transitionEnd,
module
;
module = {
initialize: function() {
module.debug('Initializing progress bar', settings);
module.set.duration();
module.set.transitionEvent();
module.read.metadata();
module.read.settings();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of progress', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous progress for', $module);
clearInterval(instance.interval);
module.remove.state();
$module.removeData(moduleNamespace);
instance = undefined;
},
reset: function() {
module.set.percent(0);
module.set.value(0);
},
complete: function() {
if(module.percent === undefined || module.percent < 100) {
module.set.percent(100);
}
},
read: {
metadata: function() {
var
data = {
percent : $module.data(metadata.percent),
total : $module.data(metadata.total),
value : $module.data(metadata.value)
}
;
if(data.percent) {
module.debug('Current percent value set from metadata', data.percent);
module.set.percent(data.percent);
}
if(data.total) {
module.debug('Total value set from metadata', data.total);
module.set.total(data.total);
}
if(data.value) {
module.debug('Current value set from metadata', data.value);
module.set.value(data.value);
module.set.progress(data.value);
}
},
settings: function() {
if(settings.total !== false) {
module.debug('Current total set in settings', settings.total);
module.set.total(settings.total);
}
if(settings.value !== false) {
module.debug('Current value set in settings', settings.value);
module.set.value(settings.value);
module.set.progress(module.value);
}
if(settings.percent !== false) {
module.debug('Current percent set in settings', settings.percent);
module.set.percent(settings.percent);
}
}
},
increment: function(incrementValue) {
var
maxValue,
startValue,
newValue
;
if( module.has.total() ) {
startValue = module.get.value();
incrementValue = incrementValue || 1;
newValue = startValue + incrementValue;
maxValue = module.get.total();
module.debug('Incrementing value', startValue, newValue, maxValue);
if(newValue > maxValue ) {
module.debug('Value cannot increment above total', maxValue);
newValue = maxValue;
}
}
else {
startValue = module.get.percent();
incrementValue = incrementValue || module.get.randomValue();
newValue = startValue + incrementValue;
maxValue = 100;
module.debug('Incrementing percentage by', startValue, newValue);
if(newValue > maxValue ) {
module.debug('Value cannot increment above 100 percent');
newValue = maxValue;
}
}
module.set.progress(newValue);
},
decrement: function(decrementValue) {
var
total = module.get.total(),
startValue,
newValue
;
if(total) {
startValue = module.get.value();
decrementValue = decrementValue || 1;
newValue = startValue - decrementValue;
module.debug('Decrementing value by', decrementValue, startValue);
}
else {
startValue = module.get.percent();
decrementValue = decrementValue || module.get.randomValue();
newValue = startValue - decrementValue;
module.debug('Decrementing percentage by', decrementValue, startValue);
}
if(newValue < 0) {
module.debug('Value cannot decrement below 0');
newValue = 0;
}
module.set.progress(newValue);
},
has: {
total: function() {
return (module.get.total() !== false);
}
},
get: {
text: function(templateText) {
var
value = module.value || 0,
total = module.total || 0,
percent = (animating)
? module.get.displayPercent()
: module.percent || 0,
left = (module.total > 0)
? (total - value)
: (100 - percent)
;
templateText = templateText || '';
templateText = templateText
.replace('{value}', value)
.replace('{total}', total)
.replace('{left}', left)
.replace('{percent}', percent)
;
module.debug('Adding variables to progress bar text', templateText);
return templateText;
},
randomValue: function() {
module.debug('Generating random increment percentage');
return Math.floor((Math.random() * settings.random.max) + settings.random.min);
},
numericValue: function(value) {
return (typeof value === 'string')
? (value.replace(/[^\d.]/g, '') !== '')
? +(value.replace(/[^\d.]/g, ''))
: false
: value
;
},
transitionEnd: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
},
// gets current displayed percentage (if animating values this is the intermediary value)
displayPercent: function() {
var
barWidth = $bar.width(),
totalWidth = $module.width(),
minDisplay = parseInt($bar.css('min-width'), 10),
displayPercent = (barWidth > minDisplay)
? (barWidth / totalWidth * 100)
: module.percent
;
return (settings.precision > 0)
? Math.round(displayPercent * (10 * settings.precision)) / (10 * settings.precision)
: Math.round(displayPercent)
;
},
percent: function() {
return module.percent || 0;
},
value: function() {
return module.value || 0;
},
total: function() {
return module.total || false;
}
},
is: {
success: function() {
return $module.hasClass(className.success);
},
warning: function() {
return $module.hasClass(className.warning);
},
error: function() {
return $module.hasClass(className.error);
},
active: function() {
return $module.hasClass(className.active);
},
visible: function() {
return $module.is(':visible');
}
},
remove: {
state: function() {
module.verbose('Removing stored state');
delete module.total;
delete module.percent;
delete module.value;
},
active: function() {
module.verbose('Removing active state');
$module.removeClass(className.active);
},
success: function() {
module.verbose('Removing success state');
$module.removeClass(className.success);
},
warning: function() {
module.verbose('Removing warning state');
$module.removeClass(className.warning);
},
error: function() {
module.verbose('Removing error state');
$module.removeClass(className.error);
}
},
set: {
barWidth: function(value) {
if(value > 100) {
module.error(error.tooHigh, value);
}
else if (value < 0) {
module.error(error.tooLow, value);
}
else {
$bar
.css('width', value + '%')
;
$module
.attr('data-percent', parseInt(value, 10))
;
}
},
duration: function(duration) {
duration = duration || settings.duration;
duration = (typeof duration == 'number')
? duration + 'ms'
: duration
;
module.verbose('Setting progress bar transition duration', duration);
$bar
.css({
'transition-duration': duration
})
;
},
percent: function(percent) {
percent = (typeof percent == 'string')
? +(percent.replace('%', ''))
: percent
;
// round display percentage
percent = (settings.precision > 0)
? Math.round(percent * (10 * settings.precision)) / (10 * settings.precision)
: Math.round(percent)
;
module.percent = percent;
if( !module.has.total() ) {
module.value = (settings.precision > 0)
? Math.round( (percent / 100) * module.total * (10 * settings.precision)) / (10 * settings.precision)
: Math.round( (percent / 100) * module.total * 10) / 10
;
if(settings.limitValues) {
module.value = (module.value > 100)
? 100
: (module.value < 0)
? 0
: module.value
;
}
}
module.set.barWidth(percent);
module.set.labelInterval();
module.set.labels();
settings.onChange.call(element, percent, module.value, module.total);
},
labelInterval: function() {
var
animationCallback = function() {
module.verbose('Bar finished animating, removing continuous label updates');
clearInterval(module.interval);
animating = false;
module.set.labels();
}
;
clearInterval(module.interval);
$bar.one(transitionEnd + eventNamespace, animationCallback);
module.timer = setTimeout(animationCallback, settings.duration + 100);
animating = true;
module.interval = setInterval(module.set.labels, settings.framerate);
},
labels: function() {
module.verbose('Setting both bar progress and outer label text');
module.set.barLabel();
module.set.state();
},
label: function(text) {
text = text || '';
if(text) {
text = module.get.text(text);
module.debug('Setting label to text', text);
$label.text(text);
}
},
state: function(percent) {
percent = (percent !== undefined)
? percent
: module.percent
;
if(percent === 100) {
if(settings.autoSuccess && !(module.is.warning() || module.is.error())) {
module.set.success();
module.debug('Automatically triggering success at 100%');
}
else {
module.verbose('Reached 100% removing active state');
module.remove.active();
}
}
else if(percent > 0) {
module.verbose('Adjusting active progress bar label', percent);
module.set.active();
}
else {
module.remove.active();
module.set.label(settings.text.active);
}
},
barLabel: function(text) {
if(text !== undefined) {
$progress.text( module.get.text(text) );
}
else if(settings.label == 'ratio' && module.total) {
module.debug('Adding ratio to bar label');
$progress.text( module.get.text(settings.text.ratio) );
}
else if(settings.label == 'percent') {
module.debug('Adding percentage to bar label');
$progress.text( module.get.text(settings.text.percent) );
}
},
active: function(text) {
text = text || settings.text.active;
module.debug('Setting active state');
if(settings.showActivity && !module.is.active() ) {
$module.addClass(className.active);
}
module.remove.warning();
module.remove.error();
module.remove.success();
if(text) {
module.set.label(text);
}
settings.onActive.call(element, module.value, module.total);
},
success : function(text) {
text = text || settings.text.success;
module.debug('Setting success state');
$module.addClass(className.success);
module.remove.active();
module.remove.warning();
module.remove.error();
module.complete();
if(text) {
module.set.label(text);
}
settings.onSuccess.call(element, module.total);
},
warning : function(text) {
text = text || settings.text.warning;
module.debug('Setting warning state');
$module.addClass(className.warning);
module.remove.active();
module.remove.success();
module.remove.error();
module.complete();
if(text) {
module.set.label(text);
}
settings.onWarning.call(element, module.value, module.total);
},
error : function(text) {
text = text || settings.text.error;
module.debug('Setting error state');
$module.addClass(className.error);
module.remove.active();
module.remove.success();
module.remove.warning();
module.complete();
if(text) {
module.set.label(text);
}
settings.onError.call(element, module.value, module.total);
},
transitionEvent: function() {
transitionEnd = module.get.transitionEnd();
},
total: function(totalValue) {
module.total = totalValue;
},
value: function(value) {
module.value = value;
},
progress: function(value) {
var
numericValue = module.get.numericValue(value),
percentComplete
;
if(numericValue === false) {
module.error(error.nonNumeric, value);
}
if( module.has.total() ) {
module.set.value(numericValue);
percentComplete = (numericValue / module.total) * 100;
module.debug('Calculating percent complete from total', percentComplete);
module.set.percent( percentComplete );
}
else {
percentComplete = numericValue;
module.debug('Setting value to exact percentage value', percentComplete);
module.set.percent( percentComplete );
}
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.progress.settings = {
name : 'Progress',
namespace : 'progress',
debug : false,
verbose : false,
performance : true,
random : {
min : 2,
max : 5
},
duration : 300,
autoSuccess : true,
showActivity : true,
limitValues : true,
label : 'percent',
precision : 0,
framerate : (1000 / 30), /// 30 fps
percent : false,
total : false,
value : false,
onChange : function(percent, value, total){},
onSuccess : function(total){},
onActive : function(value, total){},
onError : function(value, total){},
onWarning : function(value, total){},
error : {
method : 'The method you called is not defined.',
nonNumeric : 'Progress value is non numeric',
tooHigh : 'Value specified is above 100%',
tooLow : 'Value specified is below 0%'
},
regExp: {
variable: /\{\$*[A-z0-9]+\}/g
},
metadata: {
percent : 'percent',
total : 'total',
value : 'value'
},
selector : {
bar : '> .bar',
label : '> .label',
progress : '.bar > .progress'
},
text : {
active : false,
error : false,
success : false,
warning : false,
percent : '{percent}%',
ratio : '{value} of {total}'
},
className : {
active : 'active',
error : 'error',
success : 'success',
warning : 'warning'
}
};
})( jQuery, window, document ); |
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M383.8 92.2C348.5 64.5 304.1 48 256 48c-48 0-92.3 16.5-127.6 44 41.6 44.8 64.3 103 64 164.3-.3 61-23.3 118.6-64.9 162.9 35.4 28 80.1 44.8 128.5 44.8 48.5 0 93.3-16.8 128.8-45-41.5-44.3-64.5-101.8-64.8-162.7-.3-61.2 22.3-119.3 63.8-164.1z"/><path d="M353.1 255.1c0 26.9 5.1 53 15.1 77.8 9.6 23.6 23.3 44.9 40.8 63.6 34.1-37.1 55-86.5 55-140.5 0-54.5-21.2-104.2-55.8-141.4-17.1 18.5-30.6 39.6-40 62.7-10 24.8-15.1 51-15.1 77.8zM159.3 255.1c0-26.9-5.1-53-15.1-77.8-9.4-23.2-22.9-44.4-40.2-62.9-34.7 37.2-56 87-56 141.6 0 54.2 21 103.6 55.2 140.7 17.6-18.7 31.4-40.1 41-63.8 10-24.7 15.1-50.9 15.1-77.8z"/></svg>','md-tennisball'); |
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var Auth = require('../Auth');
var ClientConstants = require('../constants/client');
module.exports = Handshake;
Util.inherits(Handshake, Sequence);
function Handshake(options, callback) {
Sequence.call(this, options, callback);
options = options || {};
this._config = options.config;
this._handshakeInitializationPacket = null;
}
Handshake.prototype.determinePacket = function(firstByte) {
if (firstByte === 0xff) {
return Packets.ErrorPacket;
}
if (!this._handshakeInitializationPacket) {
return Packets.HandshakeInitializationPacket;
}
if (firstByte === 0xfe) {
return Packets.UseOldPasswordPacket;
}
};
Handshake.prototype['HandshakeInitializationPacket'] = function(packet) {
this._handshakeInitializationPacket = packet;
this._config.protocol41 = packet.protocol41;
var serverSSLSupport = packet.serverCapabilities1 & ClientConstants.CLIENT_SSL;
if (this._config.ssl) {
if (!serverSSLSupport) {
var err = new Error('Server does not support secure connnection');
err.code = 'HANDSHAKE_NO_SSL_SUPPORT';
err.fatal = true;
this.end(err);
return;
}
this._config.clientFlags |= ClientConstants.CLIENT_SSL;
this.emit('packet', new Packets.SSLRequestPacket({
clientFlags : this._config.clientFlags,
maxPacketSize : this._config.maxPacketSize,
charsetNumber : this._config.charsetNumber
}));
this.emit('start-tls');
} else {
this._sendCredentials();
}
};
Handshake.prototype._tlsUpgradeCompleteHandler = function() {
this._sendCredentials();
};
Handshake.prototype._sendCredentials = function(serverHello) {
var packet = this._handshakeInitializationPacket;
this.emit('packet', new Packets.ClientAuthenticationPacket({
clientFlags : this._config.clientFlags,
maxPacketSize : this._config.maxPacketSize,
charsetNumber : this._config.charsetNumber,
user : this._config.user,
scrambleBuff : (packet.protocol41)
? Auth.token(this._config.password, packet.scrambleBuff())
: Auth.scramble323(packet.scrambleBuff(), this._config.password),
database : this._config.database,
protocol41 : packet.protocol41
}));
};
Handshake.prototype['UseOldPasswordPacket'] = function(packet) {
if (!this._config.insecureAuth) {
var err = new Error(
'MySQL server is requesting the old and insecure pre-4.1 auth mechanism.' +
'Upgrade the user password or use the {insecureAuth: true} option.'
);
err.code = 'HANDSHAKE_INSECURE_AUTH';
err.fatal = true;
this.end(err);
return;
}
this.emit('packet', new Packets.OldPasswordPacket({
scrambleBuff : Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password)
}));
};
Handshake.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet, true);
err.fatal = true;
this.end(err);
};
|
//
// Dust - Asynchronous Templating v2.1.5
// http://akdubya.github.com/dustjs
//
// Copyright (c) 2010, Aleksander Williams
// Released under the MIT License.
//
var dust = {};
function getGlobal(){
return (function(){
return this.dust;
}).call(null);
}
(function(dust) {
if(!dust) {
return;
}
var NONE = 'NONE',
ERROR = 'ERROR',
WARN = 'WARN',
INFO = 'INFO',
DEBUG = 'DEBUG',
loggingLevels = [DEBUG, INFO, WARN, ERROR, NONE],
logger = {},
loggerContext;
dust.debugLevel = NONE;
dust.silenceErrors = false;
// Try to find the console logger in window scope (browsers) or top level scope (node.js)
if (typeof window !== 'undefined' && window && window.console) {
loggerContext = window.console;
} else if (typeof console !== 'undefined' && console) {
loggerContext = console;
}
// robust logger for node.js, modern browsers, and IE <= 9.
logger.log = loggerContext ? function() {
var originalLog = loggerContext.log;
// Do this for normal browsers
if (typeof originalLog === 'function') {
logger.log = function() {
originalLog.apply(loggerContext, arguments);
};
logger.log.apply(this, arguments);
} else {
// Do this for IE <= 9
logger.log = function() {
var message = Array.prototype.slice.apply(arguments).join(' ');
originalLog(message);
};
logger.log.apply(this, arguments);
}
} : function() { /* no op */ };
/**
* If dust.isDebug is true, Log dust debug statements, info statements, warning statements, and errors.
* This default implementation will print to the console if it exists.
* @param {String|Error} message the message to print/throw
* @param {String} type the severity of the message(ERROR, WARN, INFO, or DEBUG)
* @public
*/
dust.log = function(message, type) {
type = type || INFO;
if (dust.debugLevel !== NONE && dust.indexInArray(loggingLevels, type) >= dust.indexInArray(loggingLevels, dust.debugLevel)) {
if(!dust.logQueue) {
dust.logQueue = [];
}
dust.logQueue.push({message: message, type: type});
logger.log("[DUST " + type + "]: " + message);
}
if (!dust.silenceErrors && type === ERROR) {
if (typeof message === 'string') {
throw new Error(message);
} else {
throw message;
}
}
};
/**
* If debugging is turned on(dust.isDebug=true) log the error message and throw it.
* Otherwise try to keep rendering. This is useful to fail hard in dev mode, but keep rendering in production.
* @param {Error} error the error message to throw
* @param {Object} chunk the chunk the error was thrown from
* @public
*/
dust.onError = function(error, chunk) {
logger.log('[!!!DEPRECATION WARNING!!!]: dust.onError will no longer return a chunk object.');
dust.log(error.message || error, ERROR);
if(!dust.silenceErrors) {
throw error;
} else {
return chunk;
}
};
dust.helpers = {};
dust.cache = {};
dust.register = function(name, tmpl) {
if (!name) return;
dust.cache[name] = tmpl;
};
dust.render = function(name, context, callback) {
var chunk = new Stub(callback).head;
try {
dust.load(name, chunk, Context.wrap(context, name)).end();
} catch (err) {
dust.log(err, ERROR);
}
};
dust.stream = function(name, context) {
var stream = new Stream();
dust.nextTick(function() {
try {
dust.load(name, stream.head, Context.wrap(context, name)).end();
} catch (err) {
dust.log(err, ERROR);
}
});
return stream;
};
dust.renderSource = function(source, context, callback) {
return dust.compileFn(source)(context, callback);
};
dust.compileFn = function(source, name) {
var tmpl = dust.loadSource(dust.compile(source, name));
return function(context, callback) {
var master = callback ? new Stub(callback) : new Stream();
dust.nextTick(function() {
if(typeof tmpl === 'function') {
tmpl(master.head, Context.wrap(context, name)).end();
}
else {
dust.log(new Error('Template [' + name + '] cannot be resolved to a Dust function'), ERROR);
}
});
return master;
};
};
dust.load = function(name, chunk, context) {
var tmpl = dust.cache[name];
if (tmpl) {
return tmpl(chunk, context);
} else {
if (dust.onLoad) {
return chunk.map(function(chunk) {
dust.onLoad(name, function(err, src) {
if (err) return chunk.setError(err);
if (!dust.cache[name]) dust.loadSource(dust.compile(src, name));
dust.cache[name](chunk, context).end();
});
});
}
return chunk.setError(new Error("Template Not Found: " + name));
}
};
dust.loadSource = function(source, path) {
return eval(source);
};
if (Array.isArray) {
dust.isArray = Array.isArray;
} else {
dust.isArray = function(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
};
}
// indexOf shim for arrays for IE <= 8
// source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
dust.indexInArray = function(arr, item, fromIndex) {
fromIndex = +fromIndex || 0;
if (Array.prototype.indexOf) {
return arr.indexOf(item, fromIndex);
} else {
if ( arr === undefined || arr === null ) {
throw new TypeError( 'cannot call method "indexOf" of null' );
}
var length = arr.length; // Hack to convert object.length to a UInt32
if (Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === item) {
return fromIndex;
}
}
return -1;
}
};
dust.nextTick = (function() {
if (typeof process !== "undefined") {
return process.nextTick;
} else {
return function(callback) {
setTimeout(callback,0);
};
}
} )();
dust.isEmpty = function(value) {
if (dust.isArray(value) && !value.length) return true;
if (value === 0) return false;
return (!value);
};
// apply the filter chain and return the output string
dust.filter = function(string, auto, filters) {
if (filters) {
for (var i=0, len=filters.length; i<len; i++) {
var name = filters[i];
if (name === "s") {
auto = null;
}
else if (typeof dust.filters[name] === 'function') {
string = dust.filters[name](string);
}
else {
dust.log('Invalid filter [' + name + ']', WARN);
}
}
}
// by default always apply the h filter, unless asked to unescape with |s
if (auto) {
string = dust.filters[auto](string);
}
return string;
};
dust.filters = {
h: function(value) { return dust.escapeHtml(value); },
j: function(value) { return dust.escapeJs(value); },
u: encodeURI,
uc: encodeURIComponent,
js: function(value) {
if (!JSON) {
dust.log('JSON is undefined. JSON stringify has not been used on [' + value + ']', WARN);
return value;
} else {
return JSON.stringify(value);
}
},
jp: function(value) {
if (!JSON) {dust.log('JSON is undefined. JSON parse has not been used on [' + value + ']', WARN);
return value;
} else {
return JSON.parse(value);
}
}
};
function Context(stack, global, blocks, templateName) {
this.stack = stack;
this.global = global;
this.blocks = blocks;
this.templateName = templateName;
}
dust.makeBase = function(global) {
return new Context(new Stack(), global);
};
Context.wrap = function(context, name) {
if (context instanceof Context) {
return context;
}
return new Context(new Stack(context), {}, null, name);
};
Context.prototype.get = function(key) {
var ctx = this.stack, value, globalValue;
while(ctx) {
if (ctx.isObject) {
value = ctx.head[key];
if (!(value === undefined)) {
return value;
}
}
ctx = ctx.tail;
}
globalValue = this.global ? this.global[key] : undefined;
if(typeof globalValue === 'undefined') {
dust.log('Cannot find the value for reference [{' + key + '}] in template [' + this.templateName + ']');
}
return globalValue;
};
//supports dot path resolution, function wrapped apply, and searching global paths
Context.prototype.getPath = function(cur, down) {
var ctx = this.stack, ctxThis,
len = down.length,
tail = cur ? undefined : this.stack.tail;
if (cur && len === 0) return ctx.head;
ctx = ctx.head;
var i = 0;
while(ctx && i < len) {
ctxThis = ctx;
ctx = ctx[down[i]];
i++;
while (!ctx && !cur){
// i is the count of number of path elements matched. If > 1 then we have a partial match
// and do not continue to search for the rest of the path.
// Note: a falsey value at the end of a matched path also comes here.
// This returns the value or undefined if we just have a partial match.
if (i > 1) return ctx;
if (tail){
ctx = tail.head;
tail = tail.tail;
i=0;
} else if (!cur) {
//finally search this.global. we set cur to true to halt after
ctx = this.global;
cur = true;
i=0;
}
}
}
if (typeof ctx == 'function'){
//wrap to preserve context 'this' see #174
return function() {
try {
return ctx.apply(ctxThis, arguments);
} catch (err) {
dust.log(err, ERROR);
return ctx.head;
}
};
}
else {
return ctx;
}
};
Context.prototype.push = function(head, idx, len) {
return new Context(new Stack(head, this.stack, idx, len), this.global, this.blocks, this.templateName);
};
Context.prototype.rebase = function(head) {
return new Context(new Stack(head), this.global, this.blocks, this.templateName);
};
Context.prototype.current = function() {
return this.stack.head;
};
Context.prototype.getBlock = function(key, chk, ctx) {
if (typeof key === "function") {
var tempChk = new Chunk();
key = key(tempChk, this).data.join("");
}
var blocks = this.blocks;
if (!blocks) {
dust.log('No blocks for context[{' + key + '}] in template [' + this.templateName + ']', DEBUG);
return;
}
var len = blocks.length, fn;
while (len--) {
fn = blocks[len][key];
if (fn) return fn;
}
};
Context.prototype.shiftBlocks = function(locals) {
var blocks = this.blocks,
newBlocks;
if (locals) {
if (!blocks) {
newBlocks = [locals];
} else {
newBlocks = blocks.concat([locals]);
}
return new Context(this.stack, this.global, newBlocks, this.templateName);
}
return this;
};
function Stack(head, tail, idx, len) {
this.tail = tail;
this.isObject = !dust.isArray(head) && head && typeof head === "object";
this.head = head;
this.index = idx;
this.of = len;
}
function Stub(callback) {
this.head = new Chunk(this);
this.callback = callback;
this.out = '';
}
Stub.prototype.flush = function() {
var chunk = this.head;
while (chunk) {
if (chunk.flushable) {
this.out += chunk.data.join(""); //ie7 perf
} else if (chunk.error) {
this.callback(chunk.error);
dust.log('Chunk error [' + chunk.error + '] thrown. Ceasing to render this template.', WARN);
this.flush = function() {};
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.callback(null, this.out);
};
function Stream() {
this.head = new Chunk(this);
}
Stream.prototype.flush = function() {
var chunk = this.head;
while(chunk) {
if (chunk.flushable) {
this.emit('data', chunk.data.join("")); //ie7 perf
} else if (chunk.error) {
this.emit('error', chunk.error);
dust.log('Chunk error [' + chunk.error + '] thrown. Ceasing to render this template.', WARN);
this.flush = function() {};
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.emit('end');
};
Stream.prototype.emit = function(type, data) {
if (!this.events) {
dust.log('No events to emit', INFO);
return false;
}
var handler = this.events[type];
if (!handler) {
dust.log('Event type [' + type + '] does not exist', WARN);
return false;
}
if (typeof handler === 'function') {
handler(data);
} else if (dust.isArray(handler)) {
var listeners = handler.slice(0);
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i](data);
}
} else {
dust.log('Event Handler [' + handler + '] is not of a type that is handled by emit', WARN);
}
};
Stream.prototype.on = function(type, callback) {
if (!this.events) {
this.events = {};
}
if (!this.events[type]) {
dust.log('Event type [' + type + '] does not exist. Using just the specified callback.', WARN);
if(callback) {
this.events[type] = callback;
} else {
dust.log('Callback for type [' + type + '] does not exist. Listener not registered.', WARN);
}
} else if(typeof this.events[type] === 'function') {
this.events[type] = [this.events[type], callback];
} else {
this.events[type].push(callback);
}
return this;
};
Stream.prototype.pipe = function(stream) {
this.on("data", function(data) {
try {
stream.write(data, "utf8");
} catch (err) {
dust.log(err, ERROR);
}
}).on("end", function() {
try {
return stream.end();
} catch (err) {
dust.log(err, ERROR);
}
}).on("error", function(err) {
stream.error(err);
});
return this;
};
function Chunk(root, next, taps) {
this.root = root;
this.next = next;
this.data = []; //ie7 perf
this.flushable = false;
this.taps = taps;
}
Chunk.prototype.write = function(data) {
var taps = this.taps;
if (taps) {
data = taps.go(data);
}
this.data.push(data);
return this;
};
Chunk.prototype.end = function(data) {
if (data) {
this.write(data);
}
this.flushable = true;
this.root.flush();
return this;
};
Chunk.prototype.map = function(callback) {
var cursor = new Chunk(this.root, this.next, this.taps),
branch = new Chunk(this.root, cursor, this.taps);
this.next = branch;
this.flushable = true;
callback(branch);
return cursor;
};
Chunk.prototype.tap = function(tap) {
var taps = this.taps;
if (taps) {
this.taps = taps.push(tap);
} else {
this.taps = new Tap(tap);
}
return this;
};
Chunk.prototype.untap = function() {
this.taps = this.taps.tail;
return this;
};
Chunk.prototype.render = function(body, context) {
return body(this, context);
};
Chunk.prototype.reference = function(elem, context, auto, filters) {
if (typeof elem === "function") {
elem.isFunction = true;
// Changed the function calling to use apply with the current context to make sure
// that "this" is wat we expect it to be inside the function
elem = elem.apply(context.current(), [this, context, null, {auto: auto, filters: filters}]);
if (elem instanceof Chunk) {
return elem;
}
}
if (!dust.isEmpty(elem)) {
return this.write(dust.filter(elem, auto, filters));
} else {
return this;
}
};
Chunk.prototype.section = function(elem, context, bodies, params) {
// anonymous functions
if (typeof elem === "function") {
elem = elem.apply(context.current(), [this, context, bodies, params]);
// functions that return chunks are assumed to have handled the body and/or have modified the chunk
// use that return value as the current chunk and go to the next method in the chain
if (elem instanceof Chunk) {
return elem;
}
}
var body = bodies.block,
skip = bodies['else'];
// a.k.a Inline parameters in the Dust documentations
if (params) {
context = context.push(params);
}
/*
Dust's default behavior is to enumerate over the array elem, passing each object in the array to the block.
When elem resolves to a value or object instead of an array, Dust sets the current context to the value
and renders the block one time.
*/
//non empty array is truthy, empty array is falsy
if (dust.isArray(elem)) {
if (body) {
var len = elem.length, chunk = this;
if (len > 0) {
// any custom helper can blow up the stack
// and store a flattened context, guard defensively
if(context.stack.head) {
context.stack.head['$len'] = len;
}
for (var i=0; i<len; i++) {
if(context.stack.head) {
context.stack.head['$idx'] = i;
}
chunk = body(chunk, context.push(elem[i], i, len));
}
if(context.stack.head) {
context.stack.head['$idx'] = undefined;
context.stack.head['$len'] = undefined;
}
return chunk;
}
else if (skip) {
return skip(this, context);
}
}
}
// true is truthy but does not change context
else if (elem === true) {
if (body) {
return body(this, context);
}
}
// everything that evaluates to true are truthy ( e.g. Non-empty strings and Empty objects are truthy. )
// zero is truthy
// for anonymous functions that did not returns a chunk, truthiness is evaluated based on the return value
//
else if (elem || elem === 0) {
if (body) return body(this, context.push(elem));
// nonexistent, scalar false value, scalar empty string, null,
// undefined are all falsy
} else if (skip) {
return skip(this, context);
}
dust.log('Not rendering section (#) block in template [' + context.templateName + '], because above key was not found', DEBUG);
return this;
};
Chunk.prototype.exists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (!dust.isEmpty(elem)) {
if (body) return body(this, context);
} else if (skip) {
return skip(this, context);
}
dust.log('Not rendering exists (?) block in template [' + context.templateName + '], because above key was not found', DEBUG);
return this;
};
Chunk.prototype.notexists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (dust.isEmpty(elem)) {
if (body) return body(this, context);
} else if (skip) {
return skip(this, context);
}
dust.log('Not rendering not exists (^) block check in template [' + context.templateName + '], because above key was found', DEBUG);
return this;
};
Chunk.prototype.block = function(elem, context, bodies) {
var body = bodies.block;
if (elem) {
body = elem;
}
if (body) {
return body(this, context);
}
return this;
};
Chunk.prototype.partial = function(elem, context, params) {
var partialContext;
//put the params context second to match what section does. {.} matches the current context without parameters
// start with an empty context
partialContext = dust.makeBase(context.global);
partialContext.blocks = context.blocks;
if (context.stack && context.stack.tail){
// grab the stack(tail) off of the previous context if we have it
partialContext.stack = context.stack.tail;
}
if (params){
//put params on
partialContext = partialContext.push(params);
}
// templateName can be static (string) or dynamic (function)
// e.g. {>"static_template"/}
// {>"{dynamic_template}"/}
if (elem) {
partialContext.templateName = elem;
}
//reattach the head
partialContext = partialContext.push(context.stack.head);
var partialChunk;
if (typeof elem === "function") {
partialChunk = this.capture(elem, partialContext, function(name, chunk) {
dust.load(name, chunk, partialContext).end();
});
}
else {
partialChunk = dust.load(elem, this, partialContext);
}
return partialChunk;
};
Chunk.prototype.helper = function(name, context, bodies, params) {
var chunk = this;
// handle invalid helpers, similar to invalid filters
try {
if(dust.helpers[name]) {
return dust.helpers[name](chunk, context, bodies, params);
} else {
dust.log('Invalid helper [' + name + ']', WARN);
return chunk;
}
} catch (err) {
dust.log(err, ERROR);
return chunk;
}
};
Chunk.prototype.capture = function(body, context, callback) {
return this.map(function(chunk) {
var stub = new Stub(function(err, out) {
if (err) {
chunk.setError(err);
} else {
callback(out, chunk);
}
});
body(stub.head, context).end();
});
};
Chunk.prototype.setError = function(err) {
this.error = err;
this.root.flush();
return this;
};
function Tap(head, tail) {
this.head = head;
this.tail = tail;
}
Tap.prototype.push = function(tap) {
return new Tap(tap, this);
};
Tap.prototype.go = function(value) {
var tap = this;
while(tap) {
value = tap.head(value);
tap = tap.tail;
}
return value;
};
var HCHARS = new RegExp(/[&<>\"\']/),
AMP = /&/g,
LT = /</g,
GT = />/g,
QUOT = /\"/g,
SQUOT = /\'/g;
dust.escapeHtml = function(s) {
if (typeof s === "string") {
if (!HCHARS.test(s)) {
return s;
}
return s.replace(AMP,'&').replace(LT,'<').replace(GT,'>').replace(QUOT,'"').replace(SQUOT, ''');
}
return s;
};
var BS = /\\/g,
FS = /\//g,
CR = /\r/g,
LS = /\u2028/g,
PS = /\u2029/g,
NL = /\n/g,
LF = /\f/g,
SQ = /'/g,
DQ = /"/g,
TB = /\t/g;
dust.escapeJs = function(s) {
if (typeof s === "string") {
return s
.replace(BS, '\\\\')
.replace(FS, '\\/')
.replace(DQ, '\\"')
.replace(SQ, "\\'")
.replace(CR, '\\r')
.replace(LS, '\\u2028')
.replace(PS, '\\u2029')
.replace(NL, '\\n')
.replace(LF, '\\f')
.replace(TB, "\\t");
}
return s;
};
})(dust);
if (typeof exports !== "undefined") {
if (typeof process !== "undefined") {
require('./server')(dust);
}
module.exports = dust;
}
|
'use strict';
exports.__esModule = true;
exports['default'] = combineReducers;
var _createStore = require('./createStore');
var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = require('./utils/warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!(0, _isPlainObject2['default'])(inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
});
unexpectedKeys.forEach(function (key) {
unexpectedKeyCache[key] = true;
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
(0, _warning2['default'])('No reducer provided for key "' + key + '"');
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
if (process.env.NODE_ENV !== 'production') {
var unexpectedKeyCache = {};
}
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
return function combination() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (sanityError) {
throw sanityError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
if (warningMessage) {
(0, _warning2['default'])(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i];
var reducer = finalReducers[key];
var previousStateForKey = state[key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
} |
module.exports={title:"Google Messages",slug:"googlemessages",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Google Messages icon</title><path d="M.92 3.332c-.776 0-1.216.67-.692 1.383l2.537 4.403v7.86c0 2.013 1.467 3.69 3.459 3.69H20.31a3.75 3.75 0 003.69-3.69V7.043a3.723 3.723 0 00-3.668-3.71zm5.786 3.71H20.1c.587 0 1.153.357 1.153.923 0 .566-.566.922-1.153.922H6.706c-.587 0-1.153-.356-1.153-.922 0-.566.566-.923 1.153-.923zm0 3.69H20.1c.587 0 1.153.356 1.153.922 0 .566-.566.922-1.153.922H6.706c-.587 0-1.153-.356-1.153-.922 0-.566.566-.922 1.153-.922zm-.021 3.71h9.705c.587 0 1.153.356 1.153.922 0 .566-.566.923-1.153.923H6.685c-.587 0-1.153-.357-1.153-.923 0-.566.566-.922 1.153-.922Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://messages.google.com/",hex:"1A73E8"}; |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'format', 'fo', {
label: 'Skriftsnið',
panelTitle: 'Skriftsnið',
tag_address: 'Adressa',
tag_div: 'Vanligt (DIV)',
tag_h1: 'Yvirskrift 1',
tag_h2: 'Yvirskrift 2',
tag_h3: 'Yvirskrift 3',
tag_h4: 'Yvirskrift 4',
tag_h5: 'Yvirskrift 5',
tag_h6: 'Yvirskrift 6',
tag_p: 'Vanligt',
tag_pre: 'Sniðgivið'
});
|
/*! Responsive 1.0.1
* 2014 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary Responsive
* @description Responsive tables plug-in for DataTables
* @version 1.0.1
* @file dataTables.responsive.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2014 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
(function(window, document, undefined) {
var factory = function( $, DataTable ) {
"use strict";
/**
* Responsive is a plug-in for the DataTables library that makes use of
* DataTables' ability to change the visibility of columns, changing the
* visibility of columns so the displayed columns fit into the table container.
* The end result is that complex tables will be dynamically adjusted to fit
* into the viewport, be it on a desktop, tablet or mobile browser.
*
* Responsive for DataTables has two modes of operation, which can used
* individually or combined:
*
* * Class name based control - columns assigned class names that match the
* breakpoint logic can be shown / hidden as required for each breakpoint.
* * Automatic control - columns are automatically hidden when there is no
* room left to display them. Columns removed from the right.
*
* In additional to column visibility control, Responsive also has built into
* options to use DataTables' child row display to show / hide the information
* from the table that has been hidden. There are also two modes of operation
* for this child row display:
*
* * Inline - when the control element that the user can use to show / hide
* child rows is displayed inside the first column of the table.
* * Column - where a whole column is dedicated to be the show / hide control.
*
* Initialisation of Responsive is performed by:
*
* * Adding the class `responsive` or `dt-responsive` to the table. In this case
* Responsive will automatically be initialised with the default configuration
* options when the DataTable is created.
* * Using the `responsive` option in the DataTables configuration options. This
* can also be used to specify the configuration options, or simply set to
* `true` to use the defaults.
*
* @class
* @param {object} settings DataTables settings object for the host table
* @param {object} [opts] Configuration options
* @requires jQuery 1.7+
* @requires DataTables 1.10.1+
*
* @example
* $('#example').DataTable( {
* responsive: true
* } );
* } );
*/
var Responsive = function ( settings, opts ) {
// Sanity check that we are using DataTables 1.10 or newer
if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.1' ) ) {
throw 'DataTables Responsive requires DataTables 1.10.1 or newer';
}
else if ( settings.responsive ) {
return;
}
this.s = {
dt: new DataTable.Api( settings ),
columns: []
};
// details is an object, but for simplicity the user can give it as a string
if ( opts && typeof opts.details === 'string' ) {
opts.details = { type: opts.details };
}
this.c = $.extend( true, {}, Responsive.defaults, opts );
settings.responsive = this;
this._constructor();
};
Responsive.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constructor
*/
/**
* Initialise the Responsive instance
*
* @private
*/
_constructor: function ()
{
var that = this;
var dt = this.s.dt;
dt.settings()[0]._responsive = this;
// Use DataTables' private throttle function to avoid processor thrashing
$(window).on( 'resize.dtr orientationchange.dtr', dt.settings()[0].oApi._fnThrottle( function () {
that._resize();
} ) );
// Destroy event handler
dt.on( 'destroy.dtr', function () {
$(window).off( 'resize.dtr orientationchange.dtr' );
} );
// Reorder the breakpoints array here in case they have been added out
// of order
this.c.breakpoints.sort( function (a, b) {
return a.width < b.width ? 1 :
a.width > b.width ? -1 : 0;
} );
this._classLogic();
this._resizeAuto();
// First pass - draw the table for the current viewport size
this._resize();
// Details handler
var details = this.c.details;
if ( details.type ) {
that._detailsInit();
this._detailsVis();
dt.on( 'column-visibility.dtr', function () {
that._detailsVis();
} );
$(dt.table().node()).addClass( 'dtr-'+details.type );
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods
*/
/**
* Calculate the visibility for the columns in a table for a given
* breakpoint. The result is pre-determined based on the class logic if
* class names are used to control all columns, but the width of the table
* is also used if there are columns which are to be automatically shown
* and hidden.
*
* @param {string} breakpoint Breakpoint name to use for the calculation
* @return {array} Array of boolean values initiating the visibility of each
* column.
* @private
*/
_columnsVisiblity: function ( breakpoint )
{
var dt = this.s.dt;
var columns = this.s.columns;
var i, ien;
// Class logic - determine which columns are in this breakpoint based
// on the classes. If no class control (i.e. `auto`) then `-` is used
// to indicate this to the rest of the function
var display = $.map( columns, function ( col ) {
return col.auto && col.minWidth === null ?
false :
col.auto === true ?
'-' :
col.includeIn.indexOf( breakpoint ) !== -1;
} );
// Auto column control - first pass: how much width is taken by the
// ones that must be included from the non-auto columns
var requiredWidth = 0;
for ( i=0, ien=display.length ; i<ien ; i++ ) {
if ( display[i] === true ) {
requiredWidth += columns[i].minWidth;
}
}
// Second pass, use up any remaining width for other columns
var widthAvailable = dt.table().container().offsetWidth;
var usedWidth = widthAvailable - requiredWidth;
for ( i=0, ien=display.length ; i<ien ; i++ ) {
// Control column needs to always be included. This makes it sub-
// optimal in terms of using the available with, but to stop layout
// thrashing or overflow
if ( columns[i].control ) {
usedWidth -= columns[i].minWidth;
}
else if ( display[i] === '-' ) {
// Otherwise, remove the width
display[i] = usedWidth - columns[i].minWidth < 0 ?
false :
true;
// Continue counting down the width, so a smaller column to the
// left won't be shown
usedWidth -= columns[i].minWidth;
}
}
// Determine if the 'control' column should be shown (if there is one).
// This is the case when there is a hidden column (that is not the
// control column). The two loops look inefficient here, but they are
// trivial and will fly through. We need to know the outcome from the
// first , before the action in the second can be taken
var showControl = false;
for ( i=0, ien=columns.length ; i<ien ; i++ ) {
if ( ! columns[i].control && ! display[i] ) {
showControl = true;
break;
}
}
for ( i=0, ien=columns.length ; i<ien ; i++ ) {
if ( columns[i].control ) {
display[i] = showControl;
}
}
return display;
},
/**
* Create the internal `columns` array with information about the columns
* for the table. This includes determining which breakpoints the column
* will appear in, based upon class names in the column, which makes up the
* vast majority of this method.
*
* @private
*/
_classLogic: function ()
{
var that = this;
var calc = {};
var breakpoints = this.c.breakpoints;
var columns = this.s.dt.columns().eq(0).map( function (i) {
return {
className: this.column(i).header().className,
includeIn: [],
auto: false,
control: false
};
} );
// Simply add a breakpoint to `includeIn` array, ensuring that there are
// no duplicates
var add = function ( colIdx, name ) {
var includeIn = columns[ colIdx ].includeIn;
if ( includeIn.indexOf( name ) === -1 ) {
includeIn.push( name );
}
};
var column = function ( colIdx, name, operator, matched ) {
var size, i, ien;
if ( ! operator ) {
columns[ colIdx ].includeIn.push( name );
}
else if ( operator === 'max-' ) {
// Add this breakpoint and all smaller
size = that._find( name ).width;
for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
if ( breakpoints[i].width <= size ) {
add( colIdx, breakpoints[i].name );
}
}
}
else if ( operator === 'min-' ) {
// Add this breakpoint and all larger
size = that._find( name ).width;
for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
if ( breakpoints[i].width >= size ) {
add( colIdx, breakpoints[i].name );
}
}
}
else if ( operator === 'not-' ) {
// Add all but this breakpoint (xxx need extra information)
for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
if ( breakpoints[i].name.indexOf( matched ) === -1 ) {
add( colIdx, breakpoints[i].name );
}
}
}
};
// Loop over each column and determine if it has a responsive control
// class
columns.each( function ( col, i ) {
var classNames = col.className.split(' ');
var hasClass = false;
// Split the class name up so multiple rules can be applied if needed
for ( var k=0, ken=classNames.length ; k<ken ; k++ ) {
var className = $.trim( classNames[k] );
if ( className === 'all' ) {
// Include in all
hasClass = true;
col.includeIn = $.map( breakpoints, function (a) {
return a.name;
} );
return;
}
else if ( className === 'none' ) {
// Include in none (default) and no auto
hasClass = true;
return;
}
else if ( className === 'control' ) {
// Special column that is only visible, when one of the other
// columns is hidden. This is used for the details control
hasClass = true;
col.control = true;
return;
}
$.each( breakpoints, function ( j, breakpoint ) {
// Does this column have a class that matches this breakpoint?
var brokenPoint = breakpoint.name.split('-');
var re = new RegExp( '(min\\-|max\\-|not\\-)?('+brokenPoint[0]+')(\\-[_a-zA-Z0-9])?' );
var match = className.match( re );
if ( match ) {
hasClass = true;
if ( match[2] === brokenPoint[0] && match[3] === '-'+brokenPoint[1] ) {
// Class name matches breakpoint name fully
column( i, breakpoint.name, match[1], match[2]+match[3] );
}
else if ( match[2] === brokenPoint[0] && ! match[3] ) {
// Class name matched primary breakpoint name with no qualifier
column( i, breakpoint.name, match[1], match[2] );
}
}
} );
}
// If there was no control class, then automatic sizing is used
if ( ! hasClass ) {
col.auto = true;
}
} );
this.s.columns = columns;
},
/**
* Initialisation for the details handler
*
* @private
*/
_detailsInit: function ()
{
var that = this;
var dt = this.s.dt;
var details = this.c.details;
// The inline type always uses the first child as the target
if ( details.type === 'inline' ) {
details.target = 'td:first-child';
}
// type.target can be a string jQuery selector or a column index
var target = details.target;
var selector = typeof target === 'string' ? target : 'td';
// Click handler to show / hide the details rows when they are available
$( dt.table().body() ).on( 'click', selector, function (e) {
// If the table is not collapsed (i.e. there is no hidden columns)
// then take no action
if ( ! $(dt.table().node()).hasClass('collapsed' ) ) {
return;
}
// For column index, we determine if we should act or not in the
// handler - otherwise it is already okay
if ( typeof target === 'number' ) {
var targetIdx = target < 0 ?
dt.columns().eq(0).length + target :
target;
if ( dt.cell( this ).index().column !== targetIdx ) {
return;
}
}
// $().closest() includes itself in its check
var row = dt.row( $(this).closest('tr') );
if ( row.child.isShown() ) {
row.child( false );
$( row.node() ).removeClass( 'parent' );
}
else {
var info = that.c.details.renderer( dt, row[0] );
row.child( info, 'child' ).show();
$( row.node() ).addClass( 'parent' );
}
} );
},
/**
* Update the child rows in the table whenever the column visibility changes
*
* @private
*/
_detailsVis: function ()
{
var that = this;
var dt = this.s.dt;
var hiddenColumns = dt.columns(':hidden').indexes().flatten();
var haveHidden = true;
if ( hiddenColumns.length === 0 || ( hiddenColumns.length === 1 && this.s.columns[ hiddenColumns[0] ].control ) ) {
haveHidden = false;
}
if ( haveHidden ) {
// Got hidden columns
$( dt.table().node() ).addClass('collapsed');
// Show all existing child rows
dt.rows().eq(0).each( function (idx) {
var row = dt.row( idx );
if ( row.child() ) {
var info = that.c.details.renderer( dt, row[0] );
// The renderer can return false to have no child row
if ( info === false ) {
row.child.hide();
}
else {
row.child( info, 'child' ).show();
}
}
} );
}
else {
// No hidden columns
$( dt.table().node() ).removeClass('collapsed');
// Hide all existing child rows
dt.rows().eq(0).each( function (idx) {
dt.row( idx ).child.hide();
} );
}
},
/**
* Find a breakpoint object from a name
* @param {string} name Breakpoint name to find
* @return {object} Breakpoint description object
*/
_find: function ( name )
{
var breakpoints = this.c.breakpoints;
for ( var i=0, ien=breakpoints.length ; i<ien ; i++ ) {
if ( breakpoints[i].name === name ) {
return breakpoints[i];
}
}
},
/**
* Alter the table display for a resized viewport. This involves first
* determining what breakpoint the window currently is in, getting the
* column visibilities to apply and then setting them.
*
* @private
*/
_resize: function ()
{
var dt = this.s.dt;
var width = $(window).width();
var breakpoints = this.c.breakpoints;
var breakpoint = breakpoints[0].name;
// Determine what breakpoint we are currently at
for ( var i=breakpoints.length-1 ; i>=0 ; i-- ) {
if ( width <= breakpoints[i].width ) {
breakpoint = breakpoints[i].name;
break;
}
}
// Show the columns for that break point
var columns = this._columnsVisiblity( breakpoint );
dt.columns().eq(0).each( function ( colIdx, i ) {
dt.column( colIdx ).visible( columns[i] );
} );
},
/**
* Determine the width of each column in the table so the auto column hiding
* has that information to work with. This method is never going to be 100%
* perfect since column widths can change slightly per page, but without
* seriously compromising performance this is quite effective.
*
* @private
*/
_resizeAuto: function ()
{
var dt = this.s.dt;
var columns = this.s.columns;
// Are we allowed to do auto sizing?
if ( ! this.c.auto ) {
return;
}
// Are there any columns that actually need auto-sizing, or do they all
// have classes defined
if ( $.inArray( true, $.map( columns, function (c) { return c.auto; } ) ) === -1 ) {
return;
}
// Clone the table with the current data in it
var tableWidth = dt.table().node().offsetWidth;
var columnWidths = dt.columns;
var clonedTable = dt.table().node().cloneNode( false );
var clonedHeader = $( dt.table().header().cloneNode( false ) ).appendTo( clonedTable );
var clonedBody = $( dt.table().body().cloneNode( false ) ).appendTo( clonedTable );
// This is a bit slow, but we need to get a clone of each row that
// includes all columns. As such, try to do this as little as possible.
dt.rows( { page: 'current' } ).indexes().each( function ( idx ) {
var clone = dt.row( idx ).node().cloneNode( true );
if ( dt.columns( ':hidden' ).flatten().length ) {
$(clone).append( dt.cells( idx, ':hidden' ).nodes().to$().clone() );
}
$(clone).appendTo( clonedBody );
} );
var cells = dt.columns().header().to$().clone( false ).wrapAll('tr').appendTo( clonedHeader );
var inserted = $('<div/>')
.css( {
width: 1,
height: 1,
overflow: 'hidden'
} )
.append( clonedTable )
.insertBefore( dt.table().node() );
// The cloned header now contains the smallest that each column can be
dt.columns().eq(0).each( function ( idx ) {
columns[idx].minWidth = cells[ idx ].offsetWidth || 0;
} );
inserted.remove();
}
};
/**
* List of default breakpoints. Each item in the array is an object with two
* properties:
*
* * `name` - the breakpoint name.
* * `width` - the breakpoint width
*
* @name Responsive.breakpoints
* @static
*/
Responsive.breakpoints = [
{ name: 'desktop', width: Infinity },
{ name: 'tablet-l', width: 1024 },
{ name: 'tablet-p', width: 768 },
{ name: 'mobile-l', width: 480 },
{ name: 'mobile-p', width: 320 }
];
/**
* Responsive default settings for initialisation
*
* @namespace
* @name Responsive.defaults
* @static
*/
Responsive.defaults = {
/**
* List of breakpoints for the instance. Note that this means that each
* instance can have its own breakpoints. Additionally, the breakpoints
* cannot be changed once an instance has been creased.
*
* @type {Array}
* @default Takes the value of `Responsive.breakpoints`
*/
breakpoints: Responsive.breakpoints,
/**
* Enable / disable auto hiding calculations. It can help to increase
* performance slightly if you disable this option, but all columns would
* need to have breakpoint classes assigned to them
*
* @type {Boolean}
* @default `true`
*/
auto: true,
/**
* Details control. If given as a string value, the `type` property of the
* default object is set to that value, and the defaults used for the rest
* of the object - this is for ease of implementation.
*
* The object consists of the following properties:
*
* * `renderer` - function that is called for display of the child row data.
* The default function will show the data from the hidden columns
* * `target` - Used as the selector for what objects to attach the child
* open / close to
* * `type` - `false` to disable the details display, `inline` or `column`
* for the two control types
*
* @type {Object|string}
*/
details: {
renderer: function ( api, rowIdx ) {
var data = api.cells( rowIdx, ':hidden' ).eq(0).map( function ( cell ) {
var header = $( api.column( cell.column ).header() );
if ( header.hasClass( 'control' ) ) {
return '';
}
return '<li>'+
'<span class="dtr-title">'+
header.text()+':'+
'</span> '+
'<span class="dtr-data">'+
api.cell( cell ).data()+
'</span>'+
'</li>';
} ).toArray().join('');
return data ?
$('<ul/>').append( data ) :
false;
},
target: 0,
type: 'inline'
}
};
/*
* API
*/
var Api = $.fn.dataTable.Api;
// Doesn't do anything - work around for a bug in DT... Not documented
Api.register( 'responsive()', function () {
return this;
} );
Api.register( 'responsive.recalc()', function ( rowIdx, intParse, virtual ) {
this.iterator( 'table', function ( ctx ) {
if ( ctx._responsive ) {
ctx._responsive._resizeAuto();
ctx._responsive._resize();
}
} );
} );
/**
* Version information
*
* @name Responsive.version
* @static
*/
Responsive.version = '1.0.1';
$.fn.dataTable.Responsive = Responsive;
$.fn.DataTable.Responsive = Responsive;
// Attach a listener to the document which listens for DataTables initialisation
// events so we can automatically initialise
$(document).on( 'init.dt.dtr', function (e, settings, json) {
if ( $(settings.nTable).hasClass( 'responsive' ) ||
$(settings.nTable).hasClass( 'dt-responsive' ) ||
settings.oInit.responsive
) {
var init = settings.oInit.responsive;
if ( init !== false ) {
new Responsive( settings, $.isPlainObject( init ) ? init : {} );
}
}
} );
return Responsive;
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery && !jQuery.fn.dataTable.Responsive ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
|
x = 5, b = require('beep');
console.log(b.x * 3);
console.log(b.f(5));
|
//# sourceMappingURL=phone-be.min.js.map |
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
"use strict";
module.exports = function(Promise, PromiseArray) {
var util = require("./util.js");
var async = require("./async.js");
var errors = require("./errors.js");
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
Promise.prototype.progressed = function Promise$progressed(handler) {
return this._then(void 0, void 0, handler, void 0, void 0);
};
Promise.prototype._progress = function Promise$_progress(progressValue) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._progressUnchecked(progressValue);
};
Promise.prototype._progressHandlerAt =
function Promise$_progressHandlerAt(index) {
return index === 0
? this._progressHandler0
: this[(index << 2) + index - 5 + 2];
};
Promise.prototype._doProgressWith =
function Promise$_doProgressWith(progression) {
var progressValue = progression.value;
var handler = progression.handler;
var promise = progression.promise;
var receiver = progression.receiver;
var ret = tryCatch1(handler, receiver, progressValue);
if (ret === errorObj) {
if (ret.e != null &&
ret.e.name !== "StopProgressPropagation") {
var trace = errors.canAttach(ret.e)
? ret.e : new Error(ret.e + "");
promise._attachExtraTrace(trace);
promise._progress(ret.e);
}
} else if (ret instanceof Promise) {
ret._then(promise._progress, null, null, promise, void 0);
} else {
promise._progress(ret);
}
};
Promise.prototype._progressUnchecked =
function Promise$_progressUnchecked(progressValue) {
if (!this.isPending()) return;
var len = this._length();
var progress = this._progress;
for (var i = 0; i < len; i++) {
var handler = this._progressHandlerAt(i);
var promise = this._promiseAt(i);
if (!(promise instanceof Promise)) {
var receiver = this._receiverAt(i);
if (typeof handler === "function") {
handler.call(receiver, progressValue, promise);
} else if (receiver instanceof Promise && receiver._isProxied()) {
receiver._progressUnchecked(progressValue);
} else if (receiver instanceof PromiseArray) {
receiver._promiseProgressed(progressValue, promise);
}
continue;
}
if (typeof handler === "function") {
async.invoke(this._doProgressWith, this, {
handler: handler,
promise: promise,
receiver: this._receiverAt(i),
value: progressValue
});
} else {
async.invoke(progress, promise, progressValue);
}
}
};
};
|
// Ramda v0.16.0
// https://github.com/ramda/ramda
// (c) 2013-2015 Scott Sauyet, Michael Hurley, and David Chambers
// Ramda may be freely distributed under the MIT license.
;(function() {
'use strict';
/**
* A special placeholder value used to specify "gaps" within curried functions,
* allowing partial application of any combination of arguments,
* regardless of their positions.
*
* If `g` is a curried ternary function and `_` is `R.__`, the following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2, _)(1, 3)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @constant
* @memberOf R
* @category Function
* @example
*
* var greet = R.replace('{name}', R.__, 'Hello, {name}!');
* greet('Alice'); //=> 'Hello, Alice!'
*/
var __ = { '@@functional/placeholder': true };
// jshint unused:vars
var _arity = function _arity(n, fn) {
// jshint unused:vars
switch (n) {
case 0:
return function () {
return fn.apply(this, arguments);
};
case 1:
return function (a0) {
return fn.apply(this, arguments);
};
case 2:
return function (a0, a1) {
return fn.apply(this, arguments);
};
case 3:
return function (a0, a1, a2) {
return fn.apply(this, arguments);
};
case 4:
return function (a0, a1, a2, a3) {
return fn.apply(this, arguments);
};
case 5:
return function (a0, a1, a2, a3, a4) {
return fn.apply(this, arguments);
};
case 6:
return function (a0, a1, a2, a3, a4, a5) {
return fn.apply(this, arguments);
};
case 7:
return function (a0, a1, a2, a3, a4, a5, a6) {
return fn.apply(this, arguments);
};
case 8:
return function (a0, a1, a2, a3, a4, a5, a6, a7) {
return fn.apply(this, arguments);
};
case 9:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
return fn.apply(this, arguments);
};
case 10:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
return fn.apply(this, arguments);
};
default:
throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
}
};
var _cloneRegExp = function _cloneRegExp(pattern) {
return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : ''));
};
var _complement = function _complement(f) {
return function () {
return !f.apply(this, arguments);
};
};
/**
* Private `concat` function to merge two array-like objects.
*
* @private
* @param {Array|Arguments} [set1=[]] An array-like object.
* @param {Array|Arguments} [set2=[]] An array-like object.
* @return {Array} A new, merged array.
* @example
*
* _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
*/
var _concat = function _concat(set1, set2) {
set1 = set1 || [];
set2 = set2 || [];
var idx;
var len1 = set1.length;
var len2 = set2.length;
var result = [];
idx = 0;
while (idx < len1) {
result[result.length] = set1[idx];
idx += 1;
}
idx = 0;
while (idx < len2) {
result[result.length] = set2[idx];
idx += 1;
}
return result;
};
var _containsWith = function _containsWith(pred, x, list) {
var idx = 0, len = list.length;
while (idx < len) {
if (pred(x, list[idx])) {
return true;
}
idx += 1;
}
return false;
};
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry1 = function _curry1(fn) {
return function f1(a) {
if (arguments.length === 0) {
return f1;
} else if (a != null && a['@@functional/placeholder'] === true) {
return f1;
} else {
return fn.apply(this, arguments);
}
};
};
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry2 = function _curry2(fn) {
return function f2(a, b) {
var n = arguments.length;
if (n === 0) {
return f2;
} else if (n === 1 && a != null && a['@@functional/placeholder'] === true) {
return f2;
} else if (n === 1) {
return _curry1(function (b) {
return fn(a, b);
});
} else if (n === 2 && a != null && a['@@functional/placeholder'] === true && b != null && b['@@functional/placeholder'] === true) {
return f2;
} else if (n === 2 && a != null && a['@@functional/placeholder'] === true) {
return _curry1(function (a) {
return fn(a, b);
});
} else if (n === 2 && b != null && b['@@functional/placeholder'] === true) {
return _curry1(function (b) {
return fn(a, b);
});
} else {
return fn(a, b);
}
};
};
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry3 = function _curry3(fn) {
return function f3(a, b, c) {
var n = arguments.length;
if (n === 0) {
return f3;
} else if (n === 1 && a != null && a['@@functional/placeholder'] === true) {
return f3;
} else if (n === 1) {
return _curry2(function (b, c) {
return fn(a, b, c);
});
} else if (n === 2 && a != null && a['@@functional/placeholder'] === true && b != null && b['@@functional/placeholder'] === true) {
return f3;
} else if (n === 2 && a != null && a['@@functional/placeholder'] === true) {
return _curry2(function (a, c) {
return fn(a, b, c);
});
} else if (n === 2 && b != null && b['@@functional/placeholder'] === true) {
return _curry2(function (b, c) {
return fn(a, b, c);
});
} else if (n === 2) {
return _curry1(function (c) {
return fn(a, b, c);
});
} else if (n === 3 && a != null && a['@@functional/placeholder'] === true && b != null && b['@@functional/placeholder'] === true && c != null && c['@@functional/placeholder'] === true) {
return f3;
} else if (n === 3 && a != null && a['@@functional/placeholder'] === true && b != null && b['@@functional/placeholder'] === true) {
return _curry2(function (a, b) {
return fn(a, b, c);
});
} else if (n === 3 && a != null && a['@@functional/placeholder'] === true && c != null && c['@@functional/placeholder'] === true) {
return _curry2(function (a, c) {
return fn(a, b, c);
});
} else if (n === 3 && b != null && b['@@functional/placeholder'] === true && c != null && c['@@functional/placeholder'] === true) {
return _curry2(function (b, c) {
return fn(a, b, c);
});
} else if (n === 3 && a != null && a['@@functional/placeholder'] === true) {
return _curry1(function (a) {
return fn(a, b, c);
});
} else if (n === 3 && b != null && b['@@functional/placeholder'] === true) {
return _curry1(function (b) {
return fn(a, b, c);
});
} else if (n === 3 && c != null && c['@@functional/placeholder'] === true) {
return _curry1(function (c) {
return fn(a, b, c);
});
} else {
return fn(a, b, c);
}
};
};
/**
* Internal curryN function.
*
* @private
* @category Function
* @param {Number} length The arity of the curried function.
* @return {array} An array of arguments received thus far.
* @param {Function} fn The function to curry.
*/
var _curryN = function _curryN(length, received, fn) {
return function () {
var combined = [];
var argsIdx = 0;
var left = length;
var combinedIdx = 0;
while (combinedIdx < received.length || argsIdx < arguments.length) {
var result;
if (combinedIdx < received.length && (received[combinedIdx] == null || received[combinedIdx]['@@functional/placeholder'] !== true || argsIdx >= arguments.length)) {
result = received[combinedIdx];
} else {
result = arguments[argsIdx];
argsIdx += 1;
}
combined[combinedIdx] = result;
if (result == null || result['@@functional/placeholder'] !== true) {
left -= 1;
}
combinedIdx += 1;
}
return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn));
};
};
var _filter = function _filter(fn, list) {
var idx = 0, len = list.length, result = [];
while (idx < len) {
if (fn(list[idx])) {
result[result.length] = list[idx];
}
idx += 1;
}
return result;
};
var _forceReduced = function _forceReduced(x) {
return {
'@@transducer/value': x,
'@@transducer/reduced': true
};
};
/**
* @private
* @param {Function} fn The strategy for extracting function names from an object
* @return {Function} A function that takes an object and returns an array of function names.
*/
var _functionsWith = function _functionsWith(fn) {
return function (obj) {
return _filter(function (key) {
return typeof obj[key] === 'function';
}, fn(obj));
};
};
var _has = function _has(prop, obj) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
var _identity = function _identity(x) {
return x;
};
/**
* Tests whether or not an object is an array.
*
* @private
* @param {*} val The object to test.
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* _isArray([]); //=> true
* _isArray(null); //=> false
* _isArray({}); //=> false
*/
var _isArray = Array.isArray || function _isArray(val) {
return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';
};
/**
* Determine if the passed argument is an integer.
*
* @private
* @param {*} n
* @category Type
* @return {Boolean}
*/
var _isInteger = Number.isInteger || function _isInteger(n) {
return n << 0 === n;
};
var _isNumber = function _isNumber(x) {
return Object.prototype.toString.call(x) === '[object Number]';
};
var _isString = function _isString(x) {
return Object.prototype.toString.call(x) === '[object String]';
};
var _isTransformer = function _isTransformer(obj) {
return typeof obj['@@transducer/step'] === 'function';
};
var _map = function _map(fn, list) {
var idx = 0, len = list.length, result = Array(len);
while (idx < len) {
result[idx] = fn(list[idx]);
idx += 1;
}
return result;
};
var _pipe = function _pipe(f, g) {
return function () {
return g.call(this, f.apply(this, arguments));
};
};
var _pipeP = function _pipeP(f, g) {
return function () {
var ctx = this;
return f.apply(ctx, arguments).then(function (x) {
return g.call(ctx, x);
});
};
};
var _quote = function _quote(s) {
return '"' + s.replace(/"/g, '\\"') + '"';
};
var _reduced = function _reduced(x) {
return x && x['@@transducer/reduced'] ? x : {
'@@transducer/value': x,
'@@transducer/reduced': true
};
};
/**
* An optimized, private array `slice` implementation.
*
* @private
* @param {Arguments|Array} args The array or arguments object to consider.
* @param {Number} [from=0] The array index to slice from, inclusive.
* @param {Number} [to=args.length] The array index to slice to, exclusive.
* @return {Array} A new, sliced array.
* @example
*
* _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
*
* var firstThreeArgs = function(a, b, c, d) {
* return _slice(arguments, 0, 3);
* };
* firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
*/
var _slice = function _slice(args, from, to) {
switch (arguments.length) {
case 1:
return _slice(args, 0, args.length);
case 2:
return _slice(args, from, args.length);
default:
var list = [];
var idx = 0;
var len = Math.max(0, Math.min(args.length, to) - from);
while (idx < len) {
list[idx] = args[from + idx];
idx += 1;
}
return list;
}
};
/**
* Polyfill from <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString>.
*/
var _toISOString = function () {
var pad = function pad(n) {
return (n < 10 ? '0' : '') + n;
};
return typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) {
return d.toISOString();
} : function _toISOString(d) {
return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
};
}();
var _xdropRepeatsWith = function () {
function XDropRepeatsWith(pred, xf) {
this.xf = xf;
this.pred = pred;
this.lastValue = undefined;
this.seenFirstValue = false;
}
XDropRepeatsWith.prototype['@@transducer/init'] = function () {
return this.xf['@@transducer/init']();
};
XDropRepeatsWith.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](result);
};
XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) {
var sameAsLast = false;
if (!this.seenFirstValue) {
this.seenFirstValue = true;
} else if (this.pred(this.lastValue, input)) {
sameAsLast = true;
}
this.lastValue = input;
return sameAsLast ? result : this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdropRepeatsWith(pred, xf) {
return new XDropRepeatsWith(pred, xf);
});
}();
var _xfBase = {
init: function () {
return this.xf['@@transducer/init']();
},
result: function (result) {
return this.xf['@@transducer/result'](result);
}
};
var _xfilter = function () {
function XFilter(f, xf) {
this.xf = xf;
this.f = f;
}
XFilter.prototype['@@transducer/init'] = _xfBase.init;
XFilter.prototype['@@transducer/result'] = _xfBase.result;
XFilter.prototype['@@transducer/step'] = function (result, input) {
return this.f(input) ? this.xf['@@transducer/step'](result, input) : result;
};
return _curry2(function _xfilter(f, xf) {
return new XFilter(f, xf);
});
}();
var _xfind = function () {
function XFind(f, xf) {
this.xf = xf;
this.f = f;
this.found = false;
}
XFind.prototype['@@transducer/init'] = _xfBase.init;
XFind.prototype['@@transducer/result'] = function (result) {
if (!this.found) {
result = this.xf['@@transducer/step'](result, void 0);
}
return this.xf['@@transducer/result'](result);
};
XFind.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.found = true;
result = _reduced(this.xf['@@transducer/step'](result, input));
}
return result;
};
return _curry2(function _xfind(f, xf) {
return new XFind(f, xf);
});
}();
var _xfindIndex = function () {
function XFindIndex(f, xf) {
this.xf = xf;
this.f = f;
this.idx = -1;
this.found = false;
}
XFindIndex.prototype['@@transducer/init'] = _xfBase.init;
XFindIndex.prototype['@@transducer/result'] = function (result) {
if (!this.found) {
result = this.xf['@@transducer/step'](result, -1);
}
return this.xf['@@transducer/result'](result);
};
XFindIndex.prototype['@@transducer/step'] = function (result, input) {
this.idx += 1;
if (this.f(input)) {
this.found = true;
result = _reduced(this.xf['@@transducer/step'](result, this.idx));
}
return result;
};
return _curry2(function _xfindIndex(f, xf) {
return new XFindIndex(f, xf);
});
}();
var _xfindLast = function () {
function XFindLast(f, xf) {
this.xf = xf;
this.f = f;
}
XFindLast.prototype['@@transducer/init'] = _xfBase.init;
XFindLast.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last));
};
XFindLast.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.last = input;
}
return result;
};
return _curry2(function _xfindLast(f, xf) {
return new XFindLast(f, xf);
});
}();
var _xfindLastIndex = function () {
function XFindLastIndex(f, xf) {
this.xf = xf;
this.f = f;
this.idx = -1;
this.lastIdx = -1;
}
XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init;
XFindLastIndex.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx));
};
XFindLastIndex.prototype['@@transducer/step'] = function (result, input) {
this.idx += 1;
if (this.f(input)) {
this.lastIdx = this.idx;
}
return result;
};
return _curry2(function _xfindLastIndex(f, xf) {
return new XFindLastIndex(f, xf);
});
}();
var _xmap = function () {
function XMap(f, xf) {
this.xf = xf;
this.f = f;
}
XMap.prototype['@@transducer/init'] = _xfBase.init;
XMap.prototype['@@transducer/result'] = _xfBase.result;
XMap.prototype['@@transducer/step'] = function (result, input) {
return this.xf['@@transducer/step'](result, this.f(input));
};
return _curry2(function _xmap(f, xf) {
return new XMap(f, xf);
});
}();
var _xtake = function () {
function XTake(n, xf) {
this.xf = xf;
this.n = n;
}
XTake.prototype['@@transducer/init'] = _xfBase.init;
XTake.prototype['@@transducer/result'] = _xfBase.result;
XTake.prototype['@@transducer/step'] = function (result, input) {
if (this.n === 0) {
return _reduced(result);
} else {
this.n -= 1;
return this.xf['@@transducer/step'](result, input);
}
};
return _curry2(function _xtake(n, xf) {
return new XTake(n, xf);
});
}();
var _xtakeWhile = function () {
function XTakeWhile(f, xf) {
this.xf = xf;
this.f = f;
}
XTakeWhile.prototype['@@transducer/init'] = _xfBase.init;
XTakeWhile.prototype['@@transducer/result'] = _xfBase.result;
XTakeWhile.prototype['@@transducer/step'] = function (result, input) {
return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result);
};
return _curry2(function _xtakeWhile(f, xf) {
return new XTakeWhile(f, xf);
});
}();
var _xwrap = function () {
function XWrap(fn) {
this.f = fn;
}
XWrap.prototype['@@transducer/init'] = function () {
throw new Error('init not implemented on XWrap');
};
XWrap.prototype['@@transducer/result'] = function (acc) {
return acc;
};
XWrap.prototype['@@transducer/step'] = function (acc, x) {
return this.f(acc, x);
};
return function _xwrap(fn) {
return new XWrap(fn);
};
}();
/**
* Adds two numbers. Equivalent to `a + b` but curried.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a
* @param {Number} b
* @return {Number}
* @see R.subtract
* @example
*
* R.add(2, 3); //=> 5
* R.add(7)(10); //=> 17
*/
var add = _curry2(function add(a, b) {
return a + b;
});
/**
* Applies a function to the value at the given index of an array,
* returning a new copy of the array with the element at the given
* index replaced with the result of the function application.
* @see R.update
*
* @func
* @memberOf R
* @category List
* @sig (a -> a) -> Number -> [a] -> [a]
* @param {Function} fn The function to apply.
* @param {Number} idx The index.
* @param {Array|Arguments} list An array-like object whose value
* at the supplied index will be replaced.
* @return {Array} A copy of the supplied array-like object with
* the element at index `idx` replaced with the value
* returned by applying `fn` to the existing element.
* @example
*
* R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2]
* R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2]
*/
var adjust = _curry3(function adjust(fn, idx, list) {
if (idx >= list.length || idx < -list.length) {
return list;
}
var start = idx < 0 ? list.length : 0;
var _idx = start + idx;
var _list = _concat(list);
_list[_idx] = fn(list[_idx]);
return _list;
});
/**
* Returns a function that always returns the given value. Note that for
* non-primitives the value returned is a reference to the original value.
*
* This function is known as `const`, `constant`, or `K` (for K combinator)
* in other languages and libraries.
*
* @func
* @memberOf R
* @category Function
* @sig a -> (* -> a)
* @param {*} val The value to wrap in a function
* @return {Function} A Function :: * -> val.
* @example
*
* var t = R.always('Tee');
* t(); //=> 'Tee'
*/
var always = _curry1(function always(val) {
return function () {
return val;
};
});
/**
* Returns a new list, composed of n-tuples of consecutive elements
* If `n` is greater than the length of the list, an empty list is returned.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [[a]]
* @param {Number} n The size of the tuples to create
* @param {Array} list The list to split into `n`-tuples
* @return {Array} The new list.
* @example
*
* R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
* R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
* R.aperture(7, [1, 2, 3, 4, 5]); //=> []
*/
var aperture = _curry2(function aperture(n, list) {
var idx = 0;
var limit = list.length - (n - 1);
var acc = new Array(limit >= 0 ? limit : 0);
while (idx < limit) {
acc[idx] = _slice(list, idx, idx + n);
idx += 1;
}
return acc;
});
/**
* Returns a new list containing the contents of the given list, followed by the given
* element.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> [a]
* @param {*} el The element to add to the end of the new list.
* @param {Array} list The list whose contents will be added to the beginning of the output
* list.
* @return {Array} A new list containing the contents of the old list followed by `el`.
* @see R.prepend
* @example
*
* R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
* R.append('tests', []); //=> ['tests']
* R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
*/
var append = _curry2(function append(el, list) {
return _concat(list, [el]);
});
/**
* Applies function `fn` to the argument list `args`. This is useful for
* creating a fixed-arity function from a variadic function. `fn` should
* be a bound function if context is significant.
*
* @func
* @memberOf R
* @category Function
* @sig (*... -> a) -> [*] -> a
* @param {Function} fn
* @param {Array} args
* @return {*}
* @see R.call, R.unapply
* @example
*
* var nums = [1, 2, 3, -99, 42, 6, 7];
* R.apply(Math.max, nums); //=> 42
*/
var apply = _curry2(function apply(fn, args) {
return fn.apply(this, args);
});
/**
* Makes a shallow clone of an object, setting or overriding the specified
* property with the given value. Note that this copies and flattens
* prototype properties onto the new object as well. All non-primitive
* properties are copied by reference.
*
* @func
* @memberOf R
* @category Object
* @sig String -> a -> {k: v} -> {k: v}
* @param {String} prop the property name to set
* @param {*} val the new value
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original except for the specified property.
* @see R.dissoc
* @example
*
* R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
*/
var assoc = _curry3(function assoc(prop, val, obj) {
var result = {};
for (var p in obj) {
result[p] = obj[p];
}
result[prop] = val;
return result;
});
/**
* Makes a shallow clone of an object, setting or overriding the nodes
* required to create the given path, and placing the specific value at the
* tail end of that path. Note that this copies and flattens prototype
* properties onto the new object as well. All non-primitive properties
* are copied by reference.
*
* @func
* @memberOf R
* @category Object
* @sig [String] -> a -> {k: v} -> {k: v}
* @param {Array} path the path to set
* @param {*} val the new value
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original except along the specified path.
* @see R.dissocPath
* @example
*
* R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
*/
var assocPath = _curry3(function assocPath(path, val, obj) {
switch (path.length) {
case 0:
return obj;
case 1:
return assoc(path[0], val, obj);
default:
return assoc(path[0], assocPath(_slice(path, 1), val, Object(obj[path[0]])), obj);
}
});
/**
* Creates a function that is bound to a context.
* Note: `R.bind` does not provide the additional argument-binding capabilities of
* [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
*
* @func
* @memberOf R
* @category Function
* @category Object
* @see R.partial
* @sig (* -> *) -> {*} -> (* -> *)
* @param {Function} fn The function to bind to context
* @param {Object} thisObj The context to bind `fn` to
* @return {Function} A function that will execute in the context of `thisObj`.
*/
var bind = _curry2(function bind(fn, thisObj) {
return _arity(fn.length, function () {
return fn.apply(thisObj, arguments);
});
});
/**
* A function wrapping calls to the two functions in an `&&` operation, returning the result of the first
* function if it is false-y and the result of the second function otherwise. Note that this is
* short-circuited, meaning that the second function will not be invoked if the first returns a false-y
* value.
*
* @func
* @memberOf R
* @category Logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together.
* @see R.and
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.both(gt10, even);
* f(100); //=> true
* f(101); //=> false
*/
var both = _curry2(function both(f, g) {
return function _both() {
return f.apply(this, arguments) && g.apply(this, arguments);
};
});
/**
* Makes a comparator function out of a function that reports whether the first element is less than the second.
*
* @func
* @memberOf R
* @category Function
* @sig (a, b -> Boolean) -> (a, b -> Number)
* @param {Function} pred A predicate function of arity two.
* @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`.
* @example
*
* var cmp = R.comparator(function(a, b) {
* return a.age < b.age;
* });
* var people = [
* // ...
* ];
* R.sort(cmp, people);
*/
var comparator = _curry1(function comparator(pred) {
return function (a, b) {
return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
};
});
/**
* Takes a function `f` and returns a function `g` such that:
*
* - applying `g` to zero or more arguments will give __true__ if applying
* the same arguments to `f` gives a logical __false__ value; and
*
* - applying `g` to zero or more arguments will give __false__ if applying
* the same arguments to `f` gives a logical __true__ value.
*
* @func
* @memberOf R
* @category Logic
* @sig (*... -> *) -> (*... -> Boolean)
* @param {Function} f
* @return {Function}
* @see R.not
* @example
*
* var isEven = function(n) { return n % 2 === 0; };
* var isOdd = R.complement(isEven);
* isOdd(21); //=> true
* isOdd(42); //=> false
*/
var complement = _curry1(_complement);
/**
* Returns a function, `fn`, which encapsulates if/else-if/else logic.
* `R.cond` takes a list of [predicate, transform] pairs. All of the
* arguments to `fn` are applied to each of the predicates in turn
* until one returns a "truthy" value, at which point `fn` returns the
* result of applying its arguments to the corresponding transformer.
* If none of the predicates matches, `fn` returns undefined.
*
* @func
* @memberOf R
* @category Logic
* @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
* @param {Array} pairs
* @return {Function}
* @example
*
* var fn = R.cond([
* [R.equals(0), R.always('water freezes at 0°C')],
* [R.equals(100), R.always('water boils at 100°C')],
* [R.T, function(temp) { return 'nothing special happens at ' + temp + '°C'; }]
* ]);
* fn(0); //=> 'water freezes at 0°C'
* fn(50); //=> 'nothing special happens at 50°C'
* fn(100); //=> 'water boils at 100°C'
*/
var cond = _curry1(function cond(pairs) {
return function () {
var idx = 0;
while (idx < pairs.length) {
if (pairs[idx][0].apply(this, arguments)) {
return pairs[idx][1].apply(this, arguments);
}
idx += 1;
}
};
});
/**
* Returns `true` if the `x` is found in the `list`, using `pred` as an
* equality predicate for `x`.
*
* @func
* @memberOf R
* @category List
* @sig (a, a -> Boolean) -> a -> [a] -> Boolean
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {*} x The item to find
* @param {Array} list The list to iterate over
* @return {Boolean} `true` if `x` is in `list`, else `false`.
* @example
*
* var xs = [{x: 12}, {x: 11}, {x: 10}];
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false
*/
var containsWith = _curry3(_containsWith);
/**
* Counts the elements of a list according to how many match each value
* of a key generated by the supplied function. Returns an object
* mapping the keys produced by `fn` to the number of occurrences in
* the list. Note that all keys are coerced to strings because of how
* JavaScript objects work.
*
* @func
* @memberOf R
* @category Relation
* @sig (a -> String) -> [a] -> {*}
* @param {Function} fn The function used to map values to keys.
* @param {Array} list The list to count elements from.
* @return {Object} An object mapping keys to number of occurrences in the list.
* @example
*
* var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
* var letters = R.split('', 'abcABCaaaBBc');
* R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
* R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
*/
var countBy = _curry2(function countBy(fn, list) {
var counts = {};
var len = list.length;
var idx = 0;
while (idx < len) {
var key = fn(list[idx]);
counts[key] = (_has(key, counts) ? counts[key] : 0) + 1;
idx += 1;
}
return counts;
});
/**
* Creates an object containing a single key:value pair.
*
* @func
* @memberOf R
* @category Object
* @sig String -> a -> {String:a}
* @param {String} key
* @param {*} val
* @return {Object}
* @example
*
* var matchPhrases = R.compose(
* R.createMapEntry('must'),
* R.map(R.createMapEntry('match_phrase'))
* );
* matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}
*/
var createMapEntry = _curry2(function createMapEntry(key, val) {
var obj = {};
obj[key] = val;
return obj;
});
/**
* Returns a curried equivalent of the provided function, with the
* specified arity. The curried function has two unusual capabilities.
* First, its arguments needn't be provided one at a time. If `g` is
* `R.curryN(3, f)`, the following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value `R.__` may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is `R.__`,
* the following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curry
* @example
*
* var addFourNumbers = function() {
* return R.sum([].slice.call(arguments, 0, 4));
* };
*
* var curriedAddFourNumbers = R.curryN(4, addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4); //=> 10
*/
var curryN = _curry2(function curryN(length, fn) {
if (length === 1) {
return _curry1(fn);
}
return _arity(length, _curryN(length, [], fn));
});
/**
* Decrements its argument.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @see R.inc
* @example
*
* R.dec(42); //=> 41
*/
var dec = add(-1);
/**
* Returns the second argument if it is not null or undefined. If it is null
* or undefined, the first (default) argument is returned.
*
* @func
* @memberOf R
* @category Logic
* @sig a -> b -> a | b
* @param {a} val The default value.
* @param {b} val The value to return if it is not null or undefined
* @return {*} The the second value or the default value
* @example
*
* var defaultTo42 = defaultTo(42);
*
* defaultTo42(null); //=> 42
* defaultTo42(undefined); //=> 42
* defaultTo42('Ramda'); //=> 'Ramda'
*/
var defaultTo = _curry2(function defaultTo(d, v) {
return v == null ? d : v;
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
* Duplication is determined according to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category Relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.difference
* @return {Array} The elements in `list1` that are not in `list2`.
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}, {a: 3}];
* var l2 = [{a: 3}, {a: 4}];
* R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
*/
var differenceWith = _curry3(function differenceWith(pred, first, second) {
var out = [];
var idx = 0;
var firstLen = first.length;
var containsPred = containsWith(pred);
while (idx < firstLen) {
if (!containsPred(first[idx], second) && !containsPred(first[idx], out)) {
out[out.length] = first[idx];
}
idx += 1;
}
return out;
});
/**
* Returns a new object that does not contain a `prop` property.
*
* @func
* @memberOf R
* @category Object
* @sig String -> {k: v} -> {k: v}
* @param {String} prop the name of the property to dissociate
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original but without the specified property
* @see R.assoc
* @example
*
* R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
*/
var dissoc = _curry2(function dissoc(prop, obj) {
var result = {};
for (var p in obj) {
if (p !== prop) {
result[p] = obj[p];
}
}
return result;
});
/**
* Makes a shallow clone of an object, omitting the property at the
* given path. Note that this copies and flattens prototype properties
* onto the new object as well. All non-primitive properties are copied
* by reference.
*
* @func
* @memberOf R
* @category Object
* @sig [String] -> {k: v} -> {k: v}
* @param {Array} path the path to set
* @param {Object} obj the object to clone
* @return {Object} a new object without the property at path
* @see R.assocPath
* @example
*
* R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
*/
var dissocPath = _curry2(function dissocPath(path, obj) {
switch (path.length) {
case 0:
return obj;
case 1:
return dissoc(path[0], obj);
default:
var head = path[0];
var tail = _slice(path, 1);
return obj[head] == null ? obj : assoc(head, dissocPath(tail, obj[head]), obj);
}
});
/**
* Divides two numbers. Equivalent to `a / b`.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a / b`.
* @see R.multiply
* @example
*
* R.divide(71, 100); //=> 0.71
*
* var half = R.divide(R.__, 2);
* half(42); //=> 21
*
* var reciprocal = R.divide(1);
* reciprocal(4); //=> 0.25
*/
var divide = _curry2(function divide(a, b) {
return a / b;
});
/**
* Returns a new list containing all but last the`n` elements of a given list,
* passing each value from the right to the supplied predicate function, skipping
* elements while the predicate function returns `true`. The predicate function
* is passed one argument: (value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.takeLastWhile
* @example
*
* var lteThree = function(x) {
* return x <= 3;
* };
*
* R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2]
*/
var dropLastWhile = _curry2(function dropLastWhile(pred, list) {
var idx = list.length - 1;
while (idx >= 0 && pred(list[idx])) {
idx -= 1;
}
return _slice(list, 0, idx + 1);
});
/**
* A function wrapping calls to the two functions in an `||` operation, returning the result of the first
* function if it is truth-y and the result of the second function otherwise. Note that this is
* short-circuited, meaning that the second function will not be invoked if the first returns a truth-y
* value.
*
* @func
* @memberOf R
* @category Logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
* @see R.or
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.either(gt10, even);
* f(101); //=> true
* f(8); //=> true
*/
var either = _curry2(function either(f, g) {
return function _either() {
return f.apply(this, arguments) || g.apply(this, arguments);
};
});
/**
* Returns the empty value of its argument's type. Ramda defines the empty
* value of Array (`[]`), Object (`{}`), and String (`''`). Other types are
* supported if they define `<Type>.empty` and/or `<Type>.prototype.empty`.
*
* @func
* @memberOf R
* @category Function
* @sig a -> a
* @param {*} x
* @return {*}
* @example
*
* R.empty(Just(42)); //=> Nothing()
* R.empty([1, 2, 3]); //=> []
* R.empty('unicorns'); //=> ''
* R.empty({x: 1, y: 2}); //=> {}
*/
var empty = _curry1(function empty(x) {
if (x != null && typeof x.empty === 'function') {
return x.empty();
} else if (x != null && typeof x.constructor != null && typeof x.constructor.empty === 'function') {
return x.constructor.empty();
} else {
switch (Object.prototype.toString.call(x)) {
case '[object Array]':
return [];
case '[object Object]':
return {};
case '[object String]':
return '';
}
}
});
/**
* Creates a new object by recursively evolving a shallow copy of `object`, according to the
* `transformation` functions. All non-primitive properties are copied by reference.
*
* A `tranformation` function will not be invoked if its corresponding key does not exist in
* the evolved object.
*
* @func
* @memberOf R
* @category Object
* @sig {k: (v -> v)} -> {k: v} -> {k: v}
* @param {Object} transformations The object specifying transformation functions to apply
* to the object.
* @param {Object} object The object to be transformed.
* @return {Object} The transformed object.
* @example
*
* var tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};
* var transformations = {
* firstName: R.trim,
* lastName: R.trim, // Will not get invoked.
* data: {elapsed: R.add(1), remaining: R.add(-1)}
* };
* R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123}
*/
var evolve = _curry2(function evolve(transformations, object) {
var transformation, key, type, result = {};
for (key in object) {
transformation = transformations[key];
type = typeof transformation;
result[key] = type === 'function' ? transformation(object[key]) : type === 'object' ? evolve(transformations[key], object[key]) : object[key];
}
return result;
});
/**
* Creates a new object out of a list key-value pairs.
*
* @func
* @memberOf R
* @category List
* @sig [[k,v]] -> {k: v}
* @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object.
* @return {Object} The object made by pairing up `keys` and `values`.
* @see R.toPairs
* @example
*
* R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
*/
var fromPairs = _curry1(function fromPairs(pairs) {
var idx = 0, len = pairs.length, out = {};
while (idx < len) {
if (_isArray(pairs[idx]) && pairs[idx].length) {
out[pairs[idx][0]] = pairs[idx][1];
}
idx += 1;
}
return out;
});
/**
* Returns `true` if the first argument is greater than the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @see R.lt
* @example
*
* R.gt(2, 1); //=> true
* R.gt(2, 2); //=> false
* R.gt(2, 3); //=> false
* R.gt('a', 'z'); //=> false
* R.gt('z', 'a'); //=> true
*/
var gt = _curry2(function gt(a, b) {
return a > b;
});
/**
* Returns `true` if the first argument is greater than or equal to the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean}
* @see R.lte
* @example
*
* R.gte(2, 1); //=> true
* R.gte(2, 2); //=> true
* R.gte(2, 3); //=> false
* R.gte('a', 'z'); //=> false
* R.gte('z', 'a'); //=> true
*/
var gte = _curry2(function gte(a, b) {
return a >= b;
});
/**
* Returns whether or not an object has an own property with
* the specified name
*
* @func
* @memberOf R
* @category Object
* @sig s -> {s: x} -> Boolean
* @param {String} prop The name of the property to check for.
* @param {Object} obj The object to query.
* @return {Boolean} Whether the property exists.
* @example
*
* var hasName = R.has('name');
* hasName({name: 'alice'}); //=> true
* hasName({name: 'bob'}); //=> true
* hasName({}); //=> false
*
* var point = {x: 0, y: 0};
* var pointHas = R.has(R.__, point);
* pointHas('x'); //=> true
* pointHas('y'); //=> true
* pointHas('z'); //=> false
*/
var has = _curry2(_has);
/**
* Returns whether or not an object or its prototype chain has
* a property with the specified name
*
* @func
* @memberOf R
* @category Object
* @sig s -> {s: x} -> Boolean
* @param {String} prop The name of the property to check for.
* @param {Object} obj The object to query.
* @return {Boolean} Whether the property exists.
* @example
*
* function Rectangle(width, height) {
* this.width = width;
* this.height = height;
* }
* Rectangle.prototype.area = function() {
* return this.width * this.height;
* };
*
* var square = new Rectangle(2, 2);
* R.hasIn('width', square); //=> true
* R.hasIn('area', square); //=> true
*/
var hasIn = _curry2(function hasIn(prop, obj) {
return prop in obj;
});
/**
* Returns true if its arguments are identical, false otherwise. Values are
* identical if they reference the same memory. `NaN` is identical to `NaN`;
* `0` and `-0` are not identical.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.identical(o, o); //=> true
* R.identical(1, 1); //=> true
* R.identical(1, '1'); //=> false
* R.identical([], []); //=> false
* R.identical(0, -0); //=> false
* R.identical(NaN, NaN); //=> true
*/
// SameValue algorithm
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Step 6.a: NaN == NaN
var identical = _curry2(function identical(a, b) {
// SameValue algorithm
if (a === b) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return a !== 0 || 1 / a === 1 / b;
} else {
// Step 6.a: NaN == NaN
return a !== a && b !== b;
}
});
/**
* A function that does nothing but return the parameter supplied to it. Good as a default
* or placeholder function.
*
* @func
* @memberOf R
* @category Function
* @sig a -> a
* @param {*} x The value to return.
* @return {*} The input value, `x`.
* @example
*
* R.identity(1); //=> 1
*
* var obj = {};
* R.identity(obj) === obj; //=> true
*/
var identity = _curry1(_identity);
/**
* Creates a function that will process either the `onTrue` or the `onFalse` function depending
* upon the result of the `condition` predicate.
*
* @func
* @memberOf R
* @category Logic
* @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *)
* @param {Function} condition A predicate function
* @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value.
* @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value.
* @return {Function} A new unary function that will process either the `onTrue` or the `onFalse`
* function depending upon the result of the `condition` predicate.
* @example
*
* // Flatten all arrays in the list but leave other values alone.
* var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity));
*
* flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}]
* flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"]
*/
var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) {
return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() {
return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments);
});
});
/**
* Increments its argument.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @see R.dec
* @example
*
* R.inc(42); //=> 43
*/
var inc = add(1);
/**
* Inserts the supplied element into the list, at index `index`. _Note
* that this is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} index The position to insert the element
* @param {*} elt The element to insert into the Array
* @param {Array} list The list to insert into
* @return {Array} A new Array with `elt` inserted at `index`.
* @example
*
* R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
*/
var insert = _curry3(function insert(idx, elt, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
var result = _slice(list);
result.splice(idx, 0, elt);
return result;
});
/**
* Inserts the sub-list into the list, at index `index`. _Note that this
* is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a] -> [a]
* @param {Number} index The position to insert the sub-list
* @param {Array} elts The sub-list to insert into the Array
* @param {Array} list The list to insert the sub-list into
* @return {Array} A new Array with `elts` inserted starting at `index`.
* @example
*
* R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
*/
var insertAll = _curry3(function insertAll(idx, elts, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return _concat(_concat(_slice(list, 0, idx), elts), _slice(list, idx));
});
/**
* See if an object (`val`) is an instance of the supplied constructor.
* This function will check up the inheritance chain, if any.
*
* @func
* @memberOf R
* @category Type
* @sig (* -> {*}) -> a -> Boolean
* @param {Object} ctor A constructor
* @param {*} val The value to test
* @return {Boolean}
* @example
*
* R.is(Object, {}); //=> true
* R.is(Number, 1); //=> true
* R.is(Object, 1); //=> false
* R.is(String, 's'); //=> true
* R.is(String, new String('')); //=> true
* R.is(Object, new String('')); //=> true
* R.is(Object, 's'); //=> false
* R.is(Number, {}); //=> false
*/
var is = _curry2(function is(Ctor, val) {
return val != null && val.constructor === Ctor || val instanceof Ctor;
});
/**
* Tests whether or not an object is similar to an array.
*
* @func
* @memberOf R
* @category Type
* @category List
* @sig * -> Boolean
* @param {*} x The object to test.
* @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
* @example
*
* R.isArrayLike([]); //=> true
* R.isArrayLike(true); //=> false
* R.isArrayLike({}); //=> false
* R.isArrayLike({length: 10}); //=> false
* R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
*/
var isArrayLike = _curry1(function isArrayLike(x) {
if (_isArray(x)) {
return true;
}
if (!x) {
return false;
}
if (typeof x !== 'object') {
return false;
}
if (x instanceof String) {
return false;
}
if (x.nodeType === 1) {
return !!x.length;
}
if (x.length === 0) {
return true;
}
if (x.length > 0) {
return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
}
return false;
});
/**
* Reports whether the list has zero elements.
*
* @func
* @memberOf R
* @category Logic
* @sig [a] -> Boolean
* @param {Array} list
* @return {Boolean}
* @example
*
* R.isEmpty([1, 2, 3]); //=> false
* R.isEmpty([]); //=> true
* R.isEmpty(''); //=> true
* R.isEmpty(null); //=> false
* R.isEmpty(R.keys({})); //=> true
* R.isEmpty({}); //=> false ({} does not have a length property)
* R.isEmpty({length: 0}); //=> true
*/
var isEmpty = _curry1(function isEmpty(list) {
return Object(list).length === 0;
});
/**
* Checks if the input value is `null` or `undefined`.
*
* @func
* @memberOf R
* @category Type
* @sig * -> Boolean
* @param {*} x The value to test.
* @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`.
* @example
*
* R.isNil(null); //=> true
* R.isNil(undefined); //=> true
* R.isNil(0); //=> false
* R.isNil([]); //=> false
*/
var isNil = _curry1(function isNil(x) {
return x == null;
});
/**
* Returns a list containing the names of all the enumerable own
* properties of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own properties.
* @example
*
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
*/
// cover IE < 9 keys issues
var keys = function () {
// cover IE < 9 keys issues
var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
var nonEnumerableProps = [
'constructor',
'valueOf',
'isPrototypeOf',
'toString',
'propertyIsEnumerable',
'hasOwnProperty',
'toLocaleString'
];
var contains = function contains(list, item) {
var idx = 0;
while (idx < list.length) {
if (list[idx] === item) {
return true;
}
idx += 1;
}
return false;
};
return typeof Object.keys === 'function' ? _curry1(function keys(obj) {
return Object(obj) !== obj ? [] : Object.keys(obj);
}) : _curry1(function keys(obj) {
if (Object(obj) !== obj) {
return [];
}
var prop, ks = [], nIdx;
for (prop in obj) {
if (_has(prop, obj)) {
ks[ks.length] = prop;
}
}
if (hasEnumBug) {
nIdx = nonEnumerableProps.length - 1;
while (nIdx >= 0) {
prop = nonEnumerableProps[nIdx];
if (_has(prop, obj) && !contains(ks, prop)) {
ks[ks.length] = prop;
}
nIdx -= 1;
}
}
return ks;
});
}();
/**
* Returns a list containing the names of all the
* properties of the supplied object, including prototype properties.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.keysIn(f); //=> ['x', 'y']
*/
var keysIn = _curry1(function keysIn(obj) {
var prop, ks = [];
for (prop in obj) {
ks[ks.length] = prop;
}
return ks;
});
/**
* Returns the number of elements in the array by returning `list.length`.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Number
* @param {Array} list The array to inspect.
* @return {Number} The length of the array.
* @example
*
* R.length([]); //=> 0
* R.length([1, 2, 3]); //=> 3
*/
var length = _curry1(function length(list) {
return list != null && is(Number, list.length) ? list.length : NaN;
});
/**
* Returns `true` if the first argument is less than the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @see R.gt
* @example
*
* R.lt(2, 1); //=> false
* R.lt(2, 2); //=> false
* R.lt(2, 3); //=> true
* R.lt('a', 'z'); //=> true
* R.lt('z', 'a'); //=> false
*/
var lt = _curry2(function lt(a, b) {
return a < b;
});
/**
* Returns `true` if the first argument is less than or equal to the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean}
* @see R.gte
* @example
*
* R.lte(2, 1); //=> false
* R.lte(2, 2); //=> true
* R.lte(2, 3); //=> true
* R.lte('a', 'z'); //=> true
* R.lte('z', 'a'); //=> false
*/
var lte = _curry2(function lte(a, b) {
return a <= b;
});
/**
* The mapAccum function behaves like a combination of map and reduce; it applies a
* function to each element of a list, passing an accumulating parameter from left to
* right, and returning a final value of this accumulator together with the new list.
*
* The iterator function receives two arguments, *acc* and *value*, and should return
* a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @category List
* @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var digits = ['1', '2', '3', '4'];
* var append = function(a, b) {
* return [a + b, a + b];
* }
*
* R.mapAccum(append, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
*/
var mapAccum = _curry3(function mapAccum(fn, acc, list) {
var idx = 0, len = list.length, result = [], tuple = [acc];
while (idx < len) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx += 1;
}
return [
tuple[0],
result
];
});
/**
* The mapAccumRight function behaves like a combination of map and reduce; it applies a
* function to each element of a list, passing an accumulating parameter from right
* to left, and returning a final value of this accumulator together with the new list.
*
* Similar to `mapAccum`, except moves through the input list from the right to the
* left.
*
* The iterator function receives two arguments, *acc* and *value*, and should return
* a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @category List
* @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var digits = ['1', '2', '3', '4'];
* var append = function(a, b) {
* return [a + b, a + b];
* }
*
* R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']]
*/
var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
var idx = list.length - 1, result = [], tuple = [acc];
while (idx >= 0) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
}
return [
tuple[0],
result
];
});
/**
* mathMod behaves like the modulo operator should mathematically, unlike the `%`
* operator (and by extension, R.modulo). So while "-17 % 5" is -2,
* mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
* when the modulus is zero or negative.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} m The dividend.
* @param {Number} p the modulus.
* @return {Number} The result of `b mod a`.
* @example
*
* R.mathMod(-17, 5); //=> 3
* R.mathMod(17, 5); //=> 2
* R.mathMod(17, -5); //=> NaN
* R.mathMod(17, 0); //=> NaN
* R.mathMod(17.2, 5); //=> NaN
* R.mathMod(17, 5.3); //=> NaN
*
* var clock = R.mathMod(R.__, 12);
* clock(15); //=> 3
* clock(24); //=> 0
*
* var seventeenMod = R.mathMod(17);
* seventeenMod(3); //=> 2
* seventeenMod(4); //=> 1
* seventeenMod(10); //=> 7
*/
var mathMod = _curry2(function mathMod(m, p) {
if (!_isInteger(m)) {
return NaN;
}
if (!_isInteger(p) || p < 1) {
return NaN;
}
return (m % p + p) % p;
});
/**
* Returns the larger of its two arguments.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> a
* @param {*} a
* @param {*} b
* @return {*}
* @see R.maxBy, R.min
* @example
*
* R.max(789, 123); //=> 789
* R.max('a', 'b'); //=> 'b'
*/
var max = _curry2(function max(a, b) {
return b > a ? b : a;
});
/**
* Takes a function and two values, and returns whichever value produces
* the larger result when passed to the provided function.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord b => (a -> b) -> a -> a -> a
* @param {Function} f
* @param {*} a
* @param {*} b
* @return {*}
* @see R.max, R.minBy
* @example
*
* R.maxBy(function(n) { return n * n; }, -3, 2); //=> -3
*/
var maxBy = _curry3(function maxBy(f, a, b) {
return f(b) > f(a) ? b : a;
});
/**
* Create a new object with the own properties of `a`
* merged with the own properties of object `b`.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> {k: v} -> {k: v}
* @param {Object} a
* @param {Object} b
* @return {Object}
* @example
*
* R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*
* var resetToDefault = R.merge(R.__, {x: 0});
* resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}
*/
var merge = _curry2(function merge(a, b) {
var result = {};
var ks = keys(a);
var idx = 0;
while (idx < ks.length) {
result[ks[idx]] = a[ks[idx]];
idx += 1;
}
ks = keys(b);
idx = 0;
while (idx < ks.length) {
result[ks[idx]] = b[ks[idx]];
idx += 1;
}
return result;
});
/**
* Returns the smaller of its two arguments.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord a => a -> a -> a
* @param {*} a
* @param {*} b
* @return {*}
* @see R.minBy, R.max
* @example
*
* R.min(789, 123); //=> 123
* R.min('a', 'b'); //=> 'a'
*/
var min = _curry2(function min(a, b) {
return b < a ? b : a;
});
/**
* Takes a function and two values, and returns whichever value produces
* the smaller result when passed to the provided function.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord b => (a -> b) -> a -> a -> a
* @param {Function} f
* @param {*} a
* @param {*} b
* @return {*}
* @see R.min, R.maxBy
* @example
*
* R.minBy(function(n) { return n * n; }, -3, 2); //=> 2
*/
var minBy = _curry3(function minBy(f, a, b) {
return f(b) < f(a) ? b : a;
});
/**
* Divides the second parameter by the first and returns the remainder.
* Note that this functions preserves the JavaScript-style behavior for
* modulo. For mathematical modulo see `mathMod`
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The value to the divide.
* @param {Number} b The pseudo-modulus
* @return {Number} The result of `b % a`.
* @see R.mathMod
* @example
*
* R.modulo(17, 3); //=> 2
* // JS behavior:
* R.modulo(-17, 3); //=> -2
* R.modulo(17, -3); //=> 2
*
* var isOdd = R.modulo(R.__, 2);
* isOdd(42); //=> 0
* isOdd(21); //=> 1
*/
var modulo = _curry2(function modulo(a, b) {
return a % b;
});
/**
* Multiplies two numbers. Equivalent to `a * b` but curried.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a * b`.
* @see R.divide
* @example
*
* var double = R.multiply(2);
* var triple = R.multiply(3);
* double(3); //=> 6
* triple(4); //=> 12
* R.multiply(2, 5); //=> 10
*/
var multiply = _curry2(function multiply(a, b) {
return a * b;
});
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {Number} n The desired arity of the new function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.nAry(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only `n` arguments are passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var nAry = _curry2(function nAry(n, fn) {
switch (n) {
case 0:
return function () {
return fn.call(this);
};
case 1:
return function (a0) {
return fn.call(this, a0);
};
case 2:
return function (a0, a1) {
return fn.call(this, a0, a1);
};
case 3:
return function (a0, a1, a2) {
return fn.call(this, a0, a1, a2);
};
case 4:
return function (a0, a1, a2, a3) {
return fn.call(this, a0, a1, a2, a3);
};
case 5:
return function (a0, a1, a2, a3, a4) {
return fn.call(this, a0, a1, a2, a3, a4);
};
case 6:
return function (a0, a1, a2, a3, a4, a5) {
return fn.call(this, a0, a1, a2, a3, a4, a5);
};
case 7:
return function (a0, a1, a2, a3, a4, a5, a6) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6);
};
case 8:
return function (a0, a1, a2, a3, a4, a5, a6, a7) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);
};
case 9:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);
};
case 10:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
};
default:
throw new Error('First argument to nAry must be a non-negative integer no greater than ten');
}
});
/**
* Negates its argument.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @example
*
* R.negate(42); //=> -42
*/
var negate = _curry1(function negate(n) {
return -n;
});
/**
* A function that returns the `!` of its argument. It will return `true` when
* passed false-y value, and `false` when passed a truth-y one.
*
* @func
* @memberOf R
* @category Logic
* @sig * -> Boolean
* @param {*} a any value
* @return {Boolean} the logical inverse of passed argument.
* @see R.complement
* @example
*
* R.not(true); //=> false
* R.not(false); //=> true
* R.not(0); => true
* R.not(1); => false
*/
var not = _curry1(function not(a) {
return !a;
});
/**
* Returns the nth element of the given list or string.
* If n is negative the element at index length + n is returned.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> a | Undefined
* @sig Number -> String -> String
* @param {Number} offset
* @param {*} list
* @return {*}
* @example
*
* var list = ['foo', 'bar', 'baz', 'quux'];
* R.nth(1, list); //=> 'bar'
* R.nth(-1, list); //=> 'quux'
* R.nth(-99, list); //=> undefined
*
* R.nth('abc', 2); //=> 'c'
* R.nth('abc', 3); //=> ''
*/
var nth = _curry2(function nth(offset, list) {
var idx = offset < 0 ? list.length + offset : offset;
return _isString(list) ? list.charAt(idx) : list[idx];
});
/**
* Returns a function which returns its nth argument.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> *... -> *
* @param {Number} n
* @return {Function}
* @example
*
* R.nthArg(1)('a', 'b', 'c'); //=> 'b'
* R.nthArg(-1)('a', 'b', 'c'); //=> 'c'
*/
var nthArg = _curry1(function nthArg(n) {
return function () {
return nth(n, arguments);
};
});
/**
* Returns the nth character of the given string.
*
* @func
* @memberOf R
* @category String
* @sig Number -> String -> String
* @param {Number} n
* @param {String} str
* @return {String}
* @deprecated since v0.16.0
* @example
*
* R.nthChar(2, 'Ramda'); //=> 'm'
* R.nthChar(-2, 'Ramda'); //=> 'd'
*/
var nthChar = _curry2(function nthChar(n, str) {
return str.charAt(n < 0 ? str.length + n : n);
});
/**
* Returns the character code of the nth character of the given string.
*
* @func
* @memberOf R
* @category String
* @sig Number -> String -> Number
* @param {Number} n
* @param {String} str
* @return {Number}
* @deprecated since v0.16.0
* @example
*
* R.nthCharCode(2, 'Ramda'); //=> 'm'.charCodeAt(0)
* R.nthCharCode(-2, 'Ramda'); //=> 'd'.charCodeAt(0)
*/
var nthCharCode = _curry2(function nthCharCode(n, str) {
return str.charCodeAt(n < 0 ? str.length + n : n);
});
/**
* Returns a singleton array containing the value provided.
*
* Note this `of` is different from the ES6 `of`; See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
*
* @func
* @memberOf R
* @category Function
* @sig a -> [a]
* @param {*} x any value
* @return {Array} An array wrapping `x`.
* @example
*
* R.of(null); //=> [null]
* R.of([42]); //=> [[42]]
*/
var of = _curry1(function of(x) {
return [x];
});
/**
* Accepts a function `fn` and returns a function that guards invocation of `fn` such that
* `fn` can only ever be called once, no matter how many times the returned function is
* invoked.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to wrap in a call-only-once wrapper.
* @return {Function} The wrapped function.
* @example
*
* var addOneOnce = R.once(function(x){ return x + 1; });
* addOneOnce(10); //=> 11
* addOneOnce(addOneOnce(50)); //=> 11
*/
var once = _curry1(function once(fn) {
var called = false, result;
return function () {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
};
});
/**
* Returns the result of "setting" the portion of the given data structure
* focused by the given lens to the given value.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> (a -> a) -> s -> s
* @param {Lens} lens
* @param {*} v
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var headLens = R.lensIndex(0);
*
* R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz']
*/
var over = function () {
var Identity = function (x) {
return {
value: x,
map: function (f) {
return Identity(f(x));
}
};
};
return _curry3(function over(lens, f, x) {
return lens(function (y) {
return Identity(f(y));
})(x).value;
});
}();
/**
* Retrieve the value at a given path.
*
* @func
* @memberOf R
* @category Object
* @sig [String] -> {k: v} -> v | Undefined
* @param {Array} path The path to use.
* @return {*} The data at `path`.
* @example
*
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
*/
var path = _curry2(function path(paths, obj) {
if (obj == null) {
return;
} else {
var val = obj;
for (var idx = 0, len = paths.length; idx < len && val != null; idx += 1) {
val = val[paths[idx]];
}
return val;
}
});
/**
* Returns a partial copy of an object containing only the keys specified. If the key does not exist, the
* property is ignored.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String property names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.omit
* @example
*
* R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
*/
var pick = _curry2(function pick(names, obj) {
var result = {};
var idx = 0;
while (idx < names.length) {
if (names[idx] in obj) {
result[names[idx]] = obj[names[idx]];
}
idx += 1;
}
return result;
});
/**
* Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String property names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.pick
* @example
*
* R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
*/
var pickAll = _curry2(function pickAll(names, obj) {
var result = {};
var idx = 0;
var len = names.length;
while (idx < len) {
var name = names[idx];
result[name] = obj[name];
idx += 1;
}
return result;
});
/**
* Returns a partial copy of an object containing only the keys that
* satisfy the supplied predicate.
*
* @func
* @memberOf R
* @category Object
* @sig (v, k -> Boolean) -> {k: v} -> {k: v}
* @param {Function} pred A predicate to determine whether or not a key
* should be included on the output object.
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties that satisfy `pred`
* on it.
* @see R.pick
* @example
*
* var isUpperCase = function(val, key) { return key.toUpperCase() === key; }
* R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
*/
var pickBy = _curry2(function pickBy(test, obj) {
var result = {};
for (var prop in obj) {
if (test(obj[prop], prop, obj)) {
result[prop] = obj[prop];
}
}
return result;
});
/**
* Returns a new list with the given element at the front, followed by the contents of the
* list.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> [a]
* @param {*} el The item to add to the head of the output list.
* @param {Array} list The array to add to the tail of the output list.
* @return {Array} A new array.
* @see R.append
* @example
*
* R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
*/
var prepend = _curry2(function prepend(el, list) {
return _concat([el], list);
});
/**
* Returns a function that when supplied an object returns the indicated property of that object, if it exists.
*
* @func
* @memberOf R
* @category Object
* @sig s -> {s: a} -> a | Undefined
* @param {String} p The property name
* @param {Object} obj The object to query
* @return {*} The value at `obj.p`.
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
*/
var prop = _curry2(function prop(p, obj) {
return obj[p];
});
/**
* If the given, non-null object has an own property with the specified name,
* returns the value of that property.
* Otherwise returns the provided default value.
*
* @func
* @memberOf R
* @category Object
* @sig a -> String -> Object -> a
* @param {*} val The default value.
* @param {String} p The name of the property to return.
* @param {Object} obj The object to query.
* @return {*} The value of given property of the supplied object or the default value.
* @example
*
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var favorite = R.prop('favoriteLibrary');
* var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');
*
* favorite(alice); //=> undefined
* favoriteWithDefault(alice); //=> 'Ramda'
*/
var propOr = _curry3(function propOr(val, p, obj) {
return obj != null && _has(p, obj) ? obj[p] : val;
});
/**
* Returns `true` if the specified object property satisfies the given
* predicate; `false` otherwise.
*
* @func
* @memberOf R
* @category Logic
* @sig (a -> Boolean) -> String -> {String: a} -> Boolean
* @param {Function} pred
* @param {String} name
* @param {*} obj
* @return {Boolean}
* @see R.propEq
* @see R.propIs
* @example
*
* R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true
*/
var propSatisfies = _curry3(function propSatisfies(pred, name, obj) {
return pred(obj[name]);
});
/**
* Acts as multiple `prop`: array of keys in, array of values out. Preserves order.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> [v]
* @param {Array} ps The property names to fetch
* @param {Object} obj The object to query
* @return {Array} The corresponding values or partially applied function.
* @example
*
* R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]
* R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]
*
* var fullName = R.compose(R.join(' '), R.props(['first', 'last']));
* fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'
*/
var props = _curry2(function props(ps, obj) {
var len = ps.length;
var out = [];
var idx = 0;
while (idx < len) {
out[idx] = obj[ps[idx]];
idx += 1;
}
return out;
});
/**
* Returns a list of numbers from `from` (inclusive) to `to`
* (exclusive).
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [Number]
* @param {Number} from The first number in the list.
* @param {Number} to One more than the last number in the list.
* @return {Array} The list of numbers in tthe set `[a, b)`.
* @example
*
* R.range(1, 5); //=> [1, 2, 3, 4]
* R.range(50, 53); //=> [50, 51, 52]
*/
var range = _curry2(function range(from, to) {
if (!(_isNumber(from) && _isNumber(to))) {
throw new TypeError('Both arguments to range must be numbers');
}
var result = [];
var n = from;
while (n < to) {
result.push(n);
n += 1;
}
return result;
});
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* Similar to `reduce`, except moves through the input list from the right to the left.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
* var flattenPairs = function(acc, pair) {
* return acc.concat(pair);
* };
*
* R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
*/
var reduceRight = _curry3(function reduceRight(fn, acc, list) {
var idx = list.length - 1;
while (idx >= 0) {
acc = fn(acc, list[idx]);
idx -= 1;
}
return acc;
});
/**
* Returns a value wrapped to indicate that it is the final value of the
* reduce and transduce functions. The returned value
* should be considered a black box: the internal structure is not
* guaranteed to be stable.
*
* Note: this optimization is unavailable to functions not explicitly listed
* above. For instance, it is not currently supported by reduceIndexed,
* reduceRight, or reduceRightIndexed.
*
* @func
* @memberOf R
* @category List
* @see R.reduce, R.transduce
* @sig a -> *
* @param {*} x The final value of the reduce.
* @return {*} The wrapped value.
* @example
*
* R.reduce(
* R.pipe(R.add, R.ifElse(R.lte(10), R.reduced, R.identity)),
* 0,
* [1, 2, 3, 4, 5]) // 10
*/
var reduced = _curry1(_reduced);
/**
* Removes the sub-list of `list` starting at index `start` and containing
* `count` elements. _Note that this is not destructive_: it returns a
* copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {Number} start The position to start removing elements
* @param {Number} count The number of elements to remove
* @param {Array} list The list to remove from
* @return {Array} A new Array with `count` elements from `start` removed.
* @example
*
* R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
*/
var remove = _curry3(function remove(start, count, list) {
return _concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count)));
});
/**
* Replace a substring or regex match in a string with a replacement.
*
* @func
* @memberOf R
* @category String
* @sig RegExp|String -> String -> String -> String
* @param {RegExp|String} pattern A regular expression or a substring to match.
* @param {String} replacement The string to replace the matches with.
* @param {String} str The String to do the search and replacement in.
* @return {String} The result.
* @example
*
* R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
* R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
*
* // Use the "g" (global) flag to replace all occurrences:
* R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
*/
var replace = _curry3(function replace(regex, replacement, str) {
return str.replace(regex, replacement);
});
/**
* Returns a new list with the same elements as the original list, just
* in the reverse order.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The list to reverse.
* @return {Array} A copy of the list in reverse order.
* @example
*
* R.reverse([1, 2, 3]); //=> [3, 2, 1]
* R.reverse([1, 2]); //=> [2, 1]
* R.reverse([1]); //=> [1]
* R.reverse([]); //=> []
*/
var reverse = _curry1(function reverse(list) {
return _slice(list).reverse();
});
/**
* Scan is similar to reduce, but returns a list of successively reduced values from the left
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> [a]
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {Array} A list of all intermediately reduced values.
* @example
*
* var numbers = [1, 2, 3, 4];
* var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
*/
var scan = _curry3(function scan(fn, acc, list) {
var idx = 0, len = list.length, result = [acc];
while (idx < len) {
acc = fn(acc, list[idx]);
result[idx + 1] = acc;
idx += 1;
}
return result;
});
/**
* Returns the result of "setting" the portion of the given data structure
* focused by the given lens to the given value.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> a -> s -> s
* @param {Lens} lens
* @param {*} v
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lensProp('x');
*
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2}
*/
var set = _curry3(function set(lens, v, x) {
return over(lens, always(v), x);
});
/**
* Returns a copy of the list, sorted according to the comparator function, which should accept two values at a
* time and return a negative number if the first value is smaller, a positive number if it's larger, and zero
* if they are equal. Please note that this is a **copy** of the list. It does not modify the original.
*
* @func
* @memberOf R
* @category List
* @sig (a,a -> Number) -> [a] -> [a]
* @param {Function} comparator A sorting function :: a -> b -> Int
* @param {Array} list The list to sort
* @return {Array} a new array with its elements sorted by the comparator function.
* @example
*
* var diff = function(a, b) { return a - b; };
* R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
*/
var sort = _curry2(function sort(comparator, list) {
return _slice(list).sort(comparator);
});
/**
* Sorts the list according to the supplied function.
*
* @func
* @memberOf R
* @category Relation
* @sig Ord b => (a -> b) -> [a] -> [a]
* @param {Function} fn
* @param {Array} list The list to sort.
* @return {Array} A new list sorted by the keys generated by `fn`.
* @example
*
* var sortByFirstItem = R.sortBy(prop(0));
* var sortByNameCaseInsensitive = R.sortBy(compose(R.toLower, prop('name')));
* var pairs = [[-1, 1], [-2, 2], [-3, 3]];
* sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var bob = {
* name: 'Bob',
* age: -10
* };
* var clara = {
* name: 'clara',
* age: 314.159
* };
* var people = [clara, bob, alice];
* sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
*/
var sortBy = _curry2(function sortBy(fn, list) {
return _slice(list).sort(function (a, b) {
var aa = fn(a);
var bb = fn(b);
return aa < bb ? -1 : aa > bb ? 1 : 0;
});
});
/**
* Subtracts two numbers. Equivalent to `a - b` but curried.
*
* @func
* @memberOf R
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a - b`.
* @see R.add
* @example
*
* R.subtract(10, 8); //=> 2
*
* var minus5 = R.subtract(R.__, 5);
* minus5(17); //=> 12
*
* var complementaryAngle = R.subtract(90);
* complementaryAngle(30); //=> 60
* complementaryAngle(72); //=> 18
*/
var subtract = _curry2(function subtract(a, b) {
return a - b;
});
/**
* Returns a new list containing the last `n` elements of a given list, passing each value
* to the supplied predicate function, and terminating when the predicate function returns
* `false`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.dropLastWhile
* @example
*
* var isNotOne = function(x) {
* return !(x === 1);
* };
*
* R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4]
*/
var takeLastWhile = _curry2(function takeLastWhile(fn, list) {
var idx = list.length - 1;
while (idx >= 0 && fn(list[idx])) {
idx -= 1;
}
return _slice(list, idx + 1, Infinity);
});
/**
* Runs the given function with the supplied object, then returns the object.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> *) -> a -> a
* @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
* @param {*} x
* @return {*} `x`.
* @example
*
* var sayX = function(x) { console.log('x is ' + x); };
* R.tap(sayX, 100); //=> 100
* //-> 'x is 100'
*/
var tap = _curry2(function tap(fn, x) {
fn(x);
return x;
});
/**
* Determines whether a given string matches a given regular expression.
*
* @func
* @memberOf R
* @category String
* @sig RegExp -> String -> Boolean
* @param {RegExp} pattern
* @param {String} str
* @return {Boolean}
* @example
*
* R.test(/^x/, 'xyz'); //=> true
* R.test(/^y/, 'xyz'); //=> false
*/
var test = _curry2(function test(pattern, str) {
return _cloneRegExp(pattern).test(str);
});
/**
* Calls an input function `n` times, returning an array containing the results of those
* function calls.
*
* `fn` is passed one argument: The current value of `n`, which begins at `0` and is
* gradually incremented to `n - 1`.
*
* @func
* @memberOf R
* @category List
* @sig (i -> a) -> i -> [a]
* @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
* @param {Number} n A value between `0` and `n - 1`. Increments after each function call.
* @return {Array} An array containing the return values of all calls to `fn`.
* @example
*
* R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
*/
var times = _curry2(function times(fn, n) {
var len = Number(n);
var list = new Array(len);
var idx = 0;
while (idx < len) {
list[idx] = fn(idx);
idx += 1;
}
return list;
});
/**
* Converts an object into an array of key, value arrays.
* Only the object's own properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {String: *} -> [[String,*]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own properties.
* @see R.fromPairs
* @example
*
* R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
*/
var toPairs = _curry1(function toPairs(obj) {
var pairs = [];
for (var prop in obj) {
if (_has(prop, obj)) {
pairs[pairs.length] = [
prop,
obj[prop]
];
}
}
return pairs;
});
/**
* Converts an object into an array of key, value arrays.
* The object's own properties and prototype properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {String: *} -> [[String,*]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own
* and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
*/
var toPairsIn = _curry1(function toPairsIn(obj) {
var pairs = [];
for (var prop in obj) {
pairs[pairs.length] = [
prop,
obj[prop]
];
}
return pairs;
});
/**
* Removes (strips) whitespace from both ends of the string.
*
* @func
* @memberOf R
* @category String
* @sig String -> String
* @param {String} str The string to trim.
* @return {String} Trimmed version of `str`.
* @example
*
* R.trim(' xyz '); //=> 'xyz'
* R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']
*/
var trim = function () {
var ws = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + '\u2029\uFEFF';
var zeroWidth = '\u200B';
var hasProtoTrim = typeof String.prototype.trim === 'function';
if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) {
return _curry1(function trim(str) {
var beginRx = new RegExp('^[' + ws + '][' + ws + ']*');
var endRx = new RegExp('[' + ws + '][' + ws + ']*$');
return str.replace(beginRx, '').replace(endRx, '');
});
} else {
return _curry1(function trim(str) {
return str.trim();
});
}
}();
/**
* Gives a single-word string description of the (native) type of a value, returning such
* answers as 'Object', 'Number', 'Array', or 'Null'. Does not attempt to distinguish user
* Object types any further, reporting them all as 'Object'.
*
* @func
* @memberOf R
* @category Type
* @sig (* -> {*}) -> String
* @param {*} val The value to test
* @return {String}
* @example
*
* R.type({}); //=> "Object"
* R.type(1); //=> "Number"
* R.type(false); //=> "Boolean"
* R.type('s'); //=> "String"
* R.type(null); //=> "Null"
* R.type([]); //=> "Array"
* R.type(/[A-z]/); //=> "RegExp"
*/
var type = _curry1(function type(val) {
return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1);
});
/**
* Takes a function `fn`, which takes a single array argument, and returns
* a function which:
*
* - takes any number of positional arguments;
* - passes these arguments to `fn` as an array; and
* - returns the result.
*
* In other words, R.unapply derives a variadic function from a function
* which takes an array. R.unapply is the inverse of R.apply.
*
* @func
* @memberOf R
* @category Function
* @sig ([*...] -> a) -> (*... -> a)
* @param {Function} fn
* @return {Function}
* @see R.apply
* @example
*
* R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'
*/
var unapply = _curry1(function unapply(fn) {
return function () {
return fn(_slice(arguments));
};
});
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 1
* parameter. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> b) -> (a -> b)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 1.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.unary(takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only 1 argument is passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var unary = _curry1(function unary(fn) {
return nAry(1, fn);
});
/**
* Returns a function of arity `n` from a (manually) curried function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (a -> b) -> (a -> c)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to uncurry.
* @return {Function} A new function.
* @see R.curry
* @example
*
* var addFour = function(a) {
* return function(b) {
* return function(c) {
* return function(d) {
* return a + b + c + d;
* };
* };
* };
* };
*
* var uncurriedAddFour = R.uncurryN(4, addFour);
* curriedAddFour(1, 2, 3, 4); //=> 10
*/
var uncurryN = _curry2(function uncurryN(depth, fn) {
return curryN(depth, function () {
var currentDepth = 1;
var value = fn;
var idx = 0;
var endIdx;
while (currentDepth <= depth && typeof value === 'function') {
endIdx = currentDepth === depth ? arguments.length : idx + value.length;
value = value.apply(this, _slice(arguments, idx, endIdx));
currentDepth += 1;
idx = endIdx;
}
return value;
});
});
/**
* Builds a list from a seed value. Accepts an iterator function, which returns either false
* to stop iteration or an array of length 2 containing the value to add to the resulting
* list and the seed to be used in the next call to the iterator function.
*
* The iterator function receives one argument: *(seed)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> * -> [b]
* @param {Function} fn The iterator function. receives one argument, `seed`, and returns
* either false to quit iteration or an array of length two to proceed. The element
* at index 0 of this array will be added to the resulting array, and the element
* at index 1 will be passed to the next call to `fn`.
* @param {*} seed The seed value.
* @return {Array} The final list.
* @example
*
* var f = function(n) { return n > 50 ? false : [-n, n + 10] };
* R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
*/
var unfold = _curry2(function unfold(fn, seed) {
var pair = fn(seed);
var result = [];
while (pair && pair.length) {
result[result.length] = pair[0];
pair = fn(pair[1]);
}
return result;
});
/**
* Returns a new list containing only one copy of each element in the original list, based
* upon the value returned by applying the supplied predicate to two list elements. Prefers
* the first item if two items compare equal based on the predicate.
*
* @func
* @memberOf R
* @category List
* @sig (a, a -> Boolean) -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* var strEq = function(a, b) { return String(a) === String(b); };
* R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
* R.uniqWith(strEq)([{}, {}]); //=> [{}]
* R.uniqWith(strEq)([1, '1', 1]); //=> [1]
* R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
*/
var uniqWith = _curry2(function uniqWith(pred, list) {
var idx = 0, len = list.length;
var result = [], item;
while (idx < len) {
item = list[idx];
if (!_containsWith(pred, item, result)) {
result[result.length] = item;
}
idx += 1;
}
return result;
});
/**
* Returns a new copy of the array with the element at the
* provided index replaced with the given value.
* @see R.adjust
*
* @func
* @memberOf R
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} idx The index to update.
* @param {*} x The value to exist at the given index of the returned array.
* @param {Array|Arguments} list The source array-like object to be updated.
* @return {Array} A copy of `list` with the value at index `idx` replaced with `x`.
* @example
*
* R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2]
* R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2]
*/
var update = _curry3(function update(idx, x, list) {
return adjust(always(x), idx, list);
});
/**
* Returns a list of all the enumerable own properties of the supplied object.
* Note that the order of the output array is not guaranteed across
* different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own properties.
* @example
*
* R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
*/
var values = _curry1(function values(obj) {
var props = keys(obj);
var len = props.length;
var vals = [];
var idx = 0;
while (idx < len) {
vals[idx] = obj[props[idx]];
idx += 1;
}
return vals;
});
/**
* Returns a list of all the properties, including prototype properties,
* of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.valuesIn(f); //=> ['X', 'Y']
*/
var valuesIn = _curry1(function valuesIn(obj) {
var prop, vs = [];
for (prop in obj) {
vs[vs.length] = obj[prop];
}
return vs;
});
/**
* Returns a "view" of the given data structure, determined by the given lens.
* The lens's focus determines which portion of the data structure is visible.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> s -> a
* @param {Lens} lens
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lensProp('x');
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.view(xLens, {x: 4, y: 2}); //=> 4
*/
var view = function () {
var Const = function (x) {
return {
value: x,
map: function () {
return this;
}
};
};
return _curry2(function view(lens, x) {
return lens(Const)(x).value;
});
}();
/**
* Takes a spec object and a test object; returns true if the test satisfies
* the spec. Each of the spec's own properties must be a predicate function.
* Each predicate is applied to the value of the corresponding property of
* the test object. `where` returns true if all the predicates return true,
* false otherwise.
*
* `where` is well suited to declaratively expressing constraints for other
* functions such as `filter` and `find`.
*
* @func
* @memberOf R
* @category Object
* @sig {String: (* -> Boolean)} -> {String: *} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @example
*
* // pred :: Object -> Boolean
* var pred = R.where({
* a: R.equals('foo'),
* b: R.complement(R.equals('bar')),
* x: R.gt(_, 10),
* y: R.lt(_, 20)
* });
*
* pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
* pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
* pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
* pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
* pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
*/
var where = _curry2(function where(spec, testObj) {
for (var prop in spec) {
if (_has(prop, spec) && !spec[prop](testObj[prop])) {
return false;
}
}
return true;
});
/**
* Wrap a function inside another to allow you to make adjustments to the parameters, or do
* other processing either before the internal function is called or with its results.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c)
* @param {Function} fn The function to wrap.
* @param {Function} wrapper The wrapper function.
* @return {Function} The wrapped function.
* @example
*
* var greet = function(name) {return 'Hello ' + name;};
*
* var shoutedGreet = R.wrap(greet, function(gr, name) {
* return gr(name).toUpperCase();
* });
* shoutedGreet("Kathy"); //=> "HELLO KATHY"
*
* var shortenedGreet = R.wrap(greet, function(gr, name) {
* return gr(name.substring(0, 3));
* });
* shortenedGreet("Robert"); //=> "Hello Rob"
*/
var wrap = _curry2(function wrap(fn, wrapper) {
return curryN(fn.length, function () {
return wrapper.apply(this, _concat([fn], arguments));
});
});
/**
* Creates a new list out of the two supplied by creating each possible
* pair from the lists.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b] -> [[a,b]]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` into pairs (`[a, b]`).
* @example
*
* R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
// = xprodWith(prepend); (takes about 3 times as long...)
var xprod = _curry2(function xprod(a, b) {
// = xprodWith(prepend); (takes about 3 times as long...)
var idx = 0;
var ilen = a.length;
var j;
var jlen = b.length;
var result = [];
while (idx < ilen) {
j = 0;
while (j < jlen) {
result[result.length] = [
a[idx],
b[j]
];
j += 1;
}
idx += 1;
}
return result;
});
/**
* Creates a new list out of the two supplied by pairing up
* equally-positioned items from both lists. The returned list is
* truncated to the length of the shorter of the two input lists.
* Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b] -> [[a,b]]
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
* @example
*
* R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
*/
var zip = _curry2(function zip(a, b) {
var rv = [];
var idx = 0;
var len = Math.min(a.length, b.length);
while (idx < len) {
rv[idx] = [
a[idx],
b[idx]
];
idx += 1;
}
return rv;
});
/**
* Creates a new object out of a list of keys and a list of values.
*
* @func
* @memberOf R
* @category List
* @sig [String] -> [*] -> {String: *}
* @param {Array} keys The array that will be properties on the output object.
* @param {Array} values The list of values on the output object.
* @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
* @example
*
* R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
*/
var zipObj = _curry2(function zipObj(keys, values) {
var idx = 0, len = keys.length, out = {};
while (idx < len) {
out[keys[idx]] = values[idx];
idx += 1;
}
return out;
});
/**
* Creates a new list out of the two supplied by applying the function to
* each equally-positioned pair in the lists. The returned list is
* truncated to the length of the shorter of the two input lists.
*
* @function
* @memberOf R
* @category List
* @sig (a,b -> c) -> [a] -> [b] -> [c]
* @param {Function} fn The function used to combine the two elements into one value.
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
* using `fn`.
* @example
*
* var f = function(x, y) {
* // ...
* };
* R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
* //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
*/
var zipWith = _curry3(function zipWith(fn, a, b) {
var rv = [], idx = 0, len = Math.min(a.length, b.length);
while (idx < len) {
rv[idx] = fn(a[idx], b[idx]);
idx += 1;
}
return rv;
});
/**
* A function that always returns `false`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category Function
* @sig * -> false
* @return {Boolean} false
* @see R.always, R.T
* @example
*
* R.F(); //=> false
*/
var F = always(false);
/**
* A function that always returns `true`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category Function
* @sig * -> true
* @return {Boolean} `true`.
* @see R.always, R.F
* @example
*
* R.T(); //=> true
*/
var T = always(true);
/**
* Similar to hasMethod, this checks whether a function has a [methodname]
* function. If it isn't an array it will execute that function otherwise it will
* default to the ramda implementation.
*
* @private
* @param {Function} fn ramda implemtation
* @param {String} methodname property to check for a custom implementation
* @return {Object} Whatever the return value of the method is.
*/
var _checkForMethod = function _checkForMethod(methodname, fn) {
return function () {
var length = arguments.length;
if (length === 0) {
return fn();
}
var obj = arguments[length - 1];
return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, _slice(arguments, 0, length - 1));
};
};
/**
* Copies an object.
*
* @private
* @param {*} value The value to be copied
* @param {Array} refFrom Array containing the source references
* @param {Array} refTo Array containing the copied source references
* @return {*} The copied value.
*/
var _clone = function _clone(value, refFrom, refTo) {
var copy = function copy(copiedValue) {
var len = refFrom.length;
var idx = 0;
while (idx < len) {
if (value === refFrom[idx]) {
return refTo[idx];
}
idx += 1;
}
refFrom[idx + 1] = value;
refTo[idx + 1] = copiedValue;
for (var key in value) {
copiedValue[key] = _clone(value[key], refFrom, refTo);
}
return copiedValue;
};
switch (type(value)) {
case 'Object':
return copy({});
case 'Array':
return copy([]);
case 'Date':
return new Date(value);
case 'RegExp':
return _cloneRegExp(value);
default:
return value;
}
};
var _createPartialApplicator = function _createPartialApplicator(concat) {
return function (fn) {
var args = _slice(arguments, 1);
return _arity(Math.max(0, fn.length - args.length), function () {
return fn.apply(this, concat(args, arguments));
});
};
};
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with [methodname], it will execute that
* function (functor case). Otherwise, if it is a transformer, uses transducer
* [xf] to return a new transformer (transducer case). Otherwise, it will
* default to executing [fn].
*
* @private
* @param {String} methodname property to check for a custom implementation
* @param {Function} xf transducer to initialize if object is transformer
* @param {Function} fn default ramda implementation
* @return {Function} A function that dispatches on object in list position
*/
var _dispatchable = function _dispatchable(methodname, xf, fn) {
return function () {
var length = arguments.length;
if (length === 0) {
return fn();
}
var obj = arguments[length - 1];
if (!_isArray(obj)) {
var args = _slice(arguments, 0, length - 1);
if (typeof obj[methodname] === 'function') {
return obj[methodname].apply(obj, args);
}
if (_isTransformer(obj)) {
var transducer = xf.apply(null, args);
return transducer(obj);
}
}
return fn.apply(this, arguments);
};
};
// The algorithm used to handle cyclic structures is
// inspired by underscore's isEqual
// RegExp equality algorithm: http://stackoverflow.com/a/10776635
var _equals = function _equals(a, b, stackA, stackB) {
var typeA = type(a);
if (typeA !== type(b)) {
return false;
}
if (typeA === 'Boolean' || typeA === 'Number' || typeA === 'String') {
return typeof a === 'object' ? typeof b === 'object' && identical(a.valueOf(), b.valueOf()) : identical(a, b);
}
if (identical(a, b)) {
return true;
}
if (typeA === 'RegExp') {
// RegExp equality algorithm: http://stackoverflow.com/a/10776635
return a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode;
}
if (Object(a) === a) {
if (typeA === 'Date' && a.getTime() !== b.getTime()) {
return false;
}
var keysA = keys(a);
if (keysA.length !== keys(b).length) {
return false;
}
var idx = stackA.length - 1;
while (idx >= 0) {
if (stackA[idx] === a) {
return stackB[idx] === b;
}
idx -= 1;
}
stackA[stackA.length] = a;
stackB[stackB.length] = b;
idx = keysA.length - 1;
while (idx >= 0) {
var key = keysA[idx];
if (!_has(key, b) || !_equals(b[key], a[key], stackA, stackB)) {
return false;
}
idx -= 1;
}
stackA.pop();
stackB.pop();
return true;
}
return false;
};
/**
* Private function that determines whether or not a provided object has a given method.
* Does not ignore methods stored on the object's prototype chain. Used for dynamically
* dispatching Ramda methods to non-Array objects.
*
* @private
* @param {String} methodName The name of the method to check for.
* @param {Object} obj The object to test.
* @return {Boolean} `true` has a given method, `false` otherwise.
* @example
*
* var person = { name: 'John' };
* person.shout = function() { alert(this.name); };
*
* _hasMethod('shout', person); //=> true
* _hasMethod('foo', person); //=> false
*/
var _hasMethod = function _hasMethod(methodName, obj) {
return obj != null && !_isArray(obj) && typeof obj[methodName] === 'function';
};
/**
* `_makeFlat` is a helper function that returns a one-level or fully recursive function
* based on the flag passed in.
*
* @private
*/
var _makeFlat = function _makeFlat(recursive) {
return function flatt(list) {
var value, result = [], idx = 0, j, ilen = list.length, jlen;
while (idx < ilen) {
if (isArrayLike(list[idx])) {
value = recursive ? flatt(list[idx]) : list[idx];
j = 0;
jlen = value.length;
while (j < jlen) {
result[result.length] = value[j];
j += 1;
}
} else {
result[result.length] = list[idx];
}
idx += 1;
}
return result;
};
};
var _reduce = function () {
function _arrayReduce(xf, acc, list) {
var idx = 0, len = list.length;
while (idx < len) {
acc = xf['@@transducer/step'](acc, list[idx]);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
idx += 1;
}
return xf['@@transducer/result'](acc);
}
function _iterableReduce(xf, acc, iter) {
var step = iter.next();
while (!step.done) {
acc = xf['@@transducer/step'](acc, step.value);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
step = iter.next();
}
return xf['@@transducer/result'](acc);
}
function _methodReduce(xf, acc, obj) {
return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc));
}
var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';
return function _reduce(fn, acc, list) {
if (typeof fn === 'function') {
fn = _xwrap(fn);
}
if (isArrayLike(list)) {
return _arrayReduce(fn, acc, list);
}
if (typeof list.reduce === 'function') {
return _methodReduce(fn, acc, list);
}
if (list[symIterator] != null) {
return _iterableReduce(fn, acc, list[symIterator]());
}
if (typeof list.next === 'function') {
return _iterableReduce(fn, acc, list);
}
throw new TypeError('reduce: list must be array or iterable');
};
}();
var _stepCat = function () {
var _stepCatArray = {
'@@transducer/init': Array,
'@@transducer/step': function (xs, x) {
return _concat(xs, [x]);
},
'@@transducer/result': _identity
};
var _stepCatString = {
'@@transducer/init': String,
'@@transducer/step': function (a, b) {
return a + b;
},
'@@transducer/result': _identity
};
var _stepCatObject = {
'@@transducer/init': Object,
'@@transducer/step': function (result, input) {
return merge(result, isArrayLike(input) ? createMapEntry(input[0], input[1]) : input);
},
'@@transducer/result': _identity
};
return function _stepCat(obj) {
if (_isTransformer(obj)) {
return obj;
}
if (isArrayLike(obj)) {
return _stepCatArray;
}
if (typeof obj === 'string') {
return _stepCatString;
}
if (typeof obj === 'object') {
return _stepCatObject;
}
throw new Error('Cannot create transformer for ' + obj);
};
}();
var _xall = function () {
function XAll(f, xf) {
this.xf = xf;
this.f = f;
this.all = true;
}
XAll.prototype['@@transducer/init'] = _xfBase.init;
XAll.prototype['@@transducer/result'] = function (result) {
if (this.all) {
result = this.xf['@@transducer/step'](result, true);
}
return this.xf['@@transducer/result'](result);
};
XAll.prototype['@@transducer/step'] = function (result, input) {
if (!this.f(input)) {
this.all = false;
result = _reduced(this.xf['@@transducer/step'](result, false));
}
return result;
};
return _curry2(function _xall(f, xf) {
return new XAll(f, xf);
});
}();
var _xany = function () {
function XAny(f, xf) {
this.xf = xf;
this.f = f;
this.any = false;
}
XAny.prototype['@@transducer/init'] = _xfBase.init;
XAny.prototype['@@transducer/result'] = function (result) {
if (!this.any) {
result = this.xf['@@transducer/step'](result, false);
}
return this.xf['@@transducer/result'](result);
};
XAny.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.any = true;
result = _reduced(this.xf['@@transducer/step'](result, true));
}
return result;
};
return _curry2(function _xany(f, xf) {
return new XAny(f, xf);
});
}();
var _xdrop = function () {
function XDrop(n, xf) {
this.xf = xf;
this.n = n;
}
XDrop.prototype['@@transducer/init'] = _xfBase.init;
XDrop.prototype['@@transducer/result'] = _xfBase.result;
XDrop.prototype['@@transducer/step'] = function (result, input) {
if (this.n > 0) {
this.n -= 1;
return result;
}
return this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdrop(n, xf) {
return new XDrop(n, xf);
});
}();
var _xdropWhile = function () {
function XDropWhile(f, xf) {
this.xf = xf;
this.f = f;
}
XDropWhile.prototype['@@transducer/init'] = _xfBase.init;
XDropWhile.prototype['@@transducer/result'] = _xfBase.result;
XDropWhile.prototype['@@transducer/step'] = function (result, input) {
if (this.f) {
if (this.f(input)) {
return result;
}
this.f = null;
}
return this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdropWhile(f, xf) {
return new XDropWhile(f, xf);
});
}();
var _xgroupBy = function () {
function XGroupBy(f, xf) {
this.xf = xf;
this.f = f;
this.inputs = {};
}
XGroupBy.prototype['@@transducer/init'] = _xfBase.init;
XGroupBy.prototype['@@transducer/result'] = function (result) {
var key;
for (key in this.inputs) {
if (_has(key, this.inputs)) {
result = this.xf['@@transducer/step'](result, this.inputs[key]);
if (result['@@transducer/reduced']) {
result = result['@@transducer/value'];
break;
}
}
}
return this.xf['@@transducer/result'](result);
};
XGroupBy.prototype['@@transducer/step'] = function (result, input) {
var key = this.f(input);
this.inputs[key] = this.inputs[key] || [
key,
[]
];
this.inputs[key][1] = append(input, this.inputs[key][1]);
return result;
};
return _curry2(function _xgroupBy(f, xf) {
return new XGroupBy(f, xf);
});
}();
/**
* Creates a new list iteration function from an existing one by adding two new parameters
* to its callback function: the current index, and the entire list.
*
* This would turn, for instance, Ramda's simple `map` function into one that more closely
* resembles `Array.prototype.map`. Note that this will only work for functions in which
* the iteration callback function is the first parameter, and where the list is the last
* parameter. (This latter might be unimportant if the list parameter is not used.)
*
* @func
* @memberOf R
* @category Function
* @category List
* @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *)
* @param {Function} fn A list iteration function that does not pass index or list to its callback
* @return {Function} An altered list iteration function that passes (item, index, list) to its callback
* @example
*
* var mapIndexed = R.addIndex(R.map);
* mapIndexed(function(val, idx) {return idx + '-' + val;}, ['f', 'o', 'o', 'b', 'a', 'r']);
* //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
*/
var addIndex = _curry1(function addIndex(fn) {
return curryN(fn.length, function () {
var idx = 0;
var origFn = arguments[0];
var list = arguments[arguments.length - 1];
var args = _slice(arguments);
args[0] = function () {
var result = origFn.apply(this, _concat(arguments, [
idx,
list
]));
idx += 1;
return result;
};
return fn.apply(this, args);
});
});
/**
* Returns `true` if all elements of the list match the predicate, `false` if there are any
* that don't.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is satisfied by every element, `false`
* otherwise.
* @see R.any, R.none
* @example
*
* var lessThan2 = R.flip(R.lt)(2);
* var lessThan3 = R.flip(R.lt)(3);
* R.all(lessThan2)([1, 2]); //=> false
* R.all(lessThan3)([1, 2]); //=> true
*/
var all = _curry2(_dispatchable('all', _xall, function all(fn, list) {
var idx = 0;
while (idx < list.length) {
if (!fn(list[idx])) {
return false;
}
idx += 1;
}
return true;
}));
/**
* A function that returns the first argument if it's falsy otherwise the second
* argument. Note that this is NOT short-circuited, meaning that if expressions
* are passed they are both evaluated.
*
* Dispatches to the `and` method of the first argument if applicable.
*
* @func
* @memberOf R
* @category Logic
* @sig * -> * -> *
* @param {*} a any value
* @param {*} b any other value
* @return {*} the first argument if falsy otherwise the second argument.
* @see R.both
* @example
*
* R.and(false, true); //=> false
* R.and(0, []); //=> 0
* R.and(null, ''); => null
*/
var and = _curry2(function and(a, b) {
return _hasMethod('and', a) ? a.and(b) : a && b;
});
/**
* Returns `true` if at least one of elements of the list match the predicate, `false`
* otherwise.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is satisfied by at least one element, `false`
* otherwise.
* @see R.all, R.none
* @example
*
* var lessThan0 = R.flip(R.lt)(0);
* var lessThan2 = R.flip(R.lt)(2);
* R.any(lessThan0)([1, 2]); //=> false
* R.any(lessThan2)([1, 2]); //=> true
*/
var any = _curry2(_dispatchable('any', _xany, function any(fn, list) {
var idx = 0;
while (idx < list.length) {
if (fn(list[idx])) {
return true;
}
idx += 1;
}
return false;
}));
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 2
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> c) -> (a, b -> c)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 2.
* @example
*
* var takesThreeArgs = function(a, b, c) {
* return [a, b, c];
* };
* takesThreeArgs.length; //=> 3
* takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
*
* var takesTwoArgs = R.binary(takesThreeArgs);
* takesTwoArgs.length; //=> 2
* // Only 2 arguments are passed to the wrapped function
* takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
*/
var binary = _curry1(function binary(fn) {
return nAry(2, fn);
});
/**
* Creates a deep copy of the value which may contain (nested) `Array`s and
* `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are
* not copied, but assigned by their reference.
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> {*}
* @param {*} value The object or array to clone
* @return {*} A new object or array.
* @example
*
* var objects = [{}, {}, {}];
* var objectsClone = R.clone(objects);
* objects[0] === objectsClone[0]; //=> false
*/
var clone = _curry1(function clone(value) {
return _clone(value, [], []);
});
/**
* Returns a new list consisting of the elements of the first list followed by the elements
* of the second.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list to merge.
* @param {Array} list2 The second set to merge.
* @return {Array} A new array consisting of the contents of `list1` followed by the
* contents of `list2`. If, instead of an Array for `list1`, you pass an
* object with a `concat` method on it, `concat` will call `list1.concat`
* and pass it the value of `list2`.
*
* @example
*
* R.concat([], []); //=> []
* R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
* R.concat('ABC', 'DEF'); // 'ABCDEF'
*/
var concat = _curry2(function concat(set1, set2) {
if (_isArray(set2)) {
return _concat(set1, set2);
} else if (_hasMethod('concat', set1)) {
return set1.concat(set2);
} else {
throw new TypeError('can\'t concat ' + typeof set1);
}
});
/**
* Returns a curried equivalent of the provided function. The curried
* function has two unusual capabilities. First, its arguments needn't
* be provided one at a time. If `f` is a ternary function and `g` is
* `R.curry(f)`, the following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value `R.__` may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is `R.__`,
* the following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @category Function
* @sig (* -> a) -> (* -> a)
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curryN
* @example
*
* var addFourNumbers = function(a, b, c, d) {
* return a + b + c + d;
* };
*
* var curriedAddFourNumbers = R.curry(addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4); //=> 10
*/
var curry = _curry1(function curry(fn) {
return curryN(fn.length, fn);
});
/**
* Returns a new list containing the last `n` elements of a given list, passing each value
* to the supplied predicate function, skipping elements while the predicate function returns
* `true`. The predicate function is passed one argument: *(value)*.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.takeWhile
* @example
*
* var lteTwo = function(x) {
* return x <= 2;
* };
*
* R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1]
*/
var dropWhile = _curry2(_dispatchable('dropWhile', _xdropWhile, function dropWhile(pred, list) {
var idx = 0, len = list.length;
while (idx < len && pred(list[idx])) {
idx += 1;
}
return _slice(list, idx);
}));
/**
* Returns `true` if its arguments are equivalent, `false` otherwise.
* Dispatches to an `equals` method if present. Handles cyclical data
* structures.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* R.equals(1, 1); //=> true
* R.equals(1, '1'); //=> false
* R.equals([1, 2, 3], [1, 2, 3]); //=> true
*
* var a = {}; a.v = a;
* var b = {}; b.v = b;
* R.equals(a, b); //=> true
*/
var equals = _curry2(function equals(a, b) {
return _hasMethod('equals', a) ? a.equals(b) : _hasMethod('equals', b) ? b.equals(a) : _equals(a, b, [], []);
});
/**
* Returns a new list containing only those items that match a given predicate function.
* The predicate function is passed one argument: *(value)*.
*
* Note that `R.filter` does not skip deleted or unassigned indices, unlike the native
* `Array.prototype.filter` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @see R.reject
* @example
*
* var isEven = function(n) {
* return n % 2 === 0;
* };
* R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
*/
var filter = _curry2(_dispatchable('filter', _xfilter, _filter));
/**
* Returns the first element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.find(R.propEq(2, 'a'))(xs); //=> {a: 2}
* R.find(R.propEq(4, 'a'))(xs); //=> undefined
*/
var find = _curry2(_dispatchable('find', _xfind, function find(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (fn(list[idx])) {
return list[idx];
}
idx += 1;
}
}));
/**
* Returns the index of the first element of the list which matches the predicate, or `-1`
* if no element matches.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.findIndex(R.propEq(2, 'a'))(xs); //=> 1
* R.findIndex(R.propEq(4, 'a'))(xs); //=> -1
*/
var findIndex = _curry2(_dispatchable('findIndex', _xfindIndex, function findIndex(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (fn(list[idx])) {
return idx;
}
idx += 1;
}
return -1;
}));
/**
* Returns the last element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLast(R.propEq(1, 'a'))(xs); //=> {a: 1, b: 1}
* R.findLast(R.propEq(4, 'a'))(xs); //=> undefined
*/
var findLast = _curry2(_dispatchable('findLast', _xfindLast, function findLast(fn, list) {
var idx = list.length - 1;
while (idx >= 0) {
if (fn(list[idx])) {
return list[idx];
}
idx -= 1;
}
}));
/**
* Returns the index of the last element of the list which matches the predicate, or
* `-1` if no element matches.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLastIndex(R.propEq(1, 'a'))(xs); //=> 1
* R.findLastIndex(R.propEq(4, 'a'))(xs); //=> -1
*/
var findLastIndex = _curry2(_dispatchable('findLastIndex', _xfindLastIndex, function findLastIndex(fn, list) {
var idx = list.length - 1;
while (idx >= 0) {
if (fn(list[idx])) {
return idx;
}
idx -= 1;
}
return -1;
}));
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
* them in a new array, depth-first.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @see R.unnest
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
var flatten = _curry1(_makeFlat(true));
/**
* Returns a new function much like the supplied one, except that the first two arguments'
* order is reversed.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z)
* @param {Function} fn The function to invoke with its first two parameters reversed.
* @return {*} The result of invoking `fn` with its first two parameters' order reversed.
* @example
*
* var mergeThree = function(a, b, c) {
* return ([]).concat(a, b, c);
* };
*
* mergeThree(1, 2, 3); //=> [1, 2, 3]
*
* R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
*/
var flip = _curry1(function flip(fn) {
return curry(function (a, b) {
var args = _slice(arguments);
args[0] = b;
args[1] = a;
return fn.apply(this, args);
});
});
/**
* Iterate over an input `list`, calling a provided function `fn` for each element in the
* list.
*
* `fn` receives one argument: *(value)*.
*
* Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.forEach` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
* array. In some libraries this function is named `each`.
*
* @func
* @memberOf R
* @category List
* @sig (a -> *) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives one argument, `value`.
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @example
*
* var printXPlusFive = function(x) { console.log(x + 5); };
* R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
* //-> 6
* //-> 7
* //-> 8
*/
var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) {
var len = list.length;
var idx = 0;
while (idx < len) {
fn(list[idx]);
idx += 1;
}
return list;
}));
/**
* Returns a list of function names of object's own functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} A list of the object's own properties that map to functions.
* @example
*
* R.functions(R); // returns list of ramda's own function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functions(new F()); //=> ["x"]
*/
var functions = _curry1(_functionsWith(keys));
/**
* Returns a list of function names of object's own and prototype functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} A list of the object's own properties and prototype
* properties that map to functions.
* @example
*
* R.functionsIn(R); // returns list of ramda's own and prototype function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functionsIn(new F()); //=> ["x", "z"]
*/
var functionsIn = _curry1(_functionsWith(keysIn));
/**
* Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function
* on each element, and grouping the results according to values returned.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> String) -> [a] -> {String: [a]}
* @param {Function} fn Function :: a -> String
* @param {Array} list The array to group
* @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
* that produced that key when passed to `fn`.
* @example
*
* var byGrade = R.groupBy(function(student) {
* var score = student.score;
* return score < 65 ? 'F' :
* score < 70 ? 'D' :
* score < 80 ? 'C' :
* score < 90 ? 'B' : 'A';
* });
* var students = [{name: 'Abby', score: 84},
* {name: 'Eddy', score: 58},
* // ...
* {name: 'Jack', score: 69}];
* byGrade(students);
* // {
* // 'A': [{name: 'Dianne', score: 99}],
* // 'B': [{name: 'Abby', score: 84}]
* // // ...,
* // 'F': [{name: 'Eddy', score: 58}]
* // }
*/
var groupBy = _curry2(_dispatchable('groupBy', _xgroupBy, function groupBy(fn, list) {
return _reduce(function (acc, elt) {
var key = fn(elt);
acc[key] = append(elt, acc[key] || (acc[key] = []));
return acc;
}, {}, list);
}));
/**
* Returns the first element of the given list or string. In some libraries
* this function is named `first`.
*
* @func
* @memberOf R
* @category List
* @see R.tail, R.init, R.last
* @sig [a] -> a | Undefined
* @sig String -> String
* @param {*} list
* @return {*}
* @example
*
* R.head(['fi', 'fo', 'fum']); //=> 'fi'
* R.head([]); //=> undefined
*
* R.head('abc'); //=> 'a'
* R.head(''); //=> ''
*/
var head = nth(0);
/**
* Combines two lists into a set (i.e. no duplicates) composed of those
* elements common to both lists. Duplication is determined according
* to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category Relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate function that determines whether
* the two supplied elements are equal.
* @param {Array} list1 One list of items to compare
* @param {Array} list2 A second list of items to compare
* @see R.intersection
* @return {Array} A new list containing those elements common to both lists.
* @example
*
* var buffaloSpringfield = [
* {id: 824, name: 'Richie Furay'},
* {id: 956, name: 'Dewey Martin'},
* {id: 313, name: 'Bruce Palmer'},
* {id: 456, name: 'Stephen Stills'},
* {id: 177, name: 'Neil Young'}
* ];
* var csny = [
* {id: 204, name: 'David Crosby'},
* {id: 456, name: 'Stephen Stills'},
* {id: 539, name: 'Graham Nash'},
* {id: 177, name: 'Neil Young'}
* ];
*
* var sameId = function(o1, o2) {return o1.id === o2.id;};
*
* R.intersectionWith(sameId, buffaloSpringfield, csny);
* //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
*/
var intersectionWith = _curry3(function intersectionWith(pred, list1, list2) {
var results = [], idx = 0;
while (idx < list1.length) {
if (_containsWith(pred, list1[idx], list2)) {
results[results.length] = list1[idx];
}
idx += 1;
}
return uniqWith(pred, results);
});
/**
* Creates a new list with the separator interposed between elements.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> [a]
* @param {*} separator The element to add to the list.
* @param {Array} list The list to be interposed.
* @return {Array} The new list.
* @example
*
* R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
*/
var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) {
var out = [];
var idx = 0;
var length = list.length;
while (idx < length) {
if (idx === length - 1) {
out.push(list[idx]);
} else {
out.push(list[idx], separator);
}
idx += 1;
}
return out;
}));
/**
* Transforms the items of the list with the transducer and appends the transformed items to
* the accumulator using an appropriate iterator function based on the accumulator type.
*
* The accumulator can be an array, string, object or a transformer. Iterated items will
* be appended to arrays and concatenated to strings. Objects will be merged directly or 2-item
* arrays will be merged as key, value pairs.
*
* The accumulator can also be a transformer object that provides a 2-arity reducing iterator
* function, step, 0-arity initial value function, init, and 1-arity result extraction function
* result. The step function is used as the iterator function in reduce. The result function is
* used to convert the final accumulator into the return type and in most cases is R.identity.
* The init function is used to provide the initial accumulator.
*
* The iteration is performed with R.reduce after initializing the transducer.
*
* @func
* @memberOf R
* @category List
* @sig a -> (b -> b) -> [c] -> a
* @param {*} acc The initial accumulator value.
* @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3, 4];
* var transducer = R.compose(R.map(R.add(1)), R.take(2));
*
* R.into([], transducer, numbers); //=> [2, 3]
*
* var intoArray = R.into([]);
* intoArray(transducer, numbers); //=> [2, 3]
*/
var into = _curry3(function into(acc, xf, list) {
return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), acc, list);
});
/**
* Same as R.invertObj, however this accounts for objects
* with duplicate values by putting the values into an
* array.
*
* @func
* @memberOf R
* @category Object
* @sig {s: x} -> {x: [ s, ... ]}
* @param {Object} obj The object or array to invert
* @return {Object} out A new object with keys
* in an array.
* @example
*
* var raceResultsByFirstName = {
* first: 'alice',
* second: 'jake',
* third: 'alice',
* };
* R.invert(raceResultsByFirstName);
* //=> { 'alice': ['first', 'third'], 'jake':['second'] }
*/
var invert = _curry1(function invert(obj) {
var props = keys(obj);
var len = props.length;
var idx = 0;
var out = {};
while (idx < len) {
var key = props[idx];
var val = obj[key];
var list = _has(val, out) ? out[val] : out[val] = [];
list[list.length] = key;
idx += 1;
}
return out;
});
/**
* Returns a new object with the keys of the given object
* as values, and the values of the given object as keys.
*
* @func
* @memberOf R
* @category Object
* @sig {s: x} -> {x: s}
* @param {Object} obj The object or array to invert
* @return {Object} out A new object
* @example
*
* var raceResults = {
* first: 'alice',
* second: 'jake'
* };
* R.invertObj(raceResults);
* //=> { 'alice': 'first', 'jake':'second' }
*
* // Alternatively:
* var raceResults = ['alice', 'jake'];
* R.invertObj(raceResults);
* //=> { 'alice': '0', 'jake':'1' }
*/
var invertObj = _curry1(function invertObj(obj) {
var props = keys(obj);
var len = props.length;
var idx = 0;
var out = {};
while (idx < len) {
var key = props[idx];
out[obj[key]] = key;
idx += 1;
}
return out;
});
/**
* Returns the last element of the given list or string.
*
* @func
* @memberOf R
* @category List
* @see R.init, R.head, R.tail
* @sig [a] -> a | Undefined
* @sig String -> String
* @param {*} list
* @return {*}
* @example
*
* R.last(['fi', 'fo', 'fum']); //=> 'fum'
* R.last([]); //=> undefined
*
* R.last('abc'); //=> 'c'
* R.last(''); //=> ''
*/
var last = nth(-1);
/**
* Returns the position of the last occurrence of an item in
* an array, or -1 if the item is not included in the array.
* `R.equals` is used to determine equality.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} xs The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
* @see R.indexOf
* @example
*
* R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
* R.lastIndexOf(10, [1,2,3,4]); //=> -1
*/
var lastIndexOf = _curry2(function lastIndexOf(target, xs) {
if (_hasMethod('lastIndexOf', xs)) {
return xs.lastIndexOf(target);
} else {
var idx = xs.length - 1;
while (idx >= 0) {
if (equals(xs[idx], target)) {
return idx;
}
idx -= 1;
}
return -1;
}
});
/**
* Returns a new list, constructed by applying the supplied function to every element of the
* supplied list.
*
* Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the
* native `Array.prototype.map` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> b) -> [a] -> [b]
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @example
*
* var double = function(x) {
* return x * 2;
* };
*
* R.map(double, [1, 2, 3]); //=> [2, 4, 6]
*/
var map = _curry2(_dispatchable('map', _xmap, _map));
/**
* Map, but for objects. Creates an object with the same keys as `obj` and values
* generated by running each property of `obj` through `fn`. `fn` is passed one argument:
* *(value)*.
*
* @func
* @memberOf R
* @category Object
* @sig (v -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var double = function(num) {
* return num * 2;
* };
*
* R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 }
*/
var mapObj = _curry2(function mapObj(fn, obj) {
return _reduce(function (acc, key) {
acc[key] = fn(obj[key]);
return acc;
}, {}, keys(obj));
});
/**
* Like `mapObj`, but but passes additional arguments to the predicate function. The
* predicate function is passed three arguments: *(value, key, obj)*.
*
* @func
* @memberOf R
* @category Object
* @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var prependKeyAndDouble = function(num, key, obj) {
* return key + (num * 2);
* };
*
* R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
*/
var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) {
return _reduce(function (acc, key) {
acc[key] = fn(obj[key], key, obj);
return acc;
}, {}, keys(obj));
});
/**
* Returns `true` if no elements of the list match the predicate,
* `false` otherwise.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise.
* @see R.all, R.any
* @example
*
* R.none(R.isNaN, [1, 2, 3]); //=> true
* R.none(R.isNaN, [1, 2, 3, NaN]); //=> false
*/
var none = _curry2(_complement(_dispatchable('any', _xany, any)));
/**
* A function that returns the first truthy of two arguments otherwise the
* last argument. Note that this is NOT short-circuited, meaning that if
* expressions are passed they are both evaluated.
*
* Dispatches to the `or` method of the first argument if applicable.
*
* @func
* @memberOf R
* @category Logic
* @sig * -> * -> *
* @param {*} a any value
* @param {*} b any other value
* @return {*} the first truthy argument, otherwise the last argument.
* @see R.either
* @example
*
* R.or(false, true); //=> true
* R.or(0, []); //=> []
* R.or(null, ''); => ''
*/
var or = _curry2(function or(a, b) {
return _hasMethod('or', a) ? a.or(b) : a || b;
});
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values prepended to the
* original function's arguments list. In some libraries this function is named `applyLeft`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn`
* with `args` prepended to `fn`'s arguments list.
* @example
*
* var multiply = function(a, b) { return a * b; };
* var double = R.partial(multiply, 2);
* double(2); //=> 4
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var sayHello = R.partial(greet, 'Hello');
* var sayHelloToMs = R.partial(sayHello, 'Ms.');
* sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
*/
var partial = curry(_createPartialApplicator(_concat));
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values appended to the original
* function's arguments list.
*
* Note that `partialRight` is the opposite of `partial`: `partialRight` fills `fn`'s arguments
* from the right to the left. In some libraries this function is named `applyRight`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to append to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with
* `args` appended to `fn`'s arguments list.
* @example
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones');
*
* greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
*/
var partialRight = curry(_createPartialApplicator(flip(_concat)));
/**
* Takes a predicate and a list and returns the pair of lists of
* elements which do and do not satisfy the predicate, respectively.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [[a],[a]]
* @param {Function} pred A predicate to determine which array the element belongs to.
* @param {Array} list The array to partition.
* @return {Array} A nested array, containing first an array of elements that satisfied the predicate,
* and second an array of elements that did not satisfy.
* @example
*
* R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
* //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
*/
var partition = _curry2(function partition(pred, list) {
return _reduce(function (acc, elt) {
var xs = acc[pred(elt) ? 0 : 1];
xs[xs.length] = elt;
return acc;
}, [
[],
[]
], list);
});
/**
* Determines whether a nested path on an object has a specific value,
* in `R.equals` terms. Most likely used to filter a list.
*
* @func
* @memberOf R
* @category Relation
* @sig [String] -> * -> {String: *} -> Boolean
* @param {Array} path The path of the nested property to use
* @param {*} val The value to compare the nested property with
* @param {Object} obj The object to check the nested property in
* @return {Boolean} `true` if the value equals the nested object property,
* `false` otherwise.
* @example
*
* var user1 = { address: { zipCode: 90210 } };
* var user2 = { address: { zipCode: 55555 } };
* var user3 = { name: 'Bob' };
* var users = [ user1, user2, user3 ];
* var isFamous = R.pathEq(['address', 'zipCode'], 90210);
* R.filter(isFamous, users); //=> [ user1 ]
*/
var pathEq = _curry3(function pathEq(_path, val, obj) {
return equals(path(_path, obj), val);
});
/**
* Returns a new list by plucking the same named property off all objects in the list supplied.
*
* @func
* @memberOf R
* @category List
* @sig k -> [{k: v}] -> [v]
* @param {Number|String} key The key name to pluck off of each object.
* @param {Array} list The array to consider.
* @return {Array} The list of values for the given key.
* @example
*
* R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
* R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
*/
var pluck = _curry2(function pluck(p, list) {
return map(prop(p), list);
});
/**
* Returns `true` if the specified object property is equal, in `R.equals`
* terms, to the given value; `false` otherwise.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> String -> Object -> Boolean
* @param {*} val
* @param {String} name
* @param {*} obj
* @return {Boolean}
* @see R.equals
* @see R.propSatisfies
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond'};
* var fred = {name: 'Fred', age: 12, hair: 'brown'};
* var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
* var alois = {name: 'Alois', age: 15, disposition: 'surly'};
* var kids = [abby, fred, rusty, alois];
* var hasBrownHair = R.propEq('brown', 'hair');
* R.filter(hasBrownHair, kids); //=> [fred, rusty]
*/
var propEq = _curry3(function propEq(val, name, obj) {
return propSatisfies(equals(val), name, obj);
});
/**
* Returns `true` if the specified object property is of the given type;
* `false` otherwise.
*
* @func
* @memberOf R
* @category Type
* @sig Type -> String -> Object -> Boolean
* @param {Function} type
* @param {String} name
* @param {*} obj
* @return {Boolean}
* @see R.is
* @see R.propSatisfies
* @example
*
* R.propIs(Number, 'x', {x: 1, y: 2}); //=> true
* R.propIs(Number, 'x', {x: 'foo'}); //=> false
* R.propIs(Number, 'x', {}); //=> false
*/
var propIs = _curry3(function propIs(type, name, obj) {
return propSatisfies(is(type), name, obj);
});
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*. It may use `R.reduced` to
* shortcut the iteration.
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
* @see R.reduced
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3];
* var add = function(a, b) {
* return a + b;
* };
*
* R.reduce(add, 10, numbers); //=> 16
*/
var reduce = _curry3(_reduce);
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @see R.filter
* @example
*
* var isOdd = function(n) {
* return n % 2 === 1;
* };
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*/
var reject = _curry2(function reject(fn, list) {
return filter(_complement(fn), list);
});
/**
* Returns a fixed list of size `n` containing a specified identical value.
*
* @func
* @memberOf R
* @category List
* @sig a -> n -> [a]
* @param {*} value The value to repeat.
* @param {Number} n The desired size of the output list.
* @return {Array} A new array containing `n` `value`s.
* @example
*
* R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
*
* var obj = {};
* var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}]
* repeatedObjs[0] === repeatedObjs[1]; //=> true
*/
var repeat = _curry2(function repeat(value, n) {
return times(always(value), n);
});
/**
* Returns the elements of the given list or string (or object with a `slice`
* method) from `fromIndex` (inclusive) to `toIndex` (exclusive).
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @sig Number -> Number -> String -> String
* @param {Number} fromIndex The start index (inclusive).
* @param {Number} toIndex The end index (exclusive).
* @param {*} list
* @return {*}
* @example
*
* R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']
* R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']
* R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(0, 3, 'ramda'); //=> 'ram'
*/
var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) {
return Array.prototype.slice.call(list, fromIndex, toIndex);
}));
/**
* Splits a collection into slices of the specified length.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [[a]]
* @sig Number -> String -> [String]
* @param {Number} n
* @param {Array} list
* @return {Array}
* @example
*
* R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]]
* R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz']
*/
var splitEvery = _curry2(function splitEvery(n, list) {
if (n <= 0) {
throw new Error('First argument to splitEvery must be a positive integer');
}
var result = [];
var idx = 0;
while (idx < list.length) {
result.push(slice(idx, idx += n, list));
}
return result;
});
/**
* Adds together all the elements of a list.
*
* @func
* @memberOf R
* @category Math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {Number} The sum of all the numbers in the list.
* @see R.reduce
* @example
*
* R.sum([2,4,6,8,100,1]); //=> 121
*/
var sum = reduce(add, 0);
/**
* Returns all but the first element of the given list or string (or object
* with a `tail` method).
*
* @func
* @memberOf R
* @category List
* @see R.head, R.init, R.last
* @sig [a] -> [a]
* @sig String -> String
* @param {*} list
* @return {*}
* @example
*
* R.tail([1, 2, 3]); //=> [2, 3]
* R.tail([1, 2]); //=> [2]
* R.tail([1]); //=> []
* R.tail([]); //=> []
*
* R.tail('abc'); //=> 'bc'
* R.tail('ab'); //=> 'b'
* R.tail('a'); //=> ''
* R.tail(''); //=> ''
*/
var tail = _checkForMethod('tail', slice(1, Infinity));
/**
* Returns the first `n` elements of the given list, string, or
* transducer/transformer (or object with a `take` method).
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n
* @param {*} list
* @return {*}
* @see R.drop
* @example
*
* R.take(1, ['foo', 'bar', 'baz']); //=> ['foo']
* R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
* R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.take(3, 'ramda'); //=> 'ram'
*
* var personnel = [
* 'Dave Brubeck',
* 'Paul Desmond',
* 'Eugene Wright',
* 'Joe Morello',
* 'Gerry Mulligan',
* 'Bob Bates',
* 'Joe Dodge',
* 'Ron Crotty'
* ];
*
* var takeFive = R.take(5);
* takeFive(personnel);
* //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']
*/
var take = _curry2(_dispatchable('take', _xtake, function take(n, xs) {
return slice(0, n < 0 ? Infinity : n, xs);
}));
/**
* Returns a new list containing the first `n` elements of a given list, passing each value
* to the supplied predicate function, and terminating when the predicate function returns
* `false`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.dropWhile
* @example
*
* var isNotFour = function(x) {
* return !(x === 4);
* };
*
* R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3]
*/
var takeWhile = _curry2(_dispatchable('takeWhile', _xtakeWhile, function takeWhile(fn, list) {
var idx = 0, len = list.length;
while (idx < len && fn(list[idx])) {
idx += 1;
}
return _slice(list, 0, idx);
}));
/**
* Initializes a transducer using supplied iterator function. Returns a single item by
* iterating through the list, successively calling the transformed iterator function and
* passing it an accumulator value and the current value from the array, and then passing
* the result to the next call.
*
* The iterator function receives two values: *(acc, value)*. It will be wrapped as a
* transformer to initialize the transducer. A transformer can be passed directly in place
* of an iterator function. In both cases, iteration may be stopped early with the
* `R.reduced` function.
*
* A transducer is a function that accepts a transformer and returns a transformer and can
* be composed directly.
*
* A transformer is an an object that provides a 2-arity reducing iterator function, step,
* 0-arity initial value function, init, and 1-arity result extraction function, result.
* The step function is used as the iterator function in reduce. The result function is used
* to convert the final accumulator into the return type and in most cases is R.identity.
* The init function can be used to provide an initial accumulator, but is ignored by transduce.
*
* The iteration is performed with R.reduce after initializing the transducer.
*
* @func
* @memberOf R
* @category List
* @see R.reduce, R.reduced, R.into
* @sig (c -> c) -> (a,b -> a) -> a -> [b] -> a
* @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array. Wrapped as transformer, if necessary, and used to
* initialize the transducer
* @param {*} acc The initial accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3, 4];
* var transducer = R.compose(R.map(R.add(1)), R.take(2));
*
* R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
*/
var transduce = curryN(4, function transduce(xf, fn, acc, list) {
return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list);
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is
* determined according to the value returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @category Relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @see R.union
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}];
* var l2 = [{a: 1}, {a: 4}];
* R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
*/
var unionWith = _curry3(function unionWith(pred, list1, list2) {
return uniqWith(pred, _concat(list1, list2));
});
/**
* Returns a new list containing only one copy of each element in the original list.
* `R.equals` is used to determine equality.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniq([1, 1, 2, 1]); //=> [1, 2]
* R.uniq([1, '1']); //=> [1, '1']
* R.uniq([[42], [42]]); //=> [[42]]
*/
var uniq = uniqWith(equals);
/**
* Returns a new list by pulling every item at the first level of nesting out, and putting
* them in a new array.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @see R.flatten
* @example
*
* R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
* R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
*/
var unnest = _curry1(_makeFlat(false));
/**
* Accepts a function `fn` and any number of transformer functions and returns a new
* function. When the new function is invoked, it calls the function `fn` with parameters
* consisting of the result of calling each supplied handler on successive arguments to the
* new function.
*
* If more arguments are passed to the returned function than transformer functions, those
* arguments are passed directly to `fn` as additional parameters. If you expect additional
* arguments that don't need to be transformed, although you can ignore them, it's best to
* pass an identity function so that the new function reports the correct arity.
*
* @func
* @memberOf R
* @category Function
* @sig (x1 -> x2 -> ... -> z) -> ((a -> x1), (b -> x2), ...) -> (a -> b -> ... -> z)
* @param {Function} fn The function to wrap.
* @param {...Function} transformers A variable number of transformer functions
* @return {Function} The wrapped function.
* @example
*
* var double = function(y) { return y * 2; };
* var square = function(x) { return x * x; };
* var add = function(a, b) { return a + b; };
* // Adds any number of arguments together
* var addAll = function() {
* return R.reduce(add, 0, arguments);
* };
*
* // Basic example
* var addDoubleAndSquare = R.useWith(addAll, double, square);
*
* //≅ addAll(double(10), square(5));
* addDoubleAndSquare(10, 5); //=> 45
*
* // Example of passing more arguments than transformers
* //≅ addAll(double(10), square(5), 100);
* addDoubleAndSquare(10, 5, 100); //=> 145
*
* // If there are extra _expected_ arguments that don't need to be transformed, although
* // you can ignore them, it might be best to pass in the identity function so that the new
* // function correctly reports arity.
* var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity);
* // addDoubleAndSquareWithExtraParams.length //=> 3
* //≅ addAll(double(10), square(5), R.identity(100));
* addDoubleAndSquare(10, 5, 100); //=> 145
*/
/*, transformers */
var useWith = curry(function useWith(fn) {
var transformers = _slice(arguments, 1);
var tlen = transformers.length;
return curry(_arity(tlen, function () {
var args = [], idx = 0;
while (idx < tlen) {
args[idx] = transformers[idx](arguments[idx]);
idx += 1;
}
return fn.apply(this, args.concat(_slice(arguments, tlen)));
}));
});
/**
* Takes a spec object and a test object; returns true if the test satisfies
* the spec, false otherwise. An object satisfies the spec if, for each of the
* spec's own properties, accessing that property of the object gives the same
* value (in `R.equals` terms) as accessing that property of the spec.
*
* `whereEq` is a specialization of [`where`](#where).
*
* @func
* @memberOf R
* @category Object
* @sig {String: *} -> {String: *} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @see R.where
* @example
*
* // pred :: Object -> Boolean
* var pred = R.whereEq({a: 1, b: 2});
*
* pred({a: 1}); //=> false
* pred({a: 1, b: 2}); //=> true
* pred({a: 1, b: 2, c: 3}); //=> true
* pred({a: 1, b: 1}); //=> false
*/
var whereEq = _curry2(function whereEq(spec, testObj) {
return where(mapObj(equals, spec), testObj);
});
var _flatCat = function () {
var preservingReduced = function (xf) {
return {
'@@transducer/init': _xfBase.init,
'@@transducer/result': function (result) {
return xf['@@transducer/result'](result);
},
'@@transducer/step': function (result, input) {
var ret = xf['@@transducer/step'](result, input);
return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret;
}
};
};
return function _xcat(xf) {
var rxf = preservingReduced(xf);
return {
'@@transducer/init': _xfBase.init,
'@@transducer/result': function (result) {
return rxf['@@transducer/result'](result);
},
'@@transducer/step': function (result, input) {
return !isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input);
}
};
};
}();
var _indexOf = function _indexOf(list, item, from) {
var idx = from;
while (idx < list.length) {
if (equals(list[idx], item)) {
return idx;
}
idx += 1;
}
return -1;
};
/**
* Create a predicate wrapper which will call a pick function (all/any) for each predicate
*
* @private
* @see R.all
* @see R.any
*/
// Call function immediately if given arguments
// Return a function which will call the predicates with the provided arguments
var _predicateWrap = function _predicateWrap(predPicker) {
return function (preds) {
var predIterator = function () {
var args = arguments;
return predPicker(function (predicate) {
return predicate.apply(null, args);
}, preds);
};
return arguments.length > 1 ? // Call function immediately if given arguments
predIterator.apply(null, _slice(arguments, 1)) : // Return a function which will call the predicates with the provided arguments
_arity(Math.max.apply(Math, pluck('length', preds)), predIterator);
};
};
var _xchain = _curry2(function _xchain(f, xf) {
return map(f, _flatCat(xf));
});
/**
* Given a list of predicates, returns a new predicate that will be true exactly when all of them are.
*
* @func
* @memberOf R
* @category Logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} a function that applies its arguments to each of
* the predicates, returning `true` if all are satisfied.
* @see R.anyPass
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.allPass([gt10, even]);
* f(11); //=> false
* f(12); //=> true
*/
var allPass = _curry1(_predicateWrap(all));
/**
* Given a list of predicates returns a new predicate that will be true exactly when any one of them is.
*
* @func
* @memberOf R
* @category Logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} A function that applies its arguments to each of the predicates, returning
* `true` if all are satisfied.
* @see R.allPass
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.anyPass([gt10, even]);
* f(11); //=> true
* f(8); //=> true
* f(9); //=> false
*/
var anyPass = _curry1(_predicateWrap(any));
/**
* ap applies a list of functions to a list of values.
*
* @func
* @memberOf R
* @category Function
* @sig [f] -> [a] -> [f a]
* @param {Array} fns An array of functions
* @param {Array} vs An array of values
* @return {Array} An array of results of applying each of `fns` to all of `vs` in turn.
* @example
*
* R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
*/
var ap = _curry2(function ap(fns, vs) {
return _hasMethod('ap', fns) ? fns.ap(vs) : _reduce(function (acc, fn) {
return _concat(acc, map(fn, vs));
}, [], fns);
});
/**
* Returns the result of calling its first argument with the remaining
* arguments. This is occasionally useful as a converging function for
* `R.converge`: the left branch can produce a function while the right
* branch produces a value to be passed to that function as an argument.
*
* @func
* @memberOf R
* @category Function
* @sig (*... -> a),*... -> a
* @param {Function} fn The function to apply to the remaining arguments.
* @param {...*} args Any number of positional arguments.
* @return {*}
* @see R.apply
* @example
*
* var indentN = R.pipe(R.times(R.always(' ')),
* R.join(''),
* R.replace(/^(?!$)/gm));
*
* var format = R.converge(R.call,
* R.pipe(R.prop('indent'), indentN),
* R.prop('value'));
*
* format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n'
*/
var call = curry(function call(fn) {
return fn.apply(this, _slice(arguments, 1));
});
/**
* `chain` maps a function over a list and concatenates the results.
* This implementation is compatible with the
* Fantasy-land Chain spec, and will work with types that implement that spec.
* `chain` is also known as `flatMap` in some libraries
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> [a] -> [b]
* @param {Function} fn
* @param {Array} list
* @return {Array}
* @example
*
* var duplicate = function(n) {
* return [n, n];
* };
* R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
*/
var chain = _curry2(_dispatchable('chain', _xchain, function chain(fn, list) {
return unnest(map(fn, list));
}));
/**
* Turns a list of Functors into a Functor of a list, applying
* a mapping function to the elements of the list along the way.
*
* @func
* @memberOf R
* @category List
* @see R.commute
* @sig Functor f => (f a -> f b) -> (x -> f x) -> [f a] -> f [b]
* @param {Function} fn The transformation function
* @param {Function} of A function that returns the data type to return
* @param {Array} list An array of functors of the same type
* @return {*}
* @example
*
* R.commuteMap(R.map(R.add(10)), R.of, [[1], [2, 3]]); //=> [[11, 12], [11, 13]]
* R.commuteMap(R.map(R.add(10)), R.of, [[1, 2], [3]]); //=> [[11, 13], [12, 13]]
* R.commuteMap(R.map(R.add(10)), R.of, [[1], [2], [3]]); //=> [[11, 12, 13]]
* R.commuteMap(R.map(R.add(10)), Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([11, 12, 13])
* R.commuteMap(R.map(R.add(10)), Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
*/
var commuteMap = _curry3(function commuteMap(fn, of, list) {
function consF(acc, ftor) {
return ap(map(append, fn(ftor)), acc);
}
return _reduce(consF, of([]), list);
});
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type. The arity of the function returned is specified
* to allow using variadic constructor functions.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> {*}) -> (* -> {*})
* @param {Number} n The arity of the constructor function.
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Variadic constructor function
* var Widget = function() {
* this.children = Array.prototype.slice.call(arguments);
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = [
* // ...
* ];
* R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
*/
var constructN = _curry2(function constructN(n, Fn) {
if (n > 10) {
throw new Error('Constructor with greater than ten arguments');
}
if (n === 0) {
return function () {
return new Fn();
};
}
return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
switch (arguments.length) {
case 1:
return new Fn($0);
case 2:
return new Fn($0, $1);
case 3:
return new Fn($0, $1, $2);
case 4:
return new Fn($0, $1, $2, $3);
case 5:
return new Fn($0, $1, $2, $3, $4);
case 6:
return new Fn($0, $1, $2, $3, $4, $5);
case 7:
return new Fn($0, $1, $2, $3, $4, $5, $6);
case 8:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7);
case 9:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8);
case 10:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
}
}));
});
/**
* Accepts at least three functions and returns a new function. When invoked, this new
* function will invoke the first function, `after`, passing as its arguments the
* results of invoking the subsequent functions with whatever arguments are passed to
* the new function.
*
* @func
* @memberOf R
* @category Function
* @sig (x1 -> x2 -> ... -> z) -> ((a -> b -> ... -> x1), (a -> b -> ... -> x2), ...) -> (a -> b -> ... -> z)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {...Function} functions A variable number of functions.
* @return {Function} A new function.
* @example
*
* var add = function(a, b) { return a + b; };
* var multiply = function(a, b) { return a * b; };
* var subtract = function(a, b) { return a - b; };
*
* //≅ multiply( add(1, 2), subtract(1, 2) );
* R.converge(multiply, add, subtract)(1, 2); //=> -3
*
* var add3 = function(a, b, c) { return a + b + c; };
* R.converge(add3, multiply, add, subtract)(1, 2); //=> 4
*/
var converge = curryN(3, function converge(after) {
var fns = _slice(arguments, 1);
return curryN(Math.max.apply(Math, pluck('length', fns)), function () {
var args = arguments;
var context = this;
return after.apply(context, _map(function (fn) {
return fn.apply(context, args);
}, fns));
});
});
/**
* Returns all but the first `n` elements of the given list, string, or
* transducer/transformer (or object with a `drop` method).
*
* @func
* @memberOf R
* @category List
* @see R.transduce
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n
* @param {*} list
* @return {*}
* @see R.take
* @example
*
* R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
* R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz']
* R.drop(3, ['foo', 'bar', 'baz']); //=> []
* R.drop(4, ['foo', 'bar', 'baz']); //=> []
* R.drop(3, 'ramda'); //=> 'da'
*/
var drop = _curry2(_dispatchable('drop', _xdrop, function drop(n, xs) {
return slice(Math.max(0, n), Infinity, xs);
}));
/**
* Returns a list containing all but the last `n` elements of the given `list`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n The number of elements of `xs` to skip.
* @param {Array} xs The collection to consider.
* @return {Array}
* @see R.takeLast
* @example
*
* R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
* R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo']
* R.dropLast(3, ['foo', 'bar', 'baz']); //=> []
* R.dropLast(4, ['foo', 'bar', 'baz']); //=> []
* R.dropLast(3, 'ramda'); //=> 'ra'
*/
var dropLast = _curry2(function dropLast(n, xs) {
return take(n < xs.length ? xs.length - n : 0, xs);
});
/**
* Returns a new list without any consecutively repeating elements. Equality is
* determined by applying the supplied predicate two consecutive elements.
* The first element in a series of equal element is the one being preserved.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a, a -> Boolean) -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list The array to consider.
* @return {Array} `list` without repeating elements.
* @example
*
* function lengthEq(x, y) { return Math.abs(x) === Math.abs(y); };
* var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];
* R.dropRepeatsWith(lengthEq, l); //=> [1, 3, 4, -5, 3]
*/
var dropRepeatsWith = _curry2(_dispatchable('dropRepeatsWith', _xdropRepeatsWith, function dropRepeatsWith(pred, list) {
var result = [];
var idx = 1;
var len = list.length;
if (len !== 0) {
result[0] = list[0];
while (idx < len) {
if (!pred(last(result), list[idx])) {
result[result.length] = list[idx];
}
idx += 1;
}
}
return result;
}));
/**
* Reports whether two objects have the same value, in `R.equals` terms,
* for the specified property. Useful as a curried predicate.
*
* @func
* @memberOf R
* @category Object
* @sig k -> {k: v} -> {k: v} -> Boolean
* @param {String} prop The name of the property to compare
* @param {Object} obj1
* @param {Object} obj2
* @return {Boolean}
*
* @example
*
* var o1 = { a: 1, b: 2, c: 3, d: 4 };
* var o2 = { a: 10, b: 20, c: 3, d: 40 };
* R.eqProps('a', o1, o2); //=> false
* R.eqProps('c', o1, o2); //=> true
*/
var eqProps = _curry3(function eqProps(prop, obj1, obj2) {
return equals(obj1[prop], obj2[prop]);
});
/**
* Returns the position of the first occurrence of an item in an array,
* or -1 if the item is not included in the array. `R.equals` is used to
* determine equality.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} xs The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
* @see R.lastIndexOf
* @example
*
* R.indexOf(3, [1,2,3,4]); //=> 2
* R.indexOf(10, [1,2,3,4]); //=> -1
*/
var indexOf = _curry2(function indexOf(target, xs) {
return _hasMethod('indexOf', xs) ? xs.indexOf(target) : _indexOf(xs, target, 0);
});
/**
* Returns all but the last element of the given list or string.
*
* @func
* @memberOf R
* @category List
* @see R.last, R.head, R.tail
* @sig [a] -> [a]
* @sig String -> String
* @param {*} list
* @return {*}
* @example
*
* R.init([1, 2, 3]); //=> [1, 2]
* R.init([1, 2]); //=> [1]
* R.init([1]); //=> []
* R.init([]); //=> []
*
* R.init('abc'); //=> 'ab'
* R.init('ab'); //=> 'a'
* R.init('a'); //=> ''
* R.init(''); //=> ''
*/
var init = slice(0, -1);
/**
* Returns `true` if all elements are unique, in `R.equals` terms,
* otherwise `false`.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {Boolean} `true` if all elements are unique, else `false`.
* @example
*
* R.isSet(['1', 1]); //=> true
* R.isSet([1, 1]); //=> false
* R.isSet([[42], [42]]); //=> false
*/
var isSet = _curry1(function isSet(list) {
var len = list.length;
var idx = 0;
while (idx < len) {
if (_indexOf(list, list[idx], idx + 1) >= 0) {
return false;
}
idx += 1;
}
return true;
});
/**
* Returns a lens for the given getter and setter functions. The getter "gets"
* the value of the focus; the setter "sets" the value of the focus. The setter
* should not mutate the data structure.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig (s -> a) -> ((a, s) -> s) -> Lens s a
* @param {Function} getter
* @param {Function} setter
* @return {Lens}
* @see R.view, R.set, R.over, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lens(R.prop('x'), R.assoc('x'));
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
*/
var lens = _curry2(function lens(getter, setter) {
return function (f) {
return function (s) {
return map(function (v) {
return setter(v, s);
}, f(getter(s)));
};
};
});
/**
* Returns a lens whose focus is the specified index.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Number -> Lens s a
* @param {Number} n
* @return {Lens}
* @see R.view, R.set, R.over
* @example
*
* var headLens = R.lensIndex(0);
*
* R.view(headLens, ['a', 'b', 'c']); //=> 'a'
* R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c']
* R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c']
*/
var lensIndex = _curry1(function lensIndex(n) {
return lens(nth(n), update(n));
});
/**
* Returns a lens whose focus is the specified property.
*
* @func
* @memberOf R
* @category Object
* @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig String -> Lens s a
* @param {String} k
* @return {Lens}
* @see R.view, R.set, R.over
* @example
*
* var xLens = R.lensProp('x');
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
*/
var lensProp = _curry1(function lensProp(k) {
return lens(prop(k), assoc(k));
});
/**
* "lifts" a function to be the specified arity, so that it may "map over" that many
* lists (or other Functors).
*
* @func
* @memberOf R
* @see R.lift
* @category Function
* @sig Number -> (*... -> *) -> ([*]... -> [*])
* @param {Function} fn The function to lift into higher context
* @return {Function} The function `fn` applicable to mappable objects.
* @example
*
* var madd3 = R.liftN(3, R.curryN(3, function() {
* return R.reduce(R.add, 0, arguments);
* }));
* madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
*/
var liftN = _curry2(function liftN(arity, fn) {
var lifted = curryN(arity, fn);
return curryN(arity, function () {
return _reduce(ap, map(lifted, arguments[0]), _slice(arguments, 1));
});
});
/**
* Returns the mean of the given list of numbers.
*
* @func
* @memberOf R
* @category Math
* @sig [Number] -> Number
* @param {Array} list
* @return {Number}
* @example
*
* R.mean([2, 7, 9]); //=> 6
* R.mean([]); //=> NaN
*/
var mean = _curry1(function mean(list) {
return sum(list) / list.length;
});
/**
* Returns the median of the given list of numbers.
*
* @func
* @memberOf R
* @category Math
* @sig [Number] -> Number
* @param {Array} list
* @return {Number}
* @example
*
* R.median([2, 9, 7]); //=> 7
* R.median([7, 2, 10, 9]); //=> 8
* R.median([]); //=> NaN
*/
var median = _curry1(function median(list) {
var len = list.length;
if (len === 0) {
return NaN;
}
var width = 2 - len % 2;
var idx = (len - width) / 2;
return mean(_slice(list).sort(function (a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}).slice(idx, idx + width));
});
/**
* Merges a list of objects together into one object.
*
* @func
* @memberOf R
* @category List
* @sig [{k: v}] -> {k: v}
* @param {Array} list An array of objects
* @return {Object} A merged object.
* @see R.reduce
* @example
*
* R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3}
* R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2}
*/
var mergeAll = _curry1(function mergeAll(list) {
return reduce(merge, {}, list);
});
/**
* Performs left-to-right function composition. The leftmost function may have
* any arity; the remaining functions must be unary.
*
* In some libraries this function is named `sequence`.
*
* @func
* @memberOf R
* @category Function
* @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> (a -> b -> ... -> n -> z)
* @param {...Function} functions
* @return {Function}
* @see R.compose
* @example
*
* var f = R.pipe(Math.pow, R.negate, R.inc);
*
* f(3, 4); // -(3^4) + 1
*/
var pipe = function pipe() {
if (arguments.length === 0) {
throw new Error('pipe requires at least one argument');
}
return curryN(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments)));
};
/**
* Performs left-to-right composition of one or more Promise-returning
* functions. The leftmost function may have any arity; the remaining
* functions must be unary.
*
* @func
* @memberOf R
* @category Function
* @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z)
* @param {...Function} functions
* @return {Function}
* @see R.composeP
* @example
*
* // followersForUser :: String -> Promise [User]
* var followersForUser = R.pipeP(db.getUserById, db.getFollowers);
*/
var pipeP = function pipeP() {
if (arguments.length === 0) {
throw new Error('pipeP requires at least one argument');
}
return curryN(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments)));
};
/**
* Multiplies together all the elements of a list.
*
* @func
* @memberOf R
* @category Math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {Number} The product of all the numbers in the list.
* @see R.reduce
* @example
*
* R.product([2,4,6,8,100,1]); //=> 38400
*/
var product = reduce(multiply, 1);
/**
* Reasonable analog to SQL `select` statement.
*
* @func
* @memberOf R
* @category Object
* @category Relation
* @sig [k] -> [{k: v}] -> [{k: v}]
* @param {Array} props The property names to project
* @param {Array} objs The objects to query
* @return {Array} An array of objects with just the `props` properties.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
* var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
* var kids = [abby, fred];
* R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
*/
// passing `identity` gives correct arity
var project = useWith(_map, pickAll, identity);
/**
* Returns a new list containing the last `n` elements of the given list.
* If `n > list.length`, returns a list of `list.length` elements.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n The number of elements to return.
* @param {Array} xs The collection to consider.
* @return {Array}
* @see R.dropLast
* @example
*
* R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz']
* R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['for', 'baz']
* R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.takeLast(3, 'ramda'); //=> 'mda'
*/
var takeLast = _curry2(function takeLast(n, xs) {
return drop(n >= 0 ? xs.length - n : 0, xs);
});
var _contains = function _contains(a, list) {
return _indexOf(list, a, 0) >= 0;
};
// mapPairs :: (Object, [String]) -> [String]
// Function, RegExp, user-defined types
var _toString = function _toString(x, seen) {
var recur = function recur(y) {
var xs = seen.concat([x]);
return _contains(y, xs) ? '<Circular>' : _toString(y, xs);
};
// mapPairs :: (Object, [String]) -> [String]
var mapPairs = function (obj, keys) {
return _map(function (k) {
return _quote(k) + ': ' + recur(obj[k]);
}, keys.slice().sort());
};
switch (Object.prototype.toString.call(x)) {
case '[object Arguments]':
return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))';
case '[object Array]':
return '[' + _map(recur, x).concat(mapPairs(x, reject(test(/^\d+$/), keys(x)))).join(', ') + ']';
case '[object Boolean]':
return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString();
case '[object Date]':
return 'new Date(' + _quote(_toISOString(x)) + ')';
case '[object Null]':
return 'null';
case '[object Number]':
return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10);
case '[object String]':
return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x);
case '[object Undefined]':
return 'undefined';
default:
return typeof x.constructor === 'function' && x.constructor.name !== 'Object' && typeof x.toString === 'function' && x.toString() !== '[object Object]' ? x.toString() : // Function, RegExp, user-defined types
'{' + mapPairs(x, keys(x)).join(', ') + '}';
}
};
/**
* Turns a list of Functors into a Functor of a list.
*
* @func
* @memberOf R
* @category List
* @see R.commuteMap
* @sig Functor f => (x -> f x) -> [f a] -> f [a]
* @param {Function} of A function that returns the data type to return
* @param {Array} list An array of functors of the same type
* @return {*}
* @example
*
* R.commute(R.of, [[1], [2, 3]]); //=> [[1, 2], [1, 3]]
* R.commute(R.of, [[1, 2], [3]]); //=> [[1, 3], [2, 3]]
* R.commute(R.of, [[1], [2], [3]]); //=> [[1, 2, 3]]
* R.commute(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3])
* R.commute(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
*/
var commute = commuteMap(identity);
/**
* Performs right-to-left function composition. The rightmost function may have
* any arity; the remaining functions must be unary.
*
* @func
* @memberOf R
* @category Function
* @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> (a -> b -> ... -> n -> z)
* @param {...Function} functions
* @return {Function}
* @see R.pipe
* @example
*
* var f = R.compose(R.inc, R.negate, Math.pow);
*
* f(3, 4); // -(3^4) + 1
*/
var compose = function compose() {
if (arguments.length === 0) {
throw new Error('compose requires at least one argument');
}
return pipe.apply(this, reverse(arguments));
};
/**
* Returns the right-to-left Kleisli composition of the provided functions,
* each of which must return a value of a type supported by [`chain`](#chain).
*
* `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), R.chain(f))`.
*
* @func
* @memberOf R
* @category Function
* @see R.pipeK
* @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (m a -> m z)
* @param {...Function}
* @return {Function}
* @example
*
* // parseJson :: String -> Maybe *
* // get :: String -> Object -> Maybe *
*
* // getStateCode :: Maybe String -> Maybe String
* var getStateCode = R.composeK(
* R.compose(Maybe.of, R.toUpper),
* get('state'),
* get('address'),
* get('user'),
* parseJson
* );
*
* getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}'));
* //=> Just('NY')
* getStateCode(Maybe.of('[Invalid JSON]'));
* //=> Nothing()
*/
var composeK = function composeK() {
return arguments.length === 0 ? identity : compose.apply(this, map(chain, arguments));
};
/**
* Performs right-to-left composition of one or more Promise-returning
* functions. The rightmost function may have any arity; the remaining
* functions must be unary.
*
* @func
* @memberOf R
* @category Function
* @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z)
* @param {...Function} functions
* @return {Function}
* @see R.pipeP
* @example
*
* // followersForUser :: String -> Promise [User]
* var followersForUser = R.composeP(db.getFollowers, db.getUserById);
*/
var composeP = function composeP() {
if (arguments.length === 0) {
throw new Error('composeP requires at least one argument');
}
return pipeP.apply(this, reverse(arguments));
};
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> {*}) -> (* -> {*})
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Constructor function
* var Widget = function(config) {
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = [
* // ...
* ];
* R.map(R.construct(Widget), allConfigs); // a list of Widgets
*/
var construct = _curry1(function construct(Fn) {
return constructN(Fn.length, Fn);
});
/**
* Returns `true` if the specified value is equal, in `R.equals` terms,
* to at least one element of the given list; `false` otherwise.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Boolean
* @param {Object} a The item to compare against.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the item is in the list, `false` otherwise.
*
* @example
*
* R.contains(3, [1, 2, 3]); //=> true
* R.contains(4, [1, 2, 3]); //=> false
* R.contains([42], [[42]]); //=> true
*/
var contains = _curry2(_contains);
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
*
* @func
* @memberOf R
* @category Relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` that are not in `list2`.
* @see R.differenceWith
* @example
*
* R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
* R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
*/
var difference = _curry2(function difference(first, second) {
var out = [];
var idx = 0;
var firstLen = first.length;
while (idx < firstLen) {
if (!_contains(first[idx], second) && !_contains(first[idx], out)) {
out[out.length] = first[idx];
}
idx += 1;
}
return out;
});
/**
* Returns a new list without any consecutively repeating elements.
* `R.equals` is used to determine equality.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} `list` without repeating elements.
* @example
*
* R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
*/
var dropRepeats = _curry1(_dispatchable('dropRepeats', _xdropRepeatsWith(equals), dropRepeatsWith(equals)));
/**
* Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists.
*
* @func
* @memberOf R
* @category Relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.intersectionWith
* @return {Array} The list of elements found in both `list1` and `list2`.
* @example
*
* R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
*/
var intersection = _curry2(function intersection(list1, list2) {
return uniq(_filter(flip(_contains)(list1), list2));
});
/**
* "lifts" a function of arity > 1 so that it may "map over" an Array or
* other Functor.
*
* @func
* @memberOf R
* @see R.liftN
* @category Function
* @sig (*... -> *) -> ([*]... -> [*])
* @param {Function} fn The function to lift into higher context
* @return {Function} The function `fn` applicable to mappable objects.
* @example
*
* var madd3 = R.lift(R.curry(function(a, b, c) {
* return a + b + c;
* }));
* madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
*
* var madd5 = R.lift(R.curry(function(a, b, c, d, e) {
* return a + b + c + d + e;
* }));
* madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
*/
var lift = _curry1(function lift(fn) {
return liftN(fn.length, fn);
});
/**
* Returns a partial copy of an object omitting the keys specified.
*
* @func
* @memberOf R
* @category Object
* @sig [String] -> {String: *} -> {String: *}
* @param {Array} names an array of String property names to omit from the new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with properties from `names` not on it.
* @see R.pick
* @example
*
* R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
*/
var omit = _curry2(function omit(names, obj) {
var result = {};
for (var prop in obj) {
if (!_contains(prop, names)) {
result[prop] = obj[prop];
}
}
return result;
});
/**
* Returns the left-to-right Kleisli composition of the provided functions,
* each of which must return a value of a type supported by [`chain`](#chain).
*
* `R.pipeK(f, g, h)` is equivalent to `R.pipe(R.chain(f), R.chain(g), R.chain(h))`.
*
* @func
* @memberOf R
* @category Function
* @see R.composeK
* @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (m a -> m z)
* @param {...Function}
* @return {Function}
* @example
*
* // parseJson :: String -> Maybe *
* // get :: String -> Object -> Maybe *
*
* // getStateCode :: Maybe String -> Maybe String
* var getStateCode = R.pipeK(
* parseJson,
* get('user'),
* get('address'),
* get('state'),
* R.compose(Maybe.of, R.toUpper)
* );
*
* getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}'));
* //=> Just('NY')
* getStateCode(Maybe.of('[Invalid JSON]'));
* //=> Nothing()
*/
var pipeK = function pipeK() {
return composeK.apply(this, reverse(arguments));
};
/**
* Returns the string representation of the given value. `eval`'ing the output
* should result in a value equivalent to the input value. Many of the built-in
* `toString` methods do not satisfy this requirement.
*
* If the given value is an `[object Object]` with a `toString` method other
* than `Object.prototype.toString`, this method is invoked with no arguments
* to produce the return value. This means user-defined constructor functions
* can provide a suitable `toString` method. For example:
*
* function Point(x, y) {
* this.x = x;
* this.y = y;
* }
*
* Point.prototype.toString = function() {
* return 'new Point(' + this.x + ', ' + this.y + ')';
* };
*
* R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'
*
* @func
* @memberOf R
* @category String
* @sig * -> String
* @param {*} val
* @return {String}
* @example
*
* R.toString(42); //=> '42'
* R.toString('abc'); //=> '"abc"'
* R.toString([1, 2, 3]); //=> '[1, 2, 3]'
* R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}'
* R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")'
*/
var toString = _curry1(function toString(val) {
return _toString(val, []);
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the
* elements of each list.
*
* @func
* @memberOf R
* @category Relation
* @sig [a] -> [a] -> [a]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @example
*
* R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
*/
var union = _curry2(compose(uniq, _concat));
/**
* Returns a new list containing only one copy of each element in the
* original list, based upon the value returned by applying the supplied
* function to each list element. Prefers the first item if the supplied
* function produces the same value on two items. `R.equals` is used for
* comparison.
*
* @func
* @memberOf R
* @category List
* @sig (a -> b) -> [a] -> [a]
* @param {Function} fn A function used to produce a value to use during comparisons.
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]
*/
var uniqBy = _curry2(function uniqBy(fn, list) {
var idx = 0, applied = [], result = [], appliedItem, item;
while (idx < list.length) {
item = list[idx];
appliedItem = fn(item);
if (!_contains(appliedItem, applied)) {
result.push(item);
applied.push(appliedItem);
}
idx += 1;
}
return result;
});
/**
* Turns a named method with a specified arity into a function
* that can be called directly supplied with arguments and a target object.
*
* The returned function is curried and accepts `arity + 1` parameters where
* the final parameter is the target object.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
* @param {Number} arity Number of arguments the returned function should take
* before the target object.
* @param {Function} method Name of the method to call.
* @return {Function} A new curried function.
* @example
*
* var sliceFrom = R.invoker(1, 'slice');
* sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
* var sliceFrom6 = R.invoker(2, 'slice')(6);
* sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
*/
var invoker = _curry2(function invoker(arity, method) {
return curryN(arity + 1, function () {
var target = arguments[arity];
if (target != null && is(Function, target[method])) {
return target[method].apply(target, _slice(arguments, 0, arity));
}
throw new TypeError(toString(target) + ' does not have a method named "' + method + '"');
});
});
/**
* Returns a string made by inserting the `separator` between each
* element and concatenating all the elements into a single string.
*
* @func
* @memberOf R
* @category List
* @sig String -> [a] -> String
* @param {Number|String} separator The string used to separate the elements.
* @param {Array} xs The elements to join into a string.
* @return {String} str The string made by concatenating `xs` with `separator`.
* @see R.split
* @example
*
* var spacer = R.join(' ');
* spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
* R.join('|', [1, 2, 3]); //=> '1|2|3'
*/
var join = invoker(1, 'join');
/**
* Tests a regular expression against a String. Note that this function
* will return an empty array when there are no matches. This differs
* from [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)
* which returns `null` when there are no matches.
*
* @func
* @memberOf R
* @category String
* @sig RegExp -> String -> [String | Undefined]
* @param {RegExp} rx A regular expression.
* @param {String} str The string to match against
* @return {Array} The list of matches.
* @example
*
* R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
*/
var match = _curry2(compose(defaultTo([]), invoker(1, 'match')));
/**
* Creates a new function that, when invoked, caches the result of calling `fn` for a given
* argument set and returns the result. Subsequent calls to the memoized `fn` with the same
* argument set will not result in an additional call to `fn`; instead, the cached result
* for that set of arguments will be returned.
*
* @func
* @memberOf R
* @category Function
* @sig (*... -> a) -> (*... -> a)
* @param {Function} fn The function to memoize.
* @return {Function} Memoized version of `fn`.
* @example
*
* var count = 0;
* var factorial = R.memoize(function(n) {
* count += 1;
* return R.product(R.range(1, n + 1));
* });
* factorial(5); //=> 120
* factorial(5); //=> 120
* factorial(5); //=> 120
* count; //=> 1
*/
var memoize = _curry1(function memoize(fn) {
var cache = {};
return function () {
var key = toString(arguments);
if (!_has(key, cache)) {
cache[key] = fn.apply(this, arguments);
}
return cache[key];
};
});
/**
* Splits a string into an array of strings based on the given
* separator.
*
* @func
* @memberOf R
* @category String
* @sig String -> String -> [String]
* @param {String} sep The separator string.
* @param {String} str The string to separate into an array.
* @return {Array} The array of strings from `str` separated by `str`.
* @see R.join
* @example
*
* var pathComponents = R.split('/');
* R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
*
* R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
*/
var split = invoker(1, 'split');
/**
* The lower case version of a string.
*
* @func
* @memberOf R
* @category String
* @sig String -> String
* @param {String} str The string to lower case.
* @return {String} The lower case version of `str`.
* @see R.toUpper
* @example
*
* R.toLower('XYZ'); //=> 'xyz'
*/
var toLower = invoker(0, 'toLowerCase');
/**
* The upper case version of a string.
*
* @func
* @memberOf R
* @category String
* @sig String -> String
* @param {String} str The string to upper case.
* @return {String} The upper case version of `str`.
* @see R.toLower
* @example
*
* R.toUpper('abc'); //=> 'ABC'
*/
var toUpper = invoker(0, 'toUpperCase');
var R = {
F: F,
T: T,
__: __,
add: add,
addIndex: addIndex,
adjust: adjust,
all: all,
allPass: allPass,
always: always,
and: and,
any: any,
anyPass: anyPass,
ap: ap,
aperture: aperture,
append: append,
apply: apply,
assoc: assoc,
assocPath: assocPath,
binary: binary,
bind: bind,
both: both,
call: call,
chain: chain,
clone: clone,
commute: commute,
commuteMap: commuteMap,
comparator: comparator,
complement: complement,
compose: compose,
composeK: composeK,
composeP: composeP,
concat: concat,
cond: cond,
construct: construct,
constructN: constructN,
contains: contains,
containsWith: containsWith,
converge: converge,
countBy: countBy,
createMapEntry: createMapEntry,
curry: curry,
curryN: curryN,
dec: dec,
defaultTo: defaultTo,
difference: difference,
differenceWith: differenceWith,
dissoc: dissoc,
dissocPath: dissocPath,
divide: divide,
drop: drop,
dropLast: dropLast,
dropLastWhile: dropLastWhile,
dropRepeats: dropRepeats,
dropRepeatsWith: dropRepeatsWith,
dropWhile: dropWhile,
either: either,
empty: empty,
eqProps: eqProps,
equals: equals,
evolve: evolve,
filter: filter,
find: find,
findIndex: findIndex,
findLast: findLast,
findLastIndex: findLastIndex,
flatten: flatten,
flip: flip,
forEach: forEach,
fromPairs: fromPairs,
functions: functions,
functionsIn: functionsIn,
groupBy: groupBy,
gt: gt,
gte: gte,
has: has,
hasIn: hasIn,
head: head,
identical: identical,
identity: identity,
ifElse: ifElse,
inc: inc,
indexOf: indexOf,
init: init,
insert: insert,
insertAll: insertAll,
intersection: intersection,
intersectionWith: intersectionWith,
intersperse: intersperse,
into: into,
invert: invert,
invertObj: invertObj,
invoker: invoker,
is: is,
isArrayLike: isArrayLike,
isEmpty: isEmpty,
isNil: isNil,
isSet: isSet,
join: join,
keys: keys,
keysIn: keysIn,
last: last,
lastIndexOf: lastIndexOf,
length: length,
lens: lens,
lensIndex: lensIndex,
lensProp: lensProp,
lift: lift,
liftN: liftN,
lt: lt,
lte: lte,
map: map,
mapAccum: mapAccum,
mapAccumRight: mapAccumRight,
mapObj: mapObj,
mapObjIndexed: mapObjIndexed,
match: match,
mathMod: mathMod,
max: max,
maxBy: maxBy,
mean: mean,
median: median,
memoize: memoize,
merge: merge,
mergeAll: mergeAll,
min: min,
minBy: minBy,
modulo: modulo,
multiply: multiply,
nAry: nAry,
negate: negate,
none: none,
not: not,
nth: nth,
nthArg: nthArg,
nthChar: nthChar,
nthCharCode: nthCharCode,
of: of,
omit: omit,
once: once,
or: or,
over: over,
partial: partial,
partialRight: partialRight,
partition: partition,
path: path,
pathEq: pathEq,
pick: pick,
pickAll: pickAll,
pickBy: pickBy,
pipe: pipe,
pipeK: pipeK,
pipeP: pipeP,
pluck: pluck,
prepend: prepend,
product: product,
project: project,
prop: prop,
propEq: propEq,
propIs: propIs,
propOr: propOr,
propSatisfies: propSatisfies,
props: props,
range: range,
reduce: reduce,
reduceRight: reduceRight,
reduced: reduced,
reject: reject,
remove: remove,
repeat: repeat,
replace: replace,
reverse: reverse,
scan: scan,
set: set,
slice: slice,
sort: sort,
sortBy: sortBy,
split: split,
splitEvery: splitEvery,
subtract: subtract,
sum: sum,
tail: tail,
take: take,
takeLast: takeLast,
takeLastWhile: takeLastWhile,
takeWhile: takeWhile,
tap: tap,
test: test,
times: times,
toLower: toLower,
toPairs: toPairs,
toPairsIn: toPairsIn,
toString: toString,
toUpper: toUpper,
transduce: transduce,
trim: trim,
type: type,
unapply: unapply,
unary: unary,
uncurryN: uncurryN,
unfold: unfold,
union: union,
unionWith: unionWith,
uniq: uniq,
uniqBy: uniqBy,
uniqWith: uniqWith,
unnest: unnest,
update: update,
useWith: useWith,
values: values,
valuesIn: valuesIn,
view: view,
where: where,
whereEq: whereEq,
wrap: wrap,
xprod: xprod,
zip: zip,
zipObj: zipObj,
zipWith: zipWith
};
/* TEST_ENTRY_POINT */
if (typeof exports === 'object') {
module.exports = R;
} else if (typeof define === 'function' && define.amd) {
define(function() { return R; });
} else {
this.R = R;
}
}.call(this));
|
'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": [
"AM",
"PM"
],
"DAY": [
"Svondo",
"Muvhuro",
"Chipiri",
"Chitatu",
"China",
"Chishanu",
"Mugovera"
],
"MONTH": [
"Ndira",
"Kukadzi",
"Kurume",
"Kubvumbi",
"Chivabvu",
"Chikumi",
"Chikunguru",
"Nyamavhuvhu",
"Gunyana",
"Gumiguru",
"Mbudzi",
"Zvita"
],
"SHORTDAY": [
"Svo",
"Muv",
"Chip",
"Chit",
"Chin",
"Chis",
"Mug"
],
"SHORTMONTH": [
"Ndi",
"Kuk",
"Kur",
"Kub",
"Chv",
"Chk",
"Chg",
"Nya",
"Gun",
"Gum",
"Mb",
"Zvi"
],
"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": "$",
"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": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "sn-zw",
"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;}
});
}]);
|
(function(){/*
MIT License (c) copyright 2010-2013 B Cavalier & J Hann */
(function(n){function m(){}function v(a,b){return 0==T.call(a).indexOf("[object "+b)}function w(a){return a&&"/"==a.charAt(a.length-1)?a.substr(0,a.length-1):a}function l(a,b){var d,c,f,g;d=1;c=a;"."==c.charAt(0)&&(f=!0,c=c.replace(U,function(a,b,c,f){c&&d++;return f||""}));if(f){f=b.split("/");g=f.length-d;if(0>g)return a;f.splice(g,d);return f.concat(c||[]).join("/")}return c}function C(a){var b=a.indexOf("!");return{g:a.substr(b+1),d:0<=b&&a.substr(0,b)}}function z(){}function q(a,b){z.prototype=
a||N;var d=new z;z.prototype=N;for(var c in b)d[c]=b[c];return d}function D(){function a(a,b,d){c.push([a,b,d])}function b(a,b){for(var d,f=0;d=c[f++];)(d=d[a])&&d(b)}var d,c,f;d=this;c=[];f=function(d,p){a=d?function(a){a&&a(p)}:function(a,b){b&&b(p)};f=m;b(d?0:1,p);b=m;c=x};this.m=function(b,c,f){a(b,c,f);return d};this.h=function(a){d.C=a;f(!0,a)};this.f=function(a){d.qa=a;f(!1,a)};this.w=function(a){b(2,a)}}function A(a){return a instanceof D||a instanceof h}function y(a,b,d,c){A(a)?a.m(b,d,c):
b(a)}function B(a,b,d){var c;return function(){0<=--a&&b&&(c=b.apply(x,arguments));0==a&&d&&d(c);return c}}function e(){var a,b;s="";a=[].slice.call(arguments);v(a[0],"Object")&&(b=a.shift(),b=H(b));return new h(a[0],a[1],a[2],b)}function H(a,b,d){var c;s="";if(a&&(k.R(a),r=k.b(a),"preloads"in a&&(c=new h(a.preloads,x,d,I,!0),k.l(function(){I=c})),a=a.main))return new h(a,b,d)}function h(a,b,d,c,f){var g;g=k.k(r,x,[].concat(a),f);this.then=this.m=a=function(a,b){y(g,function(b){a&&a.apply(x,b)},function(a){if(b)b(a);
else throw a;});return this};this.next=function(a,b,c){return new h(a,b,c,g)};this.config=H;(b||d)&&a(b,d);k.l(function(){y(f||I,function(){y(c,function(){k.r(g)},d)})})}function K(a){var b,d;b=a.id;b==x&&(J!==x?J={I:"Multiple anonymous defines encountered"}:(b=k.da())||(J=a));if(b!=x){d=u[b];b in u||(d=k.j(b,r),d=k.F(d.b,b),u[b]=d);if(!A(d))throw Error("duplicate define: "+b);d.ha=!1;k.G(d,a)}}function E(){var a=k.aa(arguments);K(a)}var s,r,F,G,t=n.document,O=t&&(t.head||t.getElementsByTagName("head")[0]),
V=O&&O.getElementsByTagName("base")[0]||null,Q={},R={},L={},W="addEventListener"in n?{}:{loaded:1,complete:1},N={},T=N.toString,x,u={},M={},I=!1,J,S=/^\/|^[^:]+:\/\//,U=/(\.)(\.?)(?:$|\/([^\.\/]+.*)?)/g,X=/\/\*[\s\S]*?\*\/|\/\/.*?[\n\r]/g,Y=/require\s*\(\s*(["'])(.*?[^\\])\1\s*\)|[^\\]?(["'])/g,Z=/\s*,\s*/,P,k;k={n:function(a,b,d){var c;a=l(a,b);if("."==a.charAt(0))return a;c=C(a);a=(b=c.d)||c.g;a in d.c&&(a=d.c[a].M||a);b&&(0>b.indexOf("/")&&!(b in d.c)&&(a=w(d.P)+"/"+b),a=a+"!"+c.g);return a},k:function(a,
b,d,c){function f(b,c){var d,g;d=k.n(b,p.id,a);if(!c)return d;g=C(d);if(!g.d)return d;d=u[g.d];g.g="normalize"in d?d.normalize(g.g,f,p.b)||"":f(g.g);return g.d+"!"+g.g}function g(b,d,g){var e;e=d&&function(a){d.apply(x,a)};if(v(b,"String")){if(e)throw Error("require(id, callback) not allowed");g=f(b,!0);b=u[g];if(!(g in u))throw Error("Module not resolved: "+g);return(g=A(b)&&b.a)||b}y(k.r(k.k(a,p.id,b,c)),e,g)}var p;p=new D;p.id=b||"";p.ea=c;p.H=d;p.b=a;p.A=g;g.toUrl=function(b){return k.j(f(b,!0),
a).url};p.n=f;return p},F:function(a,b,d){var c,f,g;c=k.k(a,b,x,d);f=c.h;g=B(1,function(a){c.q=a;try{return k.V(c)}catch(b){c.f(b)}});c.h=function(a){y(d||I,function(){f(u[c.id]=M[c.url]=g(a))})};c.J=function(a){y(d||I,function(){c.a&&(g(a),c.w(R))})};return c},U:function(a,b,d,c){return k.k(a,d,x,c)},ca:function(a){return a.A},K:function(a){return a.a||(a.a={})},ba:function(a){var b=a.t;b||(b=a.t={id:a.id,uri:k.L(a),exports:k.K(a),config:function(){return a.b}},b.a=b.exports);return b},L:function(a){return a.url||
(a.url=k.D(a.A.toUrl(a.id),a.b))},R:function(a){var b,d,c,f,g;b="curl";d="define";c=f=n;if(a&&(g=a.overwriteApi||a.oa,b=a.apiName||a.ja||b,c=a.apiContext||a.ia||c,d=a.defineName||a.la||d,f=a.defineContext||a.ka||f,F&&v(F,"Function")&&(n.curl=F),F=null,G&&v(G,"Function")&&(n.define=G),G=null,!g)){if(c[b]&&c[b]!=e)throw Error(b+" already exists");if(f[d]&&f[d]!=E)throw Error(d+" already exists");}c[b]=e;f[d]=E},b:function(a){function b(a,b){var d,c,p,e,r;for(r in a){p=a[r];v(p,"String")&&(p={path:a[r]});
p.name=p.name||r;e=f;c=C(w(p.name));d=c.g;if(c=c.d)e=g[c],e||(e=g[c]=q(f),e.c=q(f.c),e.e=[]),delete a[r];c=p;var s=b,h=void 0;c.path=w(c.path||c.location||"");s&&(h=c.main||"./main","."==h.charAt(0)||(h="./"+h),c.M=l(h,c.name+"/"));c.b=c.config;c.b&&(c.b=q(f,c.b));c.S=d.split("/").length;d?(e.c[d]=c,e.e.push(d)):e.o=k.Q(p.path,f)}}function d(a){var b=a.c;a.O=RegExp("^("+a.e.sort(function(a,c){return b[c].S-b[a].S}).join("|").replace(/\/|\./g,"\\$&")+")(?=\\/|$)");delete a.e}var c,f,g,p;"baseUrl"in
a&&(a.o=a.baseUrl);"main"in a&&(a.M=a.main);"preloads"in a&&(a.pa=a.preloads);"pluginPath"in a&&(a.P=a.pluginPath);if("dontAddFileExt"in a||a.i)a.i=RegExp(a.dontAddFileExt||a.i);c=r;f=q(c,a);f.c=q(c.c);g=a.plugins||{};f.plugins=q(c.plugins);f.v=q(c.v,a.v);f.u=q(c.u,a.u);f.e=[];b(a.packages,!0);b(a.paths,!1);for(p in g)a=k.n(p+"!","",f),f.plugins[a.substr(0,a.length-1)]=g[p];g=f.plugins;for(p in g)if(g[p]=q(f,g[p]),a=g[p].e)g[p].e=a.concat(f.e),d(g[p]);for(p in c.c)f.c.hasOwnProperty(p)||f.e.push(p);
d(f);return f},j:function(a,b){var d,c,f,g;d=b.c;f=S.test(a)?a:a.replace(b.O,function(a){c=d[a]||{};g=c.b;return c.path||""});return{b:g||r,url:k.Q(f,b)}},Q:function(a,b){var d=b.o;return d&&!S.test(a)?w(d)+"/"+a:a},D:function(a,b){return a+((b||r).i.test(a)?"":".js")},s:function(a,b,d){var c=t.createElement("script");c.onload=c.onreadystatechange=function(d){d=d||n.event;if("load"==d.type||W[c.readyState])delete L[a.id],c.onload=c.onreadystatechange=c.onerror="",b()};c.onerror=function(){d(Error("Syntax or http error: "+
a.url))};c.type=a.N||"text/javascript";c.charset="utf-8";c.async=!a.fa;c.src=a.url;L[a.id]=c;O.insertBefore(c,V);return c},W:function(a){var b=[],d;("string"==typeof a?a:a.toSource?a.toSource():a.toString()).replace(X,"").replace(Y,function(a,f,g,e){e?d=d==e?x:d:d||b.push(g);return""});return b},aa:function(a){var b,d,c,f,g,e;g=a.length;c=a[g-1];f=v(c,"Function")?c.length:-1;2==g?v(a[0],"Array")?d=a[0]:b=a[0]:3==g&&(b=a[0],d=a[1]);!d&&0<f&&(e=!0,d=["require","exports","module"].slice(0,f).concat(k.W(c)));
return{id:b,q:d||[],B:0<=f?c:function(){return c},p:e}},V:function(a){var b;b=a.B.apply(a.p?a.a:x,a.q);b===x&&a.a&&(b=a.t?a.a=a.t.exports:a.a);return b},G:function(a,b){a.B=b.B;a.p=b.p;a.H=b.q;k.r(a)},r:function(a){function b(a,b,c){e[b]=a;c&&s(a,b)}function d(b,c){var d,f,g,e;d=B(1,function(a){f(a);l(a,c)});f=B(1,function(a){s(a,c)});g=k.Y(b,a);(e=A(g)&&g.a)&&f(e);y(g,d,a.f,a.a&&function(a){g.a&&(a==Q?f(g.a):a==R&&d(g.a))})}function c(){a.h(e)}var f,g,e,r,h,s,l;e=[];g=a.H;r=g.length;0==g.length&&
c();s=B(r,b,function(){a.J&&a.J(e)});l=B(r,b,c);for(f=0;f<r;f++)h=g[f],h in P?(l(P[h](a),f,!0),a.a&&a.w(Q)):h?d(h,f):l(x,f,!0);return a},Z:function(a){k.L(a);k.s(a,function(){var b=J;J=x;!1!==a.ha&&(!b||b.I?a.f(Error(b&&b.I||"define() missing or duplicated: "+a.url)):k.G(a,b))},a.f);return a},Y:function(a,b){var d,c,f,g,e,h,s,l,m,q,t,n;d=b.n;c=b.ea;f=b.b||r;e=d(a);e in u?h=e:(g=C(e),l=g.g,h=g.d||l,m=k.j(h,f));if(!(e in u))if(n=k.j(l,f).b,g.d)s=h;else if(s=n.moduleLoader||n.na||n.loader||n.ma)l=h,
h=s,m=k.j(s,f);h in u?q=u[h]:m.url in M?q=u[h]=M[m.url]:(q=k.F(n,h,c),q.url=k.D(m.url,m.b),u[h]=M[m.url]=q,k.Z(q));h==s&&(g.d&&f.plugins[g.d]&&(n=f.plugins[g.d]),t=new D,y(q,function(a){var b,f,g;g=a.dynamic;l="normalize"in a?a.normalize(l,d,q.b)||"":d(l);f=s+"!"+l;b=u[f];if(!(f in u)){b=k.U(n,f,l,c);g||(u[f]=b);var e=function(a){g||(u[f]=a);b.h(a)};e.resolve=e;e.reject=e.error=b.f;a.load(l,b.A,e,n)}t!=b&&y(b,t.h,t.f,t.w)},t.f));return t||q},da:function(){var a;if(!v(n.opera,"Opera"))for(var b in L)if("interactive"==
L[b].readyState){a=b;break}return a},$:function(a){var b=0,d,c;for(d=t&&(t.scripts||t.getElementsByTagName("script"));d&&(c=d[b++]);)if(a(c))return c},X:function(){var a,b="";(a=k.$(function(a){(a=a.getAttribute("data-curl-run"))&&(b=a);return a}))&&a.setAttribute("data-curl-run","");return b},T:function(){function a(){k.s({url:c.shift()},b,b)}function b(){s&&(c.length?(k.l(d),a()):d("run.js script did not run."))}function d(a){throw Error(a||"Primary run.js failed. Trying fallback.");}var c=s.split(Z);
c.length&&a()},l:function(a){setTimeout(a,0)}};P={require:k.ca,exports:k.K,module:k.ba};e.version="0.8.9";e.config=H;E.amd={plugins:!0,jQuery:!0,curl:"0.8.9"};r={o:"",P:"curl/plugin",i:/\?|\.js\b/,v:{},u:{},plugins:{},c:{},O:/$^/};F=n.curl;G=n.define;F&&v(F,"Object")?(n.curl=x,H(F)):k.R();(s=k.X())&&k.l(k.T);u.curl=e;u["curl/_privileged"]={core:k,cache:u,config:function(){return r},_define:K,_curl:e,Promise:D}})(this.window||"undefined"!=typeof global&&global||this);
(function(n,m){function v(){if(!m.body)return!1;E||(E=m.createTextNode(""));try{return m.body.removeChild(m.body.appendChild(E)),E=K,!0}catch(e){return!1}}function w(){var s;s=z[m[C]]&&v();if(!A&&s){A=!0;for(clearTimeout(h);e=H.pop();)e();D&&(m[C]="complete");for(var r;r=q.shift();)r()}return s}function l(){w();A||(h=setTimeout(l,y))}var C="readyState",z={loaded:1,interactive:1,complete:1},q=[],D=m&&"string"!=typeof m[C],A=!1,y=10,B,e,H=[],h,K,E;B="addEventListener"in n?function(e,h){e.addEventListener(h,
w,!1);return function(){e.removeEventListener(h,w,!1)}}:function(e,h){e.attachEvent("on"+h,w);return function(){e.detachEvent(h,w)}};m&&!w()&&(H=[B(n,"load"),B(m,"readystatechange"),B(n,"DOMContentLoaded")],h=setTimeout(l,y));define("curl/domReady",function(){function e(h){A?h():q.push(h)}e.then=e;e.amd=!0;return e})})(this,this.document);
(function(n,m,v){define("curl/plugin/js",["curl/_privileged"],function(n){function l(e,l,h){function m(){s||(q<new Date?h():setTimeout(m,10))}var q,s,r;q=(new Date).valueOf()+(e.ga||3E5);h&&e.a&&setTimeout(m,10);r=n.core.s(e,function(){s=!0;e.a&&(e.C=v(e.a));!e.a||e.C?l(r):h()},function(e){s=!0;h(e)})}function C(e,m){l(e,function(){var h=q.shift();y=0<q.length;h&&C.apply(null,h);m.h(e.C||!0)},function(e){m.f(e)})}var z={},q=[],D=m&&!0==m.createElement("script").async,A,y,B=/\?|\.js\b/;A=n.Promise;
return{dynamic:!0,normalize:function(e,l){var h=e.indexOf("!");return 0<=h?l(e.substr(0,h))+e.substr(h):l(e)},load:function(e,m,h,n){function v(e){(h.error||function(e){throw e;})(e)}var s,r,w,G,t;s=0<e.indexOf("!order");r=e.indexOf("!exports=");w=0<r?e.substr(r+9):n.a;G="prefetch"in n?n.prefetch:!0;e=s||0<r?e.substr(0,e.indexOf("!")):e;r=(r=n.dontAddFileExt||n.i)?RegExp(r):B;t=m.toUrl(e);r.test(t)||(t=t.lastIndexOf(".")<=t.lastIndexOf("/")?t+".js":t);t in z?z[t]instanceof A?z[t].m(h,v):h(z[t]):(e=
{name:e,url:t,fa:s,a:w,ga:n.timeout},z[t]=m=new A,m.m(function(e){z[t]=e;h(e)},v),s&&!D&&y?(q.push([e,m]),G&&(e.N="text/cache",l(e,function(e){e&&e.parentNode.removeChild(e)},function(){}),e.N="")):(y=y||s,C(e,m)))},cramPlugin:"../cram/js"}})})(this,this.document,function(n){try{return eval(n)}catch(m){}});
(function(n){var m=n.document,v=/^\/\//,w;m&&(w=m.head||(m.head=m.getElementsByTagName("head")[0]));define("curl/plugin/link",{load:function(l,n,z,q){l=n.toUrl(l);l=l.lastIndexOf(".")<=l.lastIndexOf("/")?l+".css":l;q=l=(q="fixSchemalessUrls"in q?q.fixSchemalessUrls:m.location.protocol)?l.replace(v,q+"//"):l;l=m.createElement("link");l.rel="stylesheet";l.type="text/css";l.href=q;w.appendChild(l);z(l.sheet||l.styleSheet)}})})(this);
define("curl/plugin/domReady",["../domReady"],function(n){return{load:function(m,v,w){n(w)}}});
}).call(this);
|
/**
* Copyright (c) 2016-present, 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.
*
* @flow
*/
'use strict';
// This is a forwarding module to allow React to require React Native internals
// as node dependency
module.exports = require('TextInputState');
|
/*
* Validation JS
*
* - Initializes validation on selector (forms)
* - Adds/removes rules on elements contained in var types.validation
* - Checks if elements are hidden by conditionals
*
* @see WPCF_Validation::renderJsonData( $selector ) how rules are added
* Use wp_enqueue_script( 'types-validation' ) to enqueue this script.
* Use wpcf_form_render_js_validation( $selector ) to render validation data used here.
*
* Used in post-relationship.js in 2 places for callback.
*/
var typesValidation = (function($) {
function init() {
$.each(types.validation, function() {
_initValidation(this.selector);
_setRules(this.elements);
});
}
function setRules() {
$.each(types.validation, function() {
_setRules(this.elements);
});
}
function _initValidation(selector) {
$(selector).validate({
// :hidden is kept because it's default value.
// All accepted by jQuery.not() can be added.
ignore: 'input[type="hidden"], .wpcf-form-groups-support-post-type, .wpcf-form-groups-support-tax, .wpcf-form-groups-support-templates, :not(.js-types-validate)',
errorPlacement: function(error, element) {
error.insertBefore(element);
},
highlight: function(element, errorClass, validClass) {
$('#publishing-action .spinner').css('visibility', 'hidden');
$('#publish').bind('click', function() {
$('#publishing-action .spinner').css('visibility', 'visible');
});
$(element).parents('.collapsible').slideDown();
if (selector == '#post') {
var box = jQuery(element).parents('postbox');
if (box.hasClass('closed')) {
box.find('.handlediv').trigger('click');
}
}
$(element).parents('.collapsible').slideDown();
$("input#publish").addClass("button-primary-disabled");
$("input#save-post").addClass("button-disabled");
$("#save-action .ajax-loading").css("visibility", "hidden");
$("#publishing-action #ajax-loading").css("visibility", "hidden");
/**
* remove colorbox
*/
$('#cboxOverlay').remove();
$('#colorbox').remove();
},
unhighlight: function(element, errorClass, validClass) {
$("input#publish, input#save-post").removeClass("button-primary-disabled").removeClass("button-disabled");
// $.validator.defaults.unhighlight(element, errorClass, validClass);
},
invalidHandler: function(form, validator) {
var elements = new Array(), form = $(selector), passed = false;
/*
* validator.errorList contains an array of objects,
* where each object has properties "element" and "message".
* element is the actual HTML Input.
*/
for (var i = 0; i < validator.errorList.length; i++) {
var el = validator.errorList[i].element;
elements.push($(el).attr('id'));
}
/*
* Valid if conditional is hidden by other conditional
*/
if (_checkConditional(selector, elements, form, validator)) {
passed = true;
}
if (passed) {
$(selector).validate().cancelSubmit = true;
$(selector).submit();
}
wpcfLoadingButtonStop();
},
errorClass: "wpcf-form-error"
});
}
function _checkConditional(selector, elements, form, validator) {
var element, failed = new Array(), failedHidden = new Array();
for (var i = 0; i < elements.length; i++) {
selector = elements[i];
element = jQuery('#' + selector);
if (element.length > 0) {
if (conditionalIsHidden(element)) {
failedHidden.push(selector);
} else {
if (element.parents('.inside').is(':hidden')) {
element.parents('.postbox').find('.handlediv').trigger('click');
}
failed.push(selector);
}
}
}
if (failed.length > 0) {
return false;
} else if (failedHidden.length > 0) {
return true;
}
return false;
}
function conditionalIsHidden(object) {
// Check if meta-box is hidden
if (object.parents('.wpcf-conditional').length > 0
&& object.parents('.inside').is(':hidden')) {
if (object.parents('.wpcf-conditional').css('display') == 'none') {
return true;
}
return false;
} else {
return object.parents('.wpcf-conditional').length > 0 && object.is(':hidden');
}
}
function _setRules(elements) {
$.each(elements, function() {
element = this;
if ($(element.selector).length > 0) {
$.each(element.rules, function() {
if (conditionalIsHidden($(element.selector))) {
$(element.selector).rules("remove", this.method);
$(element.selector).removeClass('js-types-validate');
} else {
var rule = {messages: {}};
rule[this.method] = this.value == 'true' ? true : this.value;
rule.messages[this.method] = this.message;
$(element.selector).rules("add", rule);
$(element.selector).addClass('js-types-validate');
}
});
}
});
}
return {
init: init,
setRules: setRules,
conditionalIsHidden: conditionalIsHidden
};
})(jQuery);
jQuery(document).ready(function($) {
typesValidation.init();
});
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "d/MM/yy HH:mm",
"shortDate": "d/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"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": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-be",
"pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* ShaderToon currently contains:
*
* toon1
* toon2
* hatching
* dotted
*/
THREE.ShaderToon = {
'toon1' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) }
},
vertexShader: [
"varying vec3 vNormal;",
"varying vec3 vRefract;",
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
"vNormal = normalize( normalMatrix * normal );",
"vec3 I = worldPosition.xyz - cameraPosition;",
"vRefract = refract( normalize( I ), worldNormal, 1.02 );",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"varying vec3 vRefract;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );",
"intensity += length(lightWeighting) * 0.2;",
"float cameraWeighting = dot( normalize( vNormal ), vRefract );",
"intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );",
"intensity = intensity * 0.2 + 0.3;",
"if ( intensity < 0.50 ) {",
"gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );",
"} else {",
"gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );",
"}",
"}"
].join( "\n" )
},
'toon2' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xeeeeee ) },
"uLineColor1": { value: new THREE.Color( 0x808080 ) },
"uLineColor2": { value: new THREE.Color( 0x000000 ) },
"uLineColor3": { value: new THREE.Color( 0x000000 ) },
"uLineColor4": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);",
"float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {",
"gl_FragColor *= vec4( uLineColor1, 1.0 );",
"}",
"if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {",
"gl_FragColor *= vec4( uLineColor2, 1.0 );",
"}",
"}"
].join( "\n" )
},
'hatching' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) },
"uLineColor1": { value: new THREE.Color( 0x000000 ) },
"uLineColor2": { value: new THREE.Color( 0x000000 ) },
"uLineColor3": { value: new THREE.Color( 0x000000 ) },
"uLineColor4": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(lightWeighting) < 1.00 ) {",
"if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.75 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor2, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.50 ) {",
"if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor3, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.3465 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor4, 1.0 );",
"}",
"}",
"}"
].join( "\n" )
},
'dotted' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) },
"uLineColor1": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(lightWeighting) < 1.00 ) {",
"if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.50 ) {",
"if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"}"
].join( "\n" )
}
};
|
/*************************************************************
*
* MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/CombDiacritMarks.js
*
* Defines the image size data needed for the HTML-CSS OutputJax
* to display mathematics using fallback images when the fonts
* are not availble to the client browser.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2009-2010 Design Science, Inc.
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({
"MathJax_AMS": {
0x302: [ // COMBINING CIRCUMFLEX ACCENT
[18,3,-3],[21,3,-4],[25,3,-5],[29,4,-6],[34,5,-8],[40,5,-9],[47,6,-11],[56,8,-12],
[66,8,-16],[79,10,-19],[93,12,-21],[111,14,-26],[131,17,-30],[156,20,-36]
],
0x303: [ // COMBINING TILDE
[17,2,-4],[20,2,-5],[23,4,-5],[28,5,-7],[33,4,-9],[39,5,-10],[46,6,-12],[55,6,-15],
[65,8,-17],[77,9,-21],[92,11,-25],[109,13,-29],[129,15,-35],[154,18,-41]
]
}
});
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/AMS/Regular"+
MathJax.OutputJax["HTML-CSS"].imgPacked+"/CombDiacritMarks.js");
|
describe('getLayers', function () {
var map, div;
beforeEach(function () {
div = document.createElement('div');
div.style.width = '200px';
div.style.height = '200px';
document.body.appendChild(div);
map = L.map(div, { maxZoom: 18 });
map.fitBounds(new L.LatLngBounds([
[1, 1],
[2, 2]
]));
});
afterEach(function () {
document.body.removeChild(div);
});
it('hits polygons and markers before adding to map', function () {
var group = new L.MarkerClusterGroup();
var polygon = new L.Polygon([[1.5, 1.5], [2.0, 1.5], [2.0, 2.0], [1.5, 2.0]]);
var marker = new L.Marker([1.5, 1.5]);
group.addLayers([polygon, marker]);
var layers = group.getLayers();
expect(layers.length).to.be(2);
expect(layers).to.contain(marker);
expect(layers).to.contain(polygon);
});
it('hits polygons and markers after adding to map', function () {
var group = new L.MarkerClusterGroup();
var polygon = new L.Polygon([[1.5, 1.5], [2.0, 1.5], [2.0, 2.0], [1.5, 2.0]]);
var marker = new L.Marker([1.5, 1.5]);
group.addLayers([polygon, marker]);
map.addLayer(group);
var layers = group.getLayers();
expect(layers.length).to.be(2);
expect(layers).to.contain(marker);
expect(layers).to.contain(polygon);
});
}); |
/*!
* CamanJS - Pure HTML5 Javascript (Ca)nvas (Man)ipulation
* http://camanjs.com/
*
* Copyright 2011, Ryan LeFevre
* Licensed under the new BSD License.
* See LICENSE for more info.
*
* Project Contributors:
* Ryan LeFevre - Lead Developer and Project Maintainer
* Twitter: @meltingice
* GitHub: http://github.com/meltingice
*
* Rick Waldron - Plugin Architect and Developer
* Twitter: @rwaldron
* GitHub: http://github.com/rwldrn
*
* Cezar Sa Espinola - Developer
* Twitter: @cezarsa
* GitHub: http://github.com/cezarsa
*/
/*global Caman: true, require: true, exports: true */
var fs = require('fs'),
Canvas = require('canvas'),
Image = Canvas.Image,
forEach = Array.prototype.forEach,
hasOwn = Object.prototype.hasOwnProperty,
slice = Array.prototype.slice,
Caman = function ( file, ready ) {
return new Caman.manip.load(file, ready);
};
Caman.ready = false;
Caman.store = {};
Caman.renderBlocks = 4;
Caman.manip = Caman.prototype = {
/*
* Sets up everything that needs to be done before the filter
* functions can be run. This includes loading the image into
* the canvas element and saving lots of different data about
* the image.
*/
load: function(file, ready) {
var self = this,
img = new Image();
file = fs.realpathSync(file);
img.onload = function () {
var canvas = new Canvas(img.width, img.height);
self.canvas = canvas;
self.context = canvas.getContext('2d');
self.context.drawImage(img, 0, 0);
self.image_data = self.context.getImageData(0, 0, img.width, img.height);
self.pixel_data = self.image_data.data;
self.dimensions = {
width: img.width,
height: img.height
};
self.renderQueue = [];
self.pixelStack = [];
self.layerStack = [];
if(typeof ready === "function") { ready.call(self, self); }
Caman.store[file] = self;
return self;
};
img.onerror = function (err) {
throw err;
};
img.src = file;
},
/*
* Grabs the canvas data, encodes it to Base64, then
* sets the browser location to the encoded data so that
* the user will be prompted to download it.
*/
save: function (file, overwrite) {
var out = fs.createWriteStream(file),
stream = this.canvas.createPNGStream();
var stats = fs.statSync(file);
if (stats.isFile() && !overwrite) {
return false;
}
stream.on('data', function (chunk) {
out.write(chunk);
});
},
/*
* Grabs the current canvas data and Base64 encodes it.
*/
toBase64: function (type) {
if (type) {
type = type.toLowerCase();
}
if (!type || (type !== 'png' && type !== 'jpg')) {
type = 'png';
}
return this.canvas.toDataURL("image/" + type);
},
revert: function (ready) {
this.loadCanvas(this.options.image, this.options.canvas, ready);
},
render: function (callback) {
this.processNext(function () {
this.context.putImageData(this.image_data, 0, 0);
if (typeof callback === 'function') {
callback.call(this);
}
});
}
};
Caman.manip.load.prototype = Caman.manip;
/*
* Utility forEach function for iterating over
* objects/arrays.
*/
Caman.forEach = function( obj, fn, context ) {
if ( !obj || !fn ) {
return {};
}
context = context || this;
// Use native whenever possible
if ( forEach && obj.forEach === forEach ) {
return obj.forEach(fn, context);
}
for ( var key in obj ) {
if ( hasOwn.call(obj, key) ) {
fn.call(context, obj[key], key, obj);
}
}
return obj;
};
Caman.loadPlugin = function (file) {
var stats = fs.statSync("plugins/" + file + ".js"),
load;
if (stats.isFile()) {
load = require("./plugins/" + file + ".js");
} else {
stats = fs.statSync(file);
if (stats.isFile()) {
load = require(file);
}
}
Caman.extend( Caman.manip, load.plugins );
};
/*
* Used for extending the Caman object, primarily to
* add new functionality to the base library.
*/
Caman.extend = function( obj ) {
var dest = obj, src = slice.call(arguments, 1);
Caman.forEach( src, function( copy ) {
for ( var prop in copy ) {
dest[prop] = copy[prop];
}
});
return dest;
};
/*
* CamanJS event system
* Events can be subscribed to using Caman.listen() and events
* can be triggered using Caman.trigger().
*/
Caman.events = {
types: [ "processStart", "processComplete", "renderFinished" ],
fn: {
/*
* Triggers an event with the given target name.
*/
trigger: function ( target, type, data ) {
var _target = target, _type = type, _data = data;
if ( Caman.events.types.indexOf(target) !== -1 ) {
_target = this;
_type = target;
_data = type;
}
if ( Caman.events.fn[_type] && Caman.sizeOf(Caman.events.fn[_type]) ) {
Caman.forEach(Caman.events.fn[_type], function ( obj, key ) {
obj.call(_target, _data);
});
}
},
/*
* Registers a callback function to be fired when a certain
* event occurs.
*/
listen: function ( target, type, fn ) {
var _target = target, _type = type, _fn = fn;
if ( Caman.events.types.indexOf(target) !== -1 ) {
_target = this;
_type = target;
_fn = type;
}
if ( !Caman.events.fn[_type] ) {
Caman.events.fn[_type] = [];
}
Caman.events.fn[_type].push(_fn);
return true;
}
},
cache: {}
};
// Basic event system
(function (Caman) {
Caman.forEach( ["trigger", "listen"], function ( key ) {
Caman[key] = Caman.events.fn[key];
});
})(Caman);
/*
* SINGLE = traverse the image 1 pixel at a time
* KERNEL = traverse the image using convolution kernels
* LAYER_DEQUEUE = shift a layer off the canvasQueue
* LAYER_FINISHED = finished processing a layer
*/
var ProcessType = {
SINGLE: 1,
KERNEL: 2,
LAYER_DEQUEUE: 3,
LAYER_FINISHED: 4,
LOAD_OVERLAY: 5
};
/*
* Allows the currently rendering filter to get data about
* surrounding pixels relative to the pixel currently being
* processed. The data returned is identical in format to the
* rgba object provided in the process function.
*
* Example: to get data about the pixel to the top-right
* of the currently processing pixel, you can call (within the process
* function):
* this.getPixel(1, -1);
*/
Caman.manip.pixelInfo = function (loc, self) {
this.loc = loc;
this.manip = self;
};
Caman.manip.pixelInfo.prototype.locationXY = function () {
var x, y;
y = this.manip.dimensions.height - Math.floor(this.loc / (this.manip.dimensions.width * 4));
x = ((this.loc % (this.manip.dimensions.width * 4)) / 4) - 1;
return {x: x, y: y};
};
Caman.manip.pixelInfo.prototype.getPixelRelative = function (horiz_offset, vert_offset) {
// We invert the vert_offset in order to make the coordinate system non-inverted. In laymans
// terms: -1 means down and +1 means up.
var newLoc = this.loc + (this.manip.dimensions.width * 4 * (vert_offset * -1)) + (4 * horiz_offset);
// error handling
if (newLoc > this.manip.pixel_data.length || newLoc < 0) {
return {r: 0, g: 0, b: 0, a: 0};
}
return {
r: this.manip.pixel_data[newLoc],
g: this.manip.pixel_data[newLoc+1],
b: this.manip.pixel_data[newLoc+2],
a: this.manip.pixel_data[newLoc+3]
};
};
Caman.manip.pixelInfo.prototype.putPixelRelative = function (horiz_offset, vert_offset, rgba) {
var newLoc = this.loc + (this.manip.dimensions.width * 4 * (vert_offset * -1)) + (4 * horiz_offset);
// error handling
if (newLoc > this.manip.pixel_data.length || newLoc < 0) {
return false;
}
this.manip.pixel_data[newLoc] = rgba.r;
this.manip.pixel_data[newLoc+1] = rgba.g;
this.manip.pixel_data[newLoc+2] = rgba.b;
this.manip.pixel_data[newLoc+3] = rgba.a;
};
Caman.manip.pixelInfo.prototype.getPixel = function (x, y) {
var newLoc = (y * this.manip.dimensions.width + x) * 4;
return {
r: this.manip.pixel_data[newLoc],
g: this.manip.pixel_data[newLoc+1],
b: this.manip.pixel_data[newLoc+2],
a: this.manip.pixel_data[newLoc+3]
};
};
Caman.manip.pixelInfo.prototype.putPixel = function (x, y, rgba) {
var newLoc = (y * this.manip.dimensions.width + x) * 4;
this.manip.pixel_data[newLoc] = rgba.r;
this.manip.pixel_data[newLoc+1] = rgba.g;
this.manip.pixel_data[newLoc+2] = rgba.b;
this.manip.pixel_data[newLoc+3] = rgba.a;
};
/*
* The CamanJS layering system
*/
Caman.manip.canvasQueue = [];
Caman.manip.newLayer = function (callback) {
var layer = new Caman.manip.canvasLayer(this);
this.canvasQueue.push(layer);
this.renderQueue.push({type: ProcessType.LAYER_DEQUEUE});
callback.call(layer);
this.renderQueue.push({type: ProcessType.LAYER_FINISHED});
return this;
};
Caman.manip.canvasLayer = function (manip) {
// Default options
this.options = {
blendingMode: 'normal',
opacity: 1.0
};
// Create a blank and invisible canvas and append it to the document
this.canvas = new Canvas(manip.dimensions.width, manip.dimensions.height);
this.context = this.canvas.getContext("2d");
this.context.createImageData(this.canvas.width, this.canvas.height);
this.image_data = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
this.pixel_data = this.image_data.data;
this.__defineGetter__("filter", function () {
return manip;
});
return this;
};
Caman.manip.canvasLayer.prototype.newLayer = function (callback) {
return this.filter.newLayer.call(this.filter, callback);
};
Caman.manip.canvasLayer.prototype.setBlendingMode = function (mode) {
this.options.blendingMode = mode;
return this;
};
Caman.manip.canvasLayer.prototype.opacity = function (opacity) {
this.options.opacity = (opacity / 100);
return this;
};
Caman.manip.canvasLayer.prototype.copyParent = function () {
var parentData = this.filter.pixel_data;
for (var i = 0; i < this.pixel_data.length; i += 4) {
this.pixel_data[i] = parentData[i];
this.pixel_data[i+1] = parentData[i+1];
this.pixel_data[i+2] = parentData[i+2];
this.pixel_data[i+3] = parentData[i+3];
}
return this;
};
Caman.manip.canvasLayer.prototype.fillColor = function () {
this.filter.fillColor.apply(this.filter, arguments);
return this;
};
Caman.manip.canvasLayer.prototype.overlayImage = function (image) {
if (typeof image === "object") {
image = image.src;
}
// Some problem, skip to prevent errors
if (!image) return;
this.filter.renderQueue.push({type: ProcessType.LOAD_OVERLAY, src: image, layer: this});
return this;
};
// Leaving this here for compatibility reasons. It is NO
// LONGER REQUIRED at the end of the layer.
Caman.manip.canvasLayer.prototype.render = function () {};
Caman.manip.canvasLayer.prototype.applyToParent = function () {
var parentData = this.filter.pixelStack[this.filter.pixelStack.length - 1],
layerData = this.filter.pixel_data,
rgbaParent = {},
rgbaLayer = {},
result = {};
for (var i = 0; i < layerData.length; i += 4) {
rgbaParent = {
r: parentData[i],
g: parentData[i+1],
b: parentData[i+2],
a: parentData[i+3]
};
rgbaLayer = {
r: layerData[i],
g: layerData[i+1],
b: layerData[i+2],
a: layerData[i+3]
};
result = this.blenders[this.options.blendingMode](rgbaLayer, rgbaParent);
parentData[i] = rgbaParent.r - ((rgbaParent.r - result.r) * (this.options.opacity * (result.a / 255)));
parentData[i+1] = rgbaParent.g - ((rgbaParent.g - result.g) * (this.options.opacity * (result.a / 255)));
parentData[i+2] = rgbaParent.b - ((rgbaParent.b - result.b) * (this.options.opacity * (result.a / 255)));
parentData[i+3] = 255;
}
};
// Blending functions
Caman.manip.canvasLayer.prototype.blenders = {
normal: function (rgbaLayer, rgbaParent) {
return {
r: rgbaLayer.r,
g: rgbaLayer.g,
b: rgbaLayer.b,
a: 255
};
},
multiply: function (rgbaLayer, rgbaParent) {
return {
r: (rgbaLayer.r * rgbaParent.r) / 255,
g: (rgbaLayer.g * rgbaParent.g) / 255,
b: (rgbaLayer.b * rgbaParent.b) / 255,
a: 255
};
},
screen: function (rgbaLayer, rgbaParent) {
return {
r: 255 - (((255 - rgbaLayer.r) * (255 - rgbaParent.r)) / 255),
g: 255 - (((255 - rgbaLayer.g) * (255 - rgbaParent.g)) / 255),
b: 255 - (((255 - rgbaLayer.b) * (255 - rgbaParent.b)) / 255),
a: 255
};
},
overlay: function (rgbaLayer, rgbaParent) {
var result = {};
result.r =
(rgbaParent.r > 128) ?
255 - 2 * (255 - rgbaLayer.r) * (255 - rgbaParent.r) / 255:
(rgbaParent.r * rgbaLayer.r * 2) / 255;
result.g =
(rgbaParent.g > 128) ?
255 - 2 * (255 - rgbaLayer.g) * (255 - rgbaParent.g) / 255:
(rgbaParent.g * rgbaLayer.g * 2) / 255;
result.b =
(rgbaParent.b > 128) ?
255 - 2 * (255 - rgbaLayer.b) * (255 - rgbaParent.b) / 255:
(rgbaParent.b * rgbaLayer.b * 2) / 255;
result.a = 255;
return result;
},
difference: function (rgbaLayer, rgbaParent) {
return {
r: rgbaLayer.r - rgbaParent.r,
g: rgbaLayer.g - rgbaParent.g,
b: rgbaLayer.b - rgbaParent.b,
a: 255
};
},
addition: function (rgbaLayer, rgbaParent) {
return {
r: rgbaParent.r + rgbaLayer.r,
g: rgbaParent.g + rgbaLayer.g,
b: rgbaParent.b + rgbaLayer.b,
a: 255
};
},
exclusion: function (rgbaLayer, rgbaParent) {
return {
r: 128 - 2 * (rgbaParent.r - 128) * (rgbaLayer.r - 128) / 255,
g: 128 - 2 * (rgbaParent.g - 128) * (rgbaLayer.g - 128) / 255,
b: 128 - 2 * (rgbaParent.b - 128) * (rgbaLayer.b - 128) / 255,
a: 255
};
},
softLight: function (rgbaLayer, rgbaParent) {
var result = {};
result.r =
(rgbaParent.r > 128) ?
255 - ((255 - rgbaParent.r) * (255 - (rgbaLayer.r - 128))) / 255 :
(rgbaParent.r * (rgbaLayer.r + 128)) / 255;
result.g =
(rgbaParent.g > 128) ?
255 - ((255 - rgbaParent.g) * (255 - (rgbaLayer.g - 128))) / 255 :
(rgbaParent.g * (rgbaLayer.g + 128)) / 255;
result.b = (rgbaParent.b > 128) ?
255 - ((255 - rgbaParent.b) * (255 - (rgbaLayer.b - 128))) / 255 :
(rgbaParent.b * (rgbaLayer.b + 128)) / 255;
result.a = 255;
return result;
}
};
Caman.manip.blenders = Caman.manip.canvasLayer.prototype.blenders;
/*
* Convolution kernel processing
*/
Caman.extend( Caman, {
processKernel: function (adjust, kernel, divisor, bias) {
var val = {
r: 0,
g: 0,
b: 0
};
for (var i = 0; i < adjust.length; i++) {
for (var j = 0; j < adjust[i].length; j++) {
val.r += (adjust[i][j] * kernel[i][j].r);
val.g += (adjust[i][j] * kernel[i][j].g);
val.b += (adjust[i][j] * kernel[i][j].b);
}
}
val.r = (val.r / divisor) + bias;
val.g = (val.g / divisor) + bias;
val.b = (val.b / divisor) + bias;
if (val.r > 255) {
val.r = 255;
} else if (val.r < 0) {
val.r = 0;
}
if (val.g > 255) {
val.g = 255;
} else if (val.g < 0) {
val.g = 0;
}
if (val.b > 255) {
val.b = 255;
} else if (val.b < 0) {
val.b = 0;
}
return val;
}
});
/*
* The core of the image rendering, this function executes
* the provided filter and updates the canvas pixel data
* accordingly. NOTE: this does not write the updated pixel
* data to the canvas. That happens when all filters are finished
* rendering in order to be as fast as possible.
*/
Caman.manip.executeFilter = function (adjust, processFn, type) {
var n = this.pixel_data.length,
res = null,
// (n/4) == # of pixels in image
// Give remaining pixels to last block in case it doesn't
// divide evenly.
blockPixelLength = Math.floor((n / 4) / Caman.renderBlocks),
// expand it again to make the loop easier.
blockN = blockPixelLength * 4,
// add the remainder pixels to the last block.
lastBlockN = blockN + ((n / 4) % Caman.renderBlocks) * 4,
self = this,
blocks_done = 0,
// Called whenever a block finishes. It's used to determine when all blocks
// finish rendering.
block_finished = function (bnum) {
if (bnum >= 0) {
console.log("Block #" + bnum + " finished! Filter: " + processFn.name);
}
blocks_done++;
if (blocks_done == Caman.renderBlocks || bnum == -1) {
if (bnum >= 0) {
console.log("Filter " + processFn.name + " finished!");
} else {
console.log("Kernel filter finished!");
}
Caman.trigger("processComplete", {id: self.canvas_id, completed: processFn.name});
self.processNext();
}
},
/*
* Renders a block of the image bounded by the start and end
* parameters.
*/
render_block = function (bnum, start, end) {
console.log("BLOCK #" + bnum + " - Filter: " + processFn.name + ", Start: " + start + ", End: " + end);
setTimeout(function () {
for (var i = start; i < end; i += 4) {
res = processFn.call(new self.pixelInfo(i, self), adjust, {
r: self.pixel_data[i],
g: self.pixel_data[i+1],
b: self.pixel_data[i+2],
a: self.pixel_data[i+3]
});
self.pixel_data[i] = res.r;
self.pixel_data[i+1] = res.g;
self.pixel_data[i+2] = res.b;
self.pixel_data[i+3] = res.a;
}
block_finished(bnum);
}, 0);
},
render_kernel = function () {
setTimeout(function () {
var kernel = [],
pixelInfo,
start, end,
mod_pixel_data = [],
name = adjust.name,
bias = adjust.bias,
divisor = adjust.divisor,
builder_start,
builder_end,
i, j, k;
adjust = adjust.adjust;
builder_start = (adjust.length - 1) / 2;
builder_end = builder_start * -1;
console.log("Rendering kernel - Filter: " + name);
start = self.dimensions.width * 4 * ((adjust.length - 1) / 2);
end = n - (self.dimensions.width * 4 * ((adjust.length - 1) / 2));
// Prepare the convolution kernel array
for (i = 0; i < adjust.length; i++) {
kernel[i] = [];
}
for (i = start; i < end; i += 4) {
pixelInfo = new self.pixelInfo(i, self);
// Fill the convolution kernel with values
for (j = builder_start; j >= builder_end; j--) {
for (k = builder_end; k <= builder_start; k++) {
kernel[k + ((adjust.length - 1) / 2)][((adjust.length - 1) / 2) - j] = pixelInfo.getPixelRelative(k, j);
}
}
// Execute the kernel processing function
res = processFn.call(pixelInfo, adjust, kernel, divisor, bias);
// Update the new pixel array since we can't modify the original
// until the convolutions are finished on the entire image.
mod_pixel_data[i] = res.r;
mod_pixel_data[i+1] = res.g;
mod_pixel_data[i+2] = res.b;
mod_pixel_data[i+3] = 255;
}
// Update the actual canvas pixel data
for (i = start; i < end; i++) {
self.pixel_data[i] = mod_pixel_data[i];
}
block_finished(-1);
}, 0);
};
Caman.trigger("processStart", {id: this.canvas_id, start: processFn.name});
if (type === ProcessType.SINGLE) {
// Split the image into its blocks.
for (var j = 0; j < Caman.renderBlocks; j++) {
var start = j * blockN,
end = start + ((j == Caman.renderBlocks - 1) ? lastBlockN : blockN);
render_block(j, start, end);
}
} else {
render_kernel();
}
};
Caman.manip.executeLayer = function (layer) {
this.pushContext(layer);
this.processNext();
};
Caman.manip.pushContext = function (layer) {
console.log("PUSH LAYER!");
this.layerStack.push(this.currentLayer);
this.pixelStack.push(this.pixel_data);
this.currentLayer = layer;
this.pixel_data = layer.pixel_data;
};
Caman.manip.popContext = function () {
console.log("POP LAYER!");
this.pixel_data = this.pixelStack.pop();
this.currentLayer = this.layerStack.pop();
};
Caman.manip.applyCurrentLayer = function () {
this.currentLayer.applyToParent();
};
Caman.manip.loadOverlay = function (layer, src) {
var self = this;
var img = new Image();
img.onload = function () {
layer.context.drawImage(img, 0, 0, self.dimensions.width, self.dimensions.height);
layer.image_data = layer.context.getImageData(0, 0, self.dimensions.width, self.dimensions.height);
layer.pixel_data = layer.image_data.data;
self.pixel_data = layer.pixel_data;
self.processNext();
};
img.src = src;
};
Caman.manip.process = function (adjust, processFn) {
// Since the block-based renderer is asynchronous, we simply build
// up a render queue and execute the filters in order once
// render() is called instead of executing them as they're called
// synchronously.
this.renderQueue.push({adjust: adjust, processFn: processFn, type: ProcessType.SINGLE});
return this;
};
Caman.manip.processKernel = function (name, adjust, divisor, bias) {
if (!divisor) {
divisor = 0;
for (var i = 0; i < adjust.length; i++) {
for (var j = 0; j < adjust[i].length; j++) {
divisor += adjust[i][j];
}
}
}
var data = {
name: name,
adjust: adjust,
divisor: divisor,
bias: bias || 0
};
this.renderQueue.push({adjust: data, processFn: Caman.processKernel, type: ProcessType.KERNEL});
return this;
};
/*
* Begins the render process if it's not started, or moves to the next
* filter in the queue and processes it. Calls the finishedFn callback
* when the render queue is empty.
*/
Caman.manip.processNext = function (finishedFn) {
if (typeof finishedFn === "function") {
this.finishedFn = finishedFn;
}
if (this.renderQueue.length === 0) {
Caman.trigger("renderFinished", {id: this.canvas_id});
if (typeof this.finishedFn === "function") {
this.finishedFn.call(this);
}
return;
}
var next = this.renderQueue.shift();
if (next.type == ProcessType.LAYER_DEQUEUE) {
var layer = this.canvasQueue.shift();
this.executeLayer(layer);
} else if (next.type == ProcessType.LAYER_FINISHED) {
this.applyCurrentLayer();
this.popContext();
this.processNext();
} else if (next.type == ProcessType.LOAD_OVERLAY) {
this.loadOverlay(next.layer, next.src);
} else {
this.executeFilter(next.adjust, next.processFn, next.type);
}
};
exports.Caman = Caman;
/*!
* These are all of the utility functions used in CamanJS
*/
(function (Caman) {
Caman.extend(Caman, {
/*
* Returns the size of an object (the number of properties
* the object has)
*/
sizeOf: function ( obj ) {
var size = 0,
prop;
for ( prop in obj ) {
size++;
}
return size;
},
/*
* Determines whether two given objects are the same based
* on their properties and values.
*/
sameAs: function ( base, test ) {
// only tests arrays
// TODO: extend to object tests
if ( base.length !== test.length ) {
return false;
}
for ( var i = base.length; i >= 0; i-- ) {
if ( base[i] !== test[i] ) {
return false;
}
}
return true;
},
isRemote: function (url) {
var domain_regex = /(?:(?:http|https):\/\/)((?:\w+)\.(?:(?:\w|\.)+))/,
test_domain;
if (!url || !url.length) {
return;
}
var matches = url.match(domain_regex);
if (matches) {
test_domain = matches[1];
return test_domain != document.domain;
} else {
return false;
}
},
/*
* Removes items with the given value from an array if they
* are present.
*/
remove: function ( arr, item ) {
var ret = [];
for ( var i = 0, len = arr.length; i < len; i++ ) {
if ( arr[i] !== item ) {
ret.push(arr[i]);
}
}
arr = ret;
return ret;
},
randomRange: function (min, max, float) {
var rand = min + (Math.random() * (max - min));
return typeof float == 'undefined' ? Math.round(rand) : rand.toFixed(float);
},
/**
* Converts an RGB color to HSL.
* Assumes r, g, and b are in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param Number r Red channel
* @param Number g Green channel
* @param Number b Blue channel
* @return The HSL representation
*/
rgb_to_hsl: function(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b),
h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {h: h, s: s, l: l};
},
hue_to_rgb: function (p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
},
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number l The lightness
* @return Array The RGB representation
*/
hsl_to_rgb: function(h, s, l){
var r, g, b;
if(s === 0){
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = this.hue_to_rgb(p, q, h + 1/3);
g = this.hue_to_rgb(p, q, h);
b = this.hue_to_rgb(p, q, h - 1/3);
}
return {r: r * 255, g: g * 255, b: b * 255};
},
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSV representation
*/
rgb_to_hsv: function(r, g, b){
r = r/255;
g = g/255;
b = b/255;
var max = Math.max(r, g, b), min = Math.min(r, g, b),
h, s, v = max,
d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min){
h = 0; // achromatic
} else {
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {h: h, s: s, v: v};
},
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number v The value
* @return Array The RGB representation
*/
hsv_to_rgb: function(h, s, v){
var r, g, b,
i = Math.floor(h * 6),
f = h * 6 - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s);
switch(i % 6){
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return {r: r * 255, g: g * 255, b: b * 255};
},
/**
* Converts a RGB color value to the XYZ color space. Formulas
* are based on http://en.wikipedia.org/wiki/SRGB assuming that
* RGB values are sRGB.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns x, y, and z.
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The XYZ representation
*/
rgb_to_xyz: function (r, g, b) {
r = r / 255; g = g / 255; b = b / 255;
if (r > 0.04045) {
r = Math.pow((r + 0.055) / 1.055, 2.4);
} else {
r = r / 12.92;
}
if (g > 0.04045) {
g = Math.pow((g + 0.055) / 1.055, 2.4);
} else {
g = g / 12.92;
}
if (b > 0.04045) {
b = Math.pow((b + 0.055) / 1.055, 2.4);
} else {
b = b / 12.92;
}
var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return {x: x * 100, y: y * 100, z: z * 100};
},
/**
* Converts a XYZ color value to the sRGB color space. Formulas
* are based on http://en.wikipedia.org/wiki/SRGB and the resulting
* RGB value will be in the sRGB color space.
* Assumes x, y and z values are whatever they are and returns
* r, g and b in the set [0, 255].
*
* @param Number x The X value
* @param Number y The Y value
* @param Number z The Z value
* @return Array The RGB representation
*/
xyz_to_rgb: function (x, y, z) {
x = x / 100; y = y / 100; z = z / 100;
var r, g, b;
r = (3.2406 * x) + (-1.5372 * y) + (-0.4986 * z);
g = (-0.9689 * x) + (1.8758 * y) + (0.0415 * z);
b = (0.0557 * x) + (-0.2040 * y) + (1.0570 * z);
if(r > 0.0031308) {
r = (1.055 * Math.pow(r, 0.4166666667)) - 0.055;
} else {
r = 12.92 * r;
}
if(g > 0.0031308) {
g = (1.055 * Math.pow(g, 0.4166666667)) - 0.055;
} else {
g = 12.92 * g;
}
if(b > 0.0031308) {
b = (1.055 * Math.pow(b, 0.4166666667)) - 0.055;
} else {
b = 12.92 * b;
}
return {r: r * 255, g: g * 255, b: b * 255};
},
/**
* Converts a XYZ color value to the CIELAB color space. Formulas
* are based on http://en.wikipedia.org/wiki/Lab_color_space
* The reference white point used in the conversion is D65.
* Assumes x, y and z values are whatever they are and returns
* L*, a* and b* values
*
* @param Number x The X value
* @param Number y The Y value
* @param Number z The Z value
* @return Array The Lab representation
*/
xyz_to_lab: function(x, y, z) {
// D65 reference white point
var whiteX = 95.047, whiteY = 100.0, whiteZ = 108.883;
x = x / whiteX; y = y / whiteY; z = z / whiteZ;
if (x > 0.008856451679) { // (6/29) ^ 3
x = Math.pow(x, 0.3333333333);
} else {
x = (7.787037037 * x) + 0.1379310345; // (1/3) * ((29/6) ^ 2)c + (4/29)
}
if (y > 0.008856451679) {
y = Math.pow(y, 0.3333333333);
} else {
y = (7.787037037 * y) + 0.1379310345;
}
if (z > 0.008856451679) {
z = Math.pow(z, 0.3333333333);
} else {
z = (7.787037037 * z) + 0.1379310345;
}
var l = 116 * y - 16;
var a = 500 * (x - y);
var b = 200 * (y - z);
return {l: l, a: a, b: b};
},
/**
* Converts a L*, a*, b* color values from the CIELAB color space
* to the XYZ color space. Formulas are based on
* http://en.wikipedia.org/wiki/Lab_color_space
* The reference white point used in the conversion is D65.
* Assumes L*, a* and b* values are whatever they are and returns
* x, y and z values.
*
* @param Number l The L* value
* @param Number a The a* value
* @param Number b The b* value
* @return Array The XYZ representation
*/
lab_to_xyz: function(l, a, b) {
var y = (l + 16) / 116;
var x = y + (a / 500);
var z = y - (b / 200);
if (x > 0.2068965517) { // 6 / 29
x = x * x * x;
} else {
x = 0.1284185493 * (x - 0.1379310345); // 3 * ((6 / 29) ^ 2) * (c - (4 / 29))
}
if (y > 0.2068965517) {
y = y * y * y;
} else {
y = 0.1284185493 * (y - 0.1379310345);
}
if (z > 0.2068965517) {
z = z * z * z;
} else {
z = 0.1284185493 * (z - 0.1379310345);
}
// D65 reference white point
return {x: x * 95.047, y: y * 100.0, z: z * 108.883};
},
/*
* Converts the hex representation of a color to RGB values.
* Hex value can optionally start with the hash (#).
*
* @param String hex The colors hex value
* @return Array The RGB representation
*/
hex_to_rgb: function(hex) {
var r, g, b;
if (hex.charAt(0) === "#") {
hex = hex.substr(1);
}
r = parseInt(hex.substr(0, 2), 16);
g = parseInt(hex.substr(2, 2), 16);
b = parseInt(hex.substr(4, 2), 16);
return {r: r, g: g, b: b};
},
bezier: function (start, ctrl1, ctrl2, end, lowBound, highBound) {
var Ax, Bx, Cx, Ay, By, Cy,
x0 = start[0], y0 = start[1],
x1 = ctrl1[0], y1 = ctrl1[1],
x2 = ctrl2[0], y2 = ctrl2[1],
x3 = end[0], y3 = end[1],
t, curveX, curveY,
bezier = {};
// Calculate our X and Y coefficients
Cx = 3 * (x1 - x0);
Bx = 3 * (x2 - x1) - Cx;
Ax = x3 - x0 - Cx - Bx;
Cy = 3 * (y1 - y0);
By = 3 * (y2 - y1) - Cy;
Ay = y3 - y0 - Cy - By;
for (var i = 0; i < 1000; i++) {
t = i / 1000;
curveX = Math.round((Ax * Math.pow(t, 3)) + (Bx * Math.pow(t, 2)) + (Cx * t) + x0);
curveY = Math.round((Ay * Math.pow(t, 3)) + (By * Math.pow(t, 2)) + (Cy * t) + y0);
if (lowBound && curveY < lowBound) {
curveY = lowBound;
} else if (highBound && curveY > highBound) {
curveY = highBound;
}
bezier[curveX] = curveY;
}
// Do a search for missing values in the bezier array and use linear interpolation
// to approximate their values.
var leftCoord, rightCoord, j, slope, bint;
if (bezier.length < end[0] + 1) {
for (i = 0; i <= end[0]; i++) {
if (typeof bezier[i] === "undefined") {
// The value to the left will always be defined. We don't have to worry about
// when i = 0 because the starting point is guaranteed (I think...)
leftCoord = [i-1, bezier[i-1]];
// Find the first value to the right that was found. Ideally this loop will break
// very quickly.
for (j = i; j <= end[0]; j++) {
if (typeof bezier[j] !== "undefined") {
rightCoord = [j, bezier[j]];
break;
}
}
bezier[i] = leftCoord[1] + ((rightCoord[1] - leftCoord[1]) / (rightCoord[0] - leftCoord[0])) * (i - leftCoord[0]);
}
}
}
// Edge case
if (typeof bezier[end[0]] === "undefined") {
bezier[end[0]] = bezier[254];
}
return bezier;
}
});
}(Caman));
/*!
* Below are all of the built-in filters that are a part
* of the CamanJS core library.
*/
(function(Caman) {
Caman.manip.fillColor = function () {
var color;
if (arguments.length == 1) {
color = Caman.hex_to_rgb(arguments[0]);
} else {
color = {
r: arguments[0],
g: arguments[1],
b: arguments[2]
};
}
return this.process( color, function fillColor(color, rgba) {
rgba.r = color.r;
rgba.g = color.g;
rgba.b = color.b;
rgba.a = 255;
return rgba;
});
};
Caman.manip.brightness = function(adjust) {
adjust = Math.floor(255 * (adjust / 100));
return this.process( adjust, function brightness(adjust, rgba) {
rgba.r += adjust;
rgba.g += adjust;
rgba.b += adjust;
return rgba;
});
};
Caman.manip.saturation = function(adjust) {
var max, diff;
adjust *= -1;
return this.process( adjust, function saturation(adjust, rgba) {
var chan;
max = Math.max(rgba.r, rgba.g, rgba.b);
for (chan in rgba) {
if (rgba.hasOwnProperty(chan)) {
if (rgba[chan] === max || chan === "a") {
continue;
}
diff = max - rgba[chan];
rgba[chan] += Math.ceil(diff * (adjust / 100));
}
}
return rgba;
});
};
Caman.manip.vibrance = function (adjust) {
var max, avg, amt, diff;
adjust *= -1;
return this.process( adjust, function vibrance(adjust, rgba) {
var chan;
max = Math.max(rgba.r, rgba.g, rgba.b);
// Calculate difference between max color and other colors
avg = (rgba.r + rgba.g + rgba.b) / 3;
amt = ((Math.abs(max - avg) * 2 / 255) * adjust) / 100;
for (chan in rgba) {
if (rgba.hasOwnProperty(chan)) {
if (rgba[chan] === max || chan == "a") {
continue;
}
diff = max - rgba[chan];
rgba[chan] += Math.ceil(diff * amt);
}
}
return rgba;
});
};
/*
* An improved greyscale function that should make prettier results
* than simply using the saturation filter to remove color. There are
* no arguments, it simply makes the image greyscale with no in-between.
*
* Algorithm adopted from http://www.phpied.com/image-fun/
*/
Caman.manip.greyscale = function () {
return this.process({}, function greyscale(adjust, rgba) {
var avg = 0.3 * rgba.r + 0.59 * rgba.g + 0.11 * rgba.b;
rgba.r = avg;
rgba.g = avg;
rgba.b = avg;
return rgba;
});
};
Caman.manip.contrast = function(adjust) {
adjust = (adjust + 100) / 100;
adjust = Math.pow(adjust, 2);
return this.process( adjust, function contrast(adjust, rgba) {
/* Red channel */
rgba.r /= 255;
rgba.r -= 0.5;
rgba.r *= adjust;
rgba.r += 0.5;
rgba.r *= 255;
/* Green channel */
rgba.g /= 255;
rgba.g -= 0.5;
rgba.g *= adjust;
rgba.g += 0.5;
rgba.g *= 255;
/* Blue channel */
rgba.b /= 255;
rgba.b -= 0.5;
rgba.b *= adjust;
rgba.b += 0.5;
rgba.b *= 255;
// While uglier, I found that using if statements are
// faster than calling Math.max() and Math.min() to bound
// the numbers.
if (rgba.r > 255) {
rgba.r = 255;
} else if (rgba.r < 0) {
rgba.r = 0;
}
if (rgba.g > 255) {
rgba.g = 255;
} else if (rgba.g < 0) {
rgba.g = 0;
}
if (rgba.b > 255) {
rgba.b = 255;
} else if (rgba.b < 0) {
rgba.b = 0;
}
return rgba;
});
};
Caman.manip.hue = function(adjust) {
var hsv, h;
return this.process( adjust, function hue(adjust, rgba) {
var rgb;
hsv = Caman.rgb_to_hsv(rgba.r, rgba.g, rgba.b);
h = hsv.h * 100;
h += Math.abs(adjust);
h = h % 100;
h /= 100;
hsv.h = h;
rgb = Caman.hsv_to_rgb(hsv.h, hsv.s, hsv.v);
return {r: rgb.r, g: rgb.g, b: rgb.b, a: rgba.a};
});
};
Caman.manip.colorize = function() {
var diff, rgb, level;
if (arguments.length === 2) {
rgb = Caman.hex_to_rgb(arguments[0]);
level = arguments[1];
} else if (arguments.length === 4) {
rgb = {
r: arguments[0],
g: arguments[1],
b: arguments[2]
};
level = arguments[3];
}
return this.process( [ level, rgb ], function colorize( adjust, rgba) {
// adjust[0] == level; adjust[1] == rgb;
rgba.r -= (rgba.r - adjust[1].r) * (adjust[0] / 100);
rgba.g -= (rgba.g - adjust[1].g) * (adjust[0] / 100);
rgba.b -= (rgba.b - adjust[1].b) * (adjust[0] / 100);
return rgba;
});
};
Caman.manip.invert = function () {
return this.process({}, function invert (adjust, rgba) {
rgba.r = 255 - rgba.r;
rgba.g = 255 - rgba.g;
rgba.b = 255 - rgba.b;
return rgba;
});
};
/*
* Applies a sepia filter to the image. Assumes adjustment is between 0 and 100,
* which represents how much the sepia filter is applied.
*/
Caman.manip.sepia = function (adjust) {
if (adjust === undefined) {
adjust = 100;
}
adjust = (adjust / 100);
return this.process(adjust, function sepia (adjust, rgba) {
rgba.r = Math.min(255, (rgba.r * (1 - (0.607 * adjust))) + (rgba.g * (0.769 * adjust)) + (rgba.b * (0.189 * adjust)));
rgba.g = Math.min(255, (rgba.r * (0.349 * adjust)) + (rgba.g * (1 - (0.314 * adjust))) + (rgba.b * (0.168 * adjust)));
rgba.b = Math.min(255, (rgba.r * (0.272 * adjust)) + (rgba.g * (0.534 * adjust)) + (rgba.b * (1- (0.869 * adjust))));
return rgba;
});
};
/*
* Adjusts the gamma of the image. I would stick with low values to be safe.
*/
Caman.manip.gamma = function (adjust) {
return this.process(adjust, function gamma(adjust, rgba) {
rgba.r = Math.pow(rgba.r / 255, adjust) * 255;
rgba.g = Math.pow(rgba.g / 255, adjust) * 255;
rgba.b = Math.pow(rgba.b / 255, adjust) * 255;
return rgba;
});
};
/*
* Adds noise to the image on a scale from 1 - 100
* However, the scale isn't constrained, so you can specify
* a value > 100 if you want a LOT of noise.
*/
Caman.manip.noise = function (adjust) {
adjust = Math.abs(adjust) * 2.55;
return this.process(adjust, function noise(adjust, rgba) {
var rand = Caman.randomRange(adjust*-1, adjust);
rgba.r += rand;
rgba.g += rand;
rgba.b += rand;
return rgba;
});
};
/*
* Clips a color to max values when it falls outside of the specified range.
* User supplied value should be between 0 and 100.
*/
Caman.manip.clip = function (adjust) {
adjust = Math.abs(adjust) * 2.55;
return this.process(adjust, function clip(adjust, rgba) {
if (rgba.r > 255 - adjust) {
rgba.r = 255;
} else if (rgba.r < adjust) {
rgba.r = 0;
}
if (rgba.g > 255 - adjust) {
rgba.g = 255;
} else if (rgba.g < adjust) {
rgba.g = 0;
}
if (rgba.b > 255 - adjust) {
rgba.b = 255;
} else if (rgba.b < adjust) {
rgba.b = 0;
}
return rgba;
});
};
/*
* Lets you modify the intensity of any combination of red, green, or blue channels.
* Options format (must specify 1 - 3 colors):
* {
* red: 20,
* green: -5,
* blue: -40
* }
*/
Caman.manip.channels = function (options) {
if (typeof(options) !== 'object') {
return;
}
for (var chan in options) {
if (options.hasOwnProperty(chan)) {
if (options[chan] === 0) {
delete options[chan];
continue;
}
options[chan] = options[chan] / 100;
}
}
if (options.length === 0) {
return;
}
return this.process(options, function channels(options, rgba) {
if (options.red) {
if (options.red > 0) {
// fraction of the distance between current color and 255
rgba.r = rgba.r + ((255 - rgba.r) * options.red);
} else {
rgba.r = rgba.r - (rgba.r * Math.abs(options.red));
}
}
if (options.green) {
if (options.green > 0) {
rgba.g = rgba.g + ((255 - rgba.g) * options.green);
} else {
rgba.g = rgba.g - (rgba.g * Math.abs(options.green));
}
}
if (options.blue) {
if (options.blue > 0) {
rgba.b = rgba.b + ((255 - rgba.b) * options.blue);
} else {
rgba.b = rgba.b - (rgba.b * Math.abs(options.blue));
}
}
return rgba;
});
};
/*
* Curves implementation using Bezier curve equation.
*
* Params:
* chan - [r, g, b, rgb]
* start - [x, y] (start of curve; 0 - 255)
* ctrl1 - [x, y] (control point 1; 0 - 255)
* ctrl2 - [x, y] (control point 2; 0 - 255)
* end - [x, y] (end of curve; 0 - 255)
*/
Caman.manip.curves = function (chan, start, ctrl1, ctrl2, end) {
var bezier, i;
if (typeof chan === 'string') {
if (chan == 'rgb') {
chan = ['r', 'g', 'b'];
} else {
chan = [chan];
}
}
bezier = Caman.bezier(start, ctrl1, ctrl2, end, 0, 255);
// If our curve starts after x = 0, initialize it with a flat line until
// the curve begins.
if (start[0] > 0) {
for (i = 0; i < start[0]; i++) {
bezier[i] = start[1];
}
}
// ... and the same with the end point
if (end[0] < 255) {
for (i = end[0]; i <= 255; i++) {
bezier[i] = end[1];
}
}
return this.process({bezier: bezier, chans: chan}, function curves(opts, rgba) {
for (var i = 0; i < opts.chans.length; i++) {
rgba[opts.chans[i]] = opts.bezier[rgba[opts.chans[i]]];
}
return rgba;
});
};
/*
* Adjusts the exposure of the image by using the curves function.
*/
Caman.manip.exposure = function (adjust) {
var p, ctrl1, ctrl2;
p = Math.abs(adjust) / 100;
ctrl1 = [0, (255 * p)];
ctrl2 = [(255 - (255 * p)), 255];
if (adjust < 0) {
ctrl1 = ctrl1.reverse();
ctrl2 = ctrl2.reverse();
}
return this.curves('rgb', [0, 0], ctrl1, ctrl2, [255, 255]);
};
}(Caman));
/*global Caman: true, exports: true */
/*
* NodeJS compatibility
*/
if (!Caman && typeof exports == "object") {
var Caman = {manip:{}};
exports.plugins = Caman.manip;
}
(function (Caman) {
Caman.manip.boxBlur = function () {
return this.processKernel('Box Blur', [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]);
};
Caman.manip.radialBlur = function () {
return this.processKernel('Radial Blur', [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
], 5);
};
Caman.manip.heavyRadialBlur = function () {
return this.processKernel('Heavy Radial Blur', [
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0]
], 13);
};
Caman.manip.gaussianBlur = function () {
return this.processKernel('Gaussian Blur', [
[1, 4, 6, 4, 1],
[4, 16, 24, 16, 4],
[6, 24, 36, 24, 6],
[4, 16, 24, 16, 4],
[1, 4, 6, 4, 1]
], 256);
};
Caman.manip.motionBlur = function (degrees) {
var kernel;
if (degrees === 0 || degrees == 180) {
kernel = [
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]
];
} else if ((degrees > 0 && degrees < 90) || (degrees > 180 && degrees < 270)) {
kernel = [
[0, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0],
[1, 0, 0, 0, 0]
];
} else if (degrees == 90 || degrees == 270) {
kernel = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
} else {
kernel = [
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]
];
}
return this.processKernel('Motion Blur', kernel, 5);
};
Caman.manip.sharpen = function (amt) {
if (!amt) {
amt = 1;
} else {
amt /= 100;
}
return this.processKernel('Sharpen', [
[0, -amt, 0],
[-amt, 4 * amt + 1, -amt],
[0, -amt, 0]
]);
};
}(Caman));
/*global Caman: true, exports: true */
/*
* NodeJS compatibility
*/
if (!Caman && typeof exports == "object") {
var Caman = {manip:{}};
exports.plugins = Caman.manip;
}
(function (Caman) {
/*
* If size is a string and ends with %, its a percentage. Otherwise,
* its an absolute number of pixels.
*/
Caman.manip.vignette = function (size, strength) {
var center, start, end, loc, dist, div, bezier;
if (typeof size === "string" && size.substr(-1) == "%") {
if (this.dimensions.height > this.dimensions.width) {
size = this.dimensions.width * (Number(size.substr(0, size.length - 1)) / 100);
} else {
size = this.dimensions.height * (Number(size.substr(0, size.length - 1)) / 100);
}
}
if (!strength) {
strength = 0.6;
} else {
strength /= 100;
}
center = [(this.dimensions.width / 2), (this.dimensions.height / 2)];
// start = darkest part
start = Math.sqrt(Math.pow(center[0], 2) + Math.pow(center[1], 2)); // corner to center dist
// end = lightest part (0 vignette)
end = start - size;
bezier = Caman.bezier([0, 1], [30, 30], [70, 60], [100, 80]);
return this.process({center: center, start: start, end: end, size: size, strength: strength, bezier: bezier}, function vignette(data, rgba) {
// current pixel coordinates
loc = this.locationXY();
// distance between center of image and current pixel
dist = Math.sqrt(Math.pow(loc.x - data.center[0], 2) + Math.pow(loc.y - data.center[1], 2));
if (dist > data.end) {
// % of vignette
div = Math.max(1, ((data.bezier[Math.round(((dist - data.end) / data.size) * 100)]/10) * strength));
// Use gamma to adjust the vignette - much better results
rgba.r = Math.pow(rgba.r / 255, div) * 255;
rgba.g = Math.pow(rgba.g / 255, div) * 255;
rgba.b = Math.pow(rgba.b / 255, div) * 255;
}
return rgba;
});
};
}(Caman));
/*global Caman: true, exports: true */
/*
* NodeJS compatibility
*/
if (!Caman && typeof exports == "object") {
var Caman = {manip:{}};
exports.plugins = Caman.manip;
}
(function (Caman) {
Caman.manip.edgeEnhance = function () {
return this.processKernel('Edge Enhance', [
[0, 0, 0],
[-1, 1, 0],
[0, 0, 0]
]);
};
Caman.manip.edgeDetect = function () {
return this.processKernel('Edge Detect', [
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
]);
};
Caman.manip.emboss = function () {
return this.processKernel('Emboss', [
[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]
]);
};
}(Caman));
/*global Caman: true, exports: true */
/*
* NodeJS compatibility
*/
if (!Caman && typeof exports == "object") {
var Caman = {manip:{}};
exports.plugins = Caman.manip;
}
(function (Caman) {
Caman.manip.vintage = function (vignette) {
this
.greyscale()
.contrast(5)
.noise(3)
.sepia(100)
.channels({red: 8, blue: 2, green: 4})
.gamma(0.87);
if (vignette || typeof vignette === 'undefined') {
this.vignette("40%", 30);
}
return this;
};
Caman.manip.lomo = function() {
return this
.brightness(15)
.exposure(15)
.curves('rgb', [0, 0], [200, 0], [155, 255], [255, 255])
.saturation(-20)
.gamma(1.8)
.vignette("50%", 60)
.brightness(5);
};
Caman.manip.clarity = function (grey) {
var manip = this
.vibrance(20)
.curves('rgb', [5, 0], [130, 150], [190, 220], [250, 255])
.sharpen(15)
.vignette("45%", 20);
if (grey) {
this
.greyscale()
.contrast(4);
}
return manip;
};
Caman.manip.sinCity = function () {
return this
.contrast(100)
.brightness(15)
.exposure(10)
.curves('rgb', [0,0], [100, 0], [155, 255], [255, 255])
.clip(30)
.greyscale();
};
Caman.manip.sunrise = function () {
return this
.exposure(3.5)
.saturation(-5)
.vibrance(50)
.sepia(60)
.colorize('#e87b22', 10)
.channels({red: 8, blue: 8})
.contrast(5)
.gamma(1.2)
.vignette("55%", 25);
};
Caman.manip.crossProcess = function () {
return this
.exposure(5)
.colorize('#e87b22', 4)
.sepia(20)
.channels({blue: 8, red: 3})
.curves('b', [0, 0], [100, 150], [180, 180], [255, 255])
.contrast(15)
.vibrance(75)
.gamma(1.6);
};
Caman.manip.orangePeel = function () {
return this
.curves('rgb', [0, 0], [100, 50], [140, 200], [255, 255])
.vibrance(-30)
.saturation(-30)
.colorize('#ff9000', 30)
.contrast(-5)
.gamma(1.4);
};
Caman.manip.love = function () {
return this
.brightness(5)
.exposure(8)
.colorize('#c42007', 30)
.vibrance(50)
.gamma(1.3);
};
Caman.manip.grungy = function () {
return this
.gamma(1.5)
.clip(25)
.saturation(-60)
.contrast(5)
.noise(5)
.vignette("50%", 30);
};
Caman.manip.jarques = function () {
return this
.saturation(-35)
.curves('b', [20, 0], [90, 120], [186, 144], [255, 230])
.curves('r', [0, 0], [144, 90], [138, 120], [255, 255])
.curves('g', [10, 0], [115, 105], [148, 100], [255, 248])
.curves('rgb', [0, 0], [120, 100], [128, 140], [255, 255])
.sharpen(20);
};
Caman.manip.pinhole = function () {
return this
.greyscale()
.sepia(10)
.exposure(10)
.contrast(15)
.vignette("60%", 35);
};
Caman.manip.oldBoot = function () {
return this
.saturation(-20)
.vibrance(-50)
.gamma(1.1)
.sepia(30)
.channels({red: -10, blue: 5})
.curves('rgb', [0, 0], [80, 50], [128, 230], [255, 255])
.vignette("60%", 30);
};
Caman.manip.glowingSun = function () {
this.brightness(10);
this.newLayer(function () {
this.setBlendingMode('multiply');
this.opacity(80);
this.copyParent();
this.filter.gamma(0.8);
this.filter.contrast(50);
this.filter.exposure(10);
});
this.newLayer(function () {
this.setBlendingMode('softLight');
this.opacity(80);
this.fillColor('#f49600');
});
this.exposure(20);
this.gamma(0.8);
return this.vignette("45%", 20);
};
Caman.manip.hazyDays = function () {
this.gamma(1.2);
this.newLayer(function () {
this.setBlendingMode('overlay');
this.opacity(60);
this.copyParent();
this.filter.channels({red: 5});
this.filter.heavyRadialBlur();
});
this.newLayer(function () {
this.setBlendingMode('addition');
this.opacity(40);
this.fillColor('#6899ba');
});
this.newLayer(function () {
this.setBlendingMode('multiply');
this.opacity(35);
this.copyParent();
this.filter.brightness(40);
this.filter.vibrance(40);
this.filter.exposure(30);
this.filter.contrast(15);
this.filter.curves('r', [0, 40], [128, 128], [128, 128], [255, 215]);
this.filter.curves('g', [0, 40], [128, 128], [128, 128], [255, 215]);
this.filter.curves('b', [0, 40], [128, 128], [128, 128], [255, 215]);
this.filter.gaussianBlur();
});
this.curves('r', [20, 0], [128, 158], [128, 128], [235, 255]);
this.curves('g', [20, 0], [128, 128], [128, 128], [235, 255]);
this.curves('b', [20, 0], [128, 108], [128, 128], [235, 255]);
return this.vignette("45%", 20);
};
}(Caman)); |
var ImageDialog = {
preInit : function() {
var url;
tinyMCEPopup.requireLangPack();
if (url = tinyMCEPopup.getParam("external_image_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '180px';
e = ed.selection.getNode();
this.fillFileList('image_list', 'tinyMCEImageList');
if (e.nodeName == 'IMG') {
f.src.value = ed.dom.getAttrib(e, 'src');
f.alt.value = ed.dom.getAttrib(e, 'alt');
f.border.value = this.getAttrib(e, 'border');
f.vspace.value = this.getAttrib(e, 'vspace');
f.hspace.value = this.getAttrib(e, 'hspace');
f.width.value = ed.dom.getAttrib(e, 'width');
f.height.value = ed.dom.getAttrib(e, 'height');
f.insert.value = ed.getLang('update');
this.styleVal = ed.dom.getAttrib(e, 'style');
selectByValue(f, 'image_list', f.src.value);
selectByValue(f, 'align', this.getAttrib(e, 'align'));
this.updateStyle();
}
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
update : function() {
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el;
tinyMCEPopup.restoreSelection();
if (f.src.value === '') {
if (ed.selection.getNode().nodeName == 'IMG') {
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
if (!ed.settings.inline_styles) {
args = tinymce.extend(args, {
vspace : nl.vspace.value,
hspace : nl.hspace.value,
border : nl.border.value,
align : getSelectValue(f, 'align')
});
} else
args.style = this.styleVal;
tinymce.extend(args, {
src : f.src.value,
alt : f.alt.value,
width : f.width.value,
height : f.height.value
});
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
} else {
ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
ed.dom.setAttribs('__mce_tmp', args);
ed.dom.setAttrib('__mce_tmp', 'id', '');
ed.undoManager.add();
}
tinyMCEPopup.close();
},
updateStyle : function() {
var dom = tinyMCEPopup.dom, st, v, f = document.forms[0];
if (tinyMCEPopup.editor.settings.inline_styles) {
st = tinyMCEPopup.dom.parseStyle(this.styleVal);
// Handle align
v = getSelectValue(f, 'align');
if (v) {
if (v == 'left' || v == 'right') {
st['float'] = v;
delete st['vertical-align'];
} else {
st['vertical-align'] = v;
delete st['float'];
}
} else {
delete st['float'];
delete st['vertical-align'];
}
// Handle border
v = f.border.value;
if (v || v == '0') {
if (v == '0')
st['border'] = '0';
else
st['border'] = v + 'px solid black';
} else
delete st['border'];
// Handle hspace
v = f.hspace.value;
if (v) {
delete st['margin'];
st['margin-left'] = v + 'px';
st['margin-right'] = v + 'px';
} else {
delete st['margin-left'];
delete st['margin-right'];
}
// Handle vspace
v = f.vspace.value;
if (v) {
delete st['margin'];
st['margin-top'] = v + 'px';
st['margin-bottom'] = v + 'px';
} else {
delete st['margin-top'];
delete st['margin-bottom'];
}
// Merge
st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img');
this.styleVal = dom.serializeStyle(st, 'img');
}
},
getAttrib : function(e, at) {
var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;
if (ed.settings.inline_styles) {
switch (at) {
case 'align':
if (v = dom.getStyle(e, 'float'))
return v;
if (v = dom.getStyle(e, 'vertical-align'))
return v;
break;
case 'hspace':
v = dom.getStyle(e, 'margin-left')
v2 = dom.getStyle(e, 'margin-right');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'vspace':
v = dom.getStyle(e, 'margin-top')
v2 = dom.getStyle(e, 'margin-bottom');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'border':
v = 0;
tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
sv = dom.getStyle(e, 'border-' + sv + '-width');
// False or not the same as prev
if (!sv || (sv != v && v !== 0)) {
v = 0;
return false;
}
if (sv)
v = sv;
});
if (v)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
}
}
if (v = dom.getAttrib(e, at))
return v;
return '';
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = "";
},
updateImageData : function() {
var f = document.forms[0], t = ImageDialog;
if (f.width.value == "")
f.width.value = t.preloadImg.width;
if (f.height.value == "")
f.height.value = t.preloadImg.height;
},
getImageData : function() {
var f = document.forms[0];
this.preloadImg = new Image();
this.preloadImg.onload = this.updateImageData;
this.preloadImg.onerror = this.resetImageData;
this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value);
}
};
ImageDialog.preInit();
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
|
// open websocket
var host = location.origin.replace(/^http/, 'ws'),
socket = new WebSocket(host);
socket.onopen = function(){
var message = {
clientType: 'scoreboard'
};
if (socket.readyState === 1) {
socket.send(JSON.stringify(message));
}
};
socket.onmessage = function(msg){
var data = JSON.parse(msg.data);
if (data.gameInit){
$('#home-label').text(data.gameInit.home.label);
$('#away-label').text(data.gameInit.away.label);
$('#home-timeleft').text(data.gameInit.home.time);
$('#away-timeleft').text(data.gameInit.away.time);
$('#home-percentage').text(data.gameInit.home.percentage);
$('#away-percentage').text(data.gameInit.away.percentage);
$('#progress-home').css({ width : data.gameInit.home.percentage + '%' });
$('#progress-away').css({ width : data.gameInit.away.percentage + '%' });
// SYNC game status here...
} else if (data.showRound) {
var roundPoints = 0;
$.each(data.showRound.points, function(index, point){
roundPoints += point.point;
addJuryPoint(point.theme);
});
$('.home-screen').addClass('hidden');
$('.round-screen').removeClass('hidden');
$('.round-screen .team-name').text(data.teamName);
$('.round-screen .game-title').text(data.showRound.game);
$('.round-screen .suggestions-titles').text(data.showRound.suggestions.join(', '));
$('.round-screen .points').text(roundPoints);
$('.round-screen .time').text(data.timeLeft);
} else if (data.hideRound){
$('.home-screen').removeClass('hidden');
$('.round-screen').addClass('hidden');
clearJuryPoints();
// SYNC game status here...
} else if (data.updatePoints){
var roundPoints = 0;
$.each(data.updatePoints, function(index, point){
roundPoints += point.point;
});
var addedPoint = data.updatePoints[data.updatePoints.length - 1];
addJuryPoint(addedPoint.theme);
highlightJuryPoints(addedPoint);
$('.round-screen .points').text(roundPoints);
} else if (data.updateTime){
$('.round-screen .time').text(data.updateTime);
// UPDATE time
}
};
function addJuryPoint(theme){
var themeEl = $('.' + theme);
if (themeEl.find('span').length){
var currentMultiplier = parseInt(themeEl.find('span').text() ,10);
themeEl.find('span').text(currentMultiplier + 1);
} else {
themeEl.addClass('active');
themeEl.html('<span class="multiplier">1</span>');
}
}
function clearJuryPoints(){
var elements = $('.bonus > div, .penalty > div');
elements.each(function(index, el){
$(el).empty();
$(el).removeClass('active');
})
}
function highlightJuryPoints(point){
var text = '';
var juryAction = $('.jury-action');
switch (point.theme){
case 'funny':
text = 'Grappig';
break;
case 'finish':
text = 'Mooi einde';
break;
case 'emotions':
text = 'Emotioneel spel';
break;
case 'teamwork':
text = 'Goede samenwerking';
break;
case 'spectacle':
text = 'Spectaculaire actie';
break;
case 'rude':
text = 'Nodeloos grof';
break;
case 'boring':
text = 'Saai';
break;
case 'explanation':
text = 'Teveel uitleg';
break;
case 'confusing':
text = 'Verwarrend';
break;
case 'garbage':
text = 'Negeren';
break;
}
juryAction.addClass(point.theme);
juryAction.addClass('active');
juryAction.text(text);
setTimeout(function(){
juryAction.removeClass('active');
}, 3000);
setTimeout(function(){
juryAction.text('');
juryAction.removeClass(point.theme);
}, 4000);
} |
define([
"rishson/widget/_Widget", //mixin
"rishson/util/ObjectValidator", //validate
"dijit/_TemplatedMixin", //mixin
"dijit/_WidgetsInTemplateMixin", //mixin
"dojo/text!rishson/view/simpleFooter/SimpleFooter.html", //template
"dojo/_base/declare" // declare + safeMixin
], function (_Widget, ObjectValidator, _TemplatedMixin, _WidgetsInTemplateMixin, template, declare) {
/**
* @class
* @name rishson.view.SimpleFooter
* @description An example widget that acts as a footer to a single page application.
*/
return declare('rishson.view.SimpleFooter', [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: template,
/**
* @field
* @name rishson.view.SimpleFooter.footerText
* @type {string}
* @description the text to place into the footer
*/
footerText: '',
/**
* @field
* @name rishson.view.SimpleFooter.footerLink
* @type {string}
* @description the href for the footer link
*/
footerLink: '',
/**
* @constructor
* @param {{footerText : string, footerLink : string}} params contains the footer link and footer text
*/
constructor: function (params) {
var criteria = [
{paramName: 'footerText', paramType: 'string'},
{paramName: 'footerLink', paramType: 'string'}
],
validator = new ObjectValidator(criteria);
if (validator.validate(params)) {
declare.safeMixin(this, params);
} else {
validator.logErrorToConsole(params, 'Invalid params passed to the SimpleFooter.');
throw ('Invalid params passed to the SimpleFooter.');
}
}
});
}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = require('../utils');
exports.default = () => {
const teams = new Map();
return {
forEach: callback => teams.forEach(callback),
installedTeam: async installInfo => {
let team = teams.get(installInfo.team.id);
if (!team) {
team = (0, _utils.createTeam)(installInfo);
teams.set(team.id, team);
} else {
team = (0, _utils.updateTeam)(team, installInfo);
teams.set(team.id, team);
}
return team;
}
};
};
//# sourceMappingURL=index.js.map |
import { resolve } from 'path';
import Node from './Node';
import Chain from './Chain';
export function load ( file, options ) {
const { node, sourcesContentByPath, sourceMapByPath } = init( file, options );
return node.load( sourcesContentByPath, sourceMapByPath )
.then( () => node.isOriginalSource ? null : new Chain( node, sourcesContentByPath ) );
}
export function loadSync ( file, options = {} ) {
const { node, sourcesContentByPath, sourceMapByPath } = init( file, options );
node.loadSync( sourcesContentByPath, sourceMapByPath );
return node.isOriginalSource ? null : new Chain( node, sourcesContentByPath );
}
function init ( file, options = {} ) {
const node = new Node({ file });
let sourcesContentByPath = {};
let sourceMapByPath = {};
if ( options.content ) {
Object.keys( options.content ).forEach( key => {
sourcesContentByPath[ resolve( key ) ] = options.content[ key ];
});
}
if ( options.sourcemaps ) {
Object.keys( options.sourcemaps ).forEach( key => {
sourceMapByPath[ resolve( key ) ] = options.sourcemaps[ key ];
});
}
return { node, sourcesContentByPath, sourceMapByPath };
} |
var time = process.hrtime;
var uuid = require('uuid');
var async = require('async');
var LocalStorage = require('node-localstorage').LocalStorage;
var StorageLRU = require('storage-lru').StorageLRU;
var localStorage = new LocalStorage('./');
var cache = new StorageLRU(localStorage);
console.log('%s %s %s %s', 'Iterations', 'Average (ms)', 'Total (ms)', 'Memory Usage (bytes)');
var start, prev; start = prev = time();
var memory = process.memoryUsage().heapUsed;
for (var i = 1; i <= 1e6; i++) {
var wait = true;
cache.setItem(i, { key: i, value: uuid.v4() }, { json: true, cacheControl: 'max-age=999999' }, function (error) { wait = false; });
while (wait) {}
if (i % 1e4 === 0) {
console.log('%d %d %d %d', i, ms(time(prev)) / 1e4, ms(time(start)), process.memoryUsage().heapUsed - memory);
prev = time();
}
}
localStorage._deleteLocation();
function ms(tuple) {
return tuple[0] * 1e3 + tuple[1] / 1e6;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.