code
stringlengths 2
1.05M
|
---|
/**
* Generic require login routing middleware
*/
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.send(401, 'User is not authorized');
}
next();
};
/**
* User authorizations routing middleware
*/
exports.user = {
hasAuthorization: function(req, res, next) {
if (req.profile.id != req.user.id) {
return res.send(401, 'User is not authorized');
}
next();
}
};
/**
* Article authorizations routing middleware
*/
exports.article = {
hasAuthorization: function(req, res, next) {
if (req.article.user.id != req.user.id) {
return res.send(401, 'User is not authorized');
}
next();
}
};
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'blockquote', 'th', {
toolbar: 'Block Quote'
} );
|
var gulp = require('gulp'),
sass = require('gulp-sass'),
uglify = require('gulp-uglify'),
autoprefixer = require('gulp-autoprefixer'),
minifyCss = require('gulp-minify-css'),
rename = require('gulp-rename'),
filter = require('gulp-filter'),
util = require('gulp-util'),
imagemin = require('gulp-imagemin'),
browserSync = require('browser-sync').create();
gulp.task('build', ['sass', 'uglify', 'svg']);
gulp.task('serve', ['sass', 'uglify', 'svg'], function() {
browserSync.init(['**/*.html', '**/*.css', '**/*.js'], {
server: "."
});
gulp.watch('scss/**/*.scss', ['sass']);
gulp.watch('js/rrssb.js', ['uglify']);
});
gulp.task('sass', function() {
gulp.src(['scss/**/*.scss'])
.pipe(sass())
.on('error', util.log)
.pipe(autoprefixer())
.pipe(minifyCss())
.pipe(gulp.dest('css/'));
});
gulp.task('uglify', function() {
gulp.src(['js/rrssb.js'])
.pipe(uglify())
.on('error', util.log)
.pipe(rename({
extname: '.min.js'
}))
.pipe(gulp.dest('js'));
});
gulp.task('svg', function() {
gulp.src(['icons/**/*.svg', '!icons/**/*.min.svg'])
.pipe(imagemin())
.on('error', util.log)
.pipe(rename({
extname: '.min.svg'
}))
.pipe(gulp.dest('icons/'));
});
gulp.task('default', ['serve']);
|
/*!
* Inferno v1.3.0-rc.10
* (c) 2017 Dominic Gannaway'
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.Inferno = global.Inferno || {})));
}(this, (function (exports) { 'use strict';
var NO_OP = '$NO_OP';
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
var isBrowser = typeof window !== 'undefined' && window.document;
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
var isArray = Array.isArray;
function isStatefulComponent(o) {
return !isUndefined(o.prototype) && !isUndefined(o.prototype.render);
}
function isStringOrNumber(obj) {
var type = typeof obj;
return type === 'string' || type === 'number';
}
function isNullOrUndef(obj) {
return isUndefined(obj) || isNull(obj);
}
function isInvalid(obj) {
return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj);
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isAttrAnEvent(attr) {
return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3;
}
function isString(obj) {
return typeof obj === 'string';
}
function isNumber(obj) {
return typeof obj === 'number';
}
function isNull(obj) {
return obj === null;
}
function isTrue(obj) {
return obj === true;
}
function isUndefined(obj) {
return obj === undefined;
}
function isObject(o) {
return typeof o === 'object';
}
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
function warning(message) {
console.warn(message);
}
function assign(target) {
var arguments$1 = arguments;
for (var i = 1, argumentsLength = arguments.length; i < argumentsLength; i++) {
var obj = arguments$1[i];
if (!isNullOrUndef(obj)) {
var keys = Object.keys(obj);
for (var j = 0, keysLength = keys.length; j < keysLength; j++) {
var key = keys[j];
target[key] = obj[key];
}
}
}
return target;
}
function Lifecycle() {
this.listeners = [];
}
Lifecycle.prototype.addListener = function addListener(callback) {
this.listeners.push(callback);
};
Lifecycle.prototype.trigger = function trigger() {
var listeners = this.listeners;
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i]();
}
};
function applyKey(key, vNode) {
vNode.key = key;
return vNode;
}
function applyKeyIfMissing(key, vNode) {
if (isNumber(key)) {
key = "." + key;
}
if (isNull(vNode.key) || vNode.key[0] === '.') {
return applyKey(key, vNode);
}
return vNode;
}
function applyKeyPrefix(key, vNode) {
vNode.key = key + vNode.key;
return vNode;
}
function _normalizeVNodes(nodes, result, index, currentKey) {
for (var len = nodes.length; index < len; index++) {
var n = nodes[index];
var key = currentKey + "." + index;
if (!isInvalid(n)) {
if (isArray(n)) {
_normalizeVNodes(n, result, 0, key);
}
else {
if (isStringOrNumber(n)) {
n = createTextVNode(n, null);
}
else if (isVNode(n) && n.dom || (n.key && n.key[0] === '.')) {
n = cloneVNode(n);
}
if (isNull(n.key) || n.key[0] === '.') {
n = applyKey(key, n);
}
else {
n = applyKeyPrefix(currentKey, n);
}
result.push(n);
}
}
}
}
function normalizeVNodes(nodes) {
var newNodes;
// we assign $ which basically means we've flagged this array for future note
// if it comes back again, we need to clone it, as people are using it
// in an immutable way
// tslint:disable
if (nodes['$']) {
nodes = nodes.slice();
}
else {
nodes['$'] = true;
}
// tslint:enable
for (var i = 0, len = nodes.length; i < len; i++) {
var n = nodes[i];
if (isInvalid(n) || isArray(n)) {
var result = (newNodes || nodes).slice(0, i);
_normalizeVNodes(nodes, result, i, "");
return result;
}
else if (isStringOrNumber(n)) {
if (!newNodes) {
newNodes = nodes.slice(0, i);
}
newNodes.push(applyKeyIfMissing(i, createTextVNode(n, null)));
}
else if ((isVNode(n) && n.dom) || (isNull(n.key) && !(n.flags & 64 /* HasNonKeyedChildren */))) {
if (!newNodes) {
newNodes = nodes.slice(0, i);
}
newNodes.push(applyKeyIfMissing(i, cloneVNode(n)));
}
else if (newNodes) {
newNodes.push(applyKeyIfMissing(i, cloneVNode(n)));
}
}
return newNodes || nodes;
}
function normalizeChildren(children) {
if (isArray(children)) {
return normalizeVNodes(children);
}
else if (isVNode(children) && children.dom) {
return cloneVNode(children);
}
return children;
}
function normalizeProps(vNode, props, children) {
if (!(vNode.flags & 28 /* Component */) && isNullOrUndef(children) && !isNullOrUndef(props.children)) {
vNode.children = props.children;
}
if (props.ref) {
vNode.ref = props.ref;
delete props.ref;
}
if (props.events) {
vNode.events = props.events;
}
if (!isNullOrUndef(props.key)) {
vNode.key = props.key;
delete props.key;
}
}
function normalizeElement(type, vNode) {
if (type === 'svg') {
vNode.flags = 128 /* SvgElement */;
}
else if (type === 'input') {
vNode.flags = 512 /* InputElement */;
}
else if (type === 'select') {
vNode.flags = 2048 /* SelectElement */;
}
else if (type === 'textarea') {
vNode.flags = 1024 /* TextareaElement */;
}
else if (type === 'media') {
vNode.flags = 256 /* MediaElement */;
}
else {
vNode.flags = 2 /* HtmlElement */;
}
}
function normalize(vNode) {
var props = vNode.props;
var type = vNode.type;
var children = vNode.children;
// convert a wrongly created type back to element
// Primitive node doesn't have defaultProps, only Component
if (vNode.flags & 28 /* Component */) {
// set default props
var defaultProps = type.defaultProps;
if (!isNullOrUndef(defaultProps)) {
if (!props) {
props = vNode.props = defaultProps; // Create new object if only defaultProps given
}
else {
for (var prop in defaultProps) {
if (isUndefined(props[prop])) {
props[prop] = defaultProps[prop];
}
}
}
}
if (isString(type)) {
normalizeElement(type, vNode);
if (props && props.children) {
vNode.children = props.children;
children = props.children;
}
}
}
if (props) {
normalizeProps(vNode, props, children);
}
if (!isInvalid(children)) {
vNode.children = normalizeChildren(children);
}
if (props && !isInvalid(props.children)) {
props.children = normalizeChildren(props.children);
}
{
// This code will be stripped out from production CODE
// It will help users to track errors in their applications.
var verifyKeys = function (vNodes) {
var keyValues = vNodes.map(function (vnode) { return vnode.key; });
keyValues.some(function (item, idx) {
var hasDuplicate = keyValues.indexOf(item) !== idx;
if (hasDuplicate) {
warning('Inferno normalisation(...): Encountered two children with same key, all keys must be unique within its siblings. Duplicated key is:' + item);
}
return hasDuplicate;
});
};
if (vNode.children && Array.isArray(vNode.children)) {
verifyKeys(vNode.children);
}
}
}
var options = {
recyclingEnabled: false,
findDOMNodeEnabled: false,
roots: null,
createVNode: null,
beforeRender: null,
afterRender: null,
afterMount: null,
afterUpdate: null,
beforeUnmount: null
};
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var svgNS = 'http://www.w3.org/2000/svg';
var strictProps = Object.create(null);
strictProps.volume = true;
strictProps.defaultChecked = true;
var booleanProps = Object.create(null);
booleanProps.muted = 1;
booleanProps.scoped = 1;
booleanProps.loop = 1;
booleanProps.open = 1;
booleanProps.checked = 1;
booleanProps.default = 1;
booleanProps.capture = 1;
booleanProps.disabled = 1;
booleanProps.readOnly = 1;
booleanProps.required = 1;
booleanProps.autoplay = 1;
booleanProps.controls = 1;
booleanProps.seamless = 1;
booleanProps.reversed = 1;
booleanProps.allowfullscreen = 1;
booleanProps.novalidate = 1;
booleanProps.hidden = 1;
var namespaces = Object.create(null);
namespaces['xlink:href'] = xlinkNS;
namespaces['xlink:arcrole'] = xlinkNS;
namespaces['xlink:actuate'] = xlinkNS;
namespaces['xlink:role'] = xlinkNS;
namespaces['xlink:titlef'] = xlinkNS;
namespaces['xlink:type'] = xlinkNS;
namespaces['xml:base'] = xmlNS;
namespaces['xml:lang'] = xmlNS;
namespaces['xml:space'] = xmlNS;
var isUnitlessNumber = Object.create(null);
isUnitlessNumber.animationIterationCount = 1;
isUnitlessNumber.borderImageOutset = 1;
isUnitlessNumber.borderImageSlice = 1;
isUnitlessNumber.borderImageWidth = 1;
isUnitlessNumber.boxFlex = 1;
isUnitlessNumber.boxFlexGroup = 1;
isUnitlessNumber.boxOrdinalGroup = 1;
isUnitlessNumber.columnCount = 1;
isUnitlessNumber.flex = 1;
isUnitlessNumber.flexGrow = 1;
isUnitlessNumber.flexPositive = 1;
isUnitlessNumber.flexShrink = 1;
isUnitlessNumber.flexNegative = 1;
isUnitlessNumber.flexOrder = 1;
isUnitlessNumber.gridRow = 1;
isUnitlessNumber.gridColumn = 1;
isUnitlessNumber.fontWeight = 1;
isUnitlessNumber.lineClamp = 1;
isUnitlessNumber.lineHeight = 1;
isUnitlessNumber.opacity = 1;
isUnitlessNumber.order = 1;
isUnitlessNumber.orphans = 1;
isUnitlessNumber.tabSize = 1;
isUnitlessNumber.widows = 1;
isUnitlessNumber.zIndex = 1;
isUnitlessNumber.zoom = 1;
isUnitlessNumber.fillOpacity = 1;
isUnitlessNumber.floodOpacity = 1;
isUnitlessNumber.stopOpacity = 1;
isUnitlessNumber.strokeDasharray = 1;
isUnitlessNumber.strokeDashoffset = 1;
isUnitlessNumber.strokeMiterlimit = 1;
isUnitlessNumber.strokeOpacity = 1;
isUnitlessNumber.strokeWidth = 1;
var skipProps = Object.create(null);
skipProps.children = 1;
skipProps.childrenType = 1;
skipProps.defaultValue = 1;
skipProps.ref = 1;
skipProps.key = 1;
skipProps.selected = 1;
skipProps.checked = 1;
skipProps.multiple = 1;
var delegatedProps = Object.create(null);
delegatedProps.onClick = 1;
delegatedProps.onMouseDown = 1;
delegatedProps.onMouseUp = 1;
delegatedProps.onMouseMove = 1;
delegatedProps.onSubmit = 1;
delegatedProps.onDblClick = 1;
delegatedProps.onKeyDown = 1;
delegatedProps.onKeyUp = 1;
delegatedProps.onKeyPress = 1;
var isiOS = isBrowser && !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
var delegatedEvents = new Map();
function handleEvent(name, lastEvent, nextEvent, dom) {
var delegatedRoots = delegatedEvents.get(name);
if (nextEvent) {
if (!delegatedRoots) {
delegatedRoots = { items: new Map(), count: 0, docEvent: null };
delegatedRoots.docEvent = attachEventToDocument(name, delegatedRoots);
delegatedEvents.set(name, delegatedRoots);
}
if (!lastEvent) {
delegatedRoots.count++;
if (isiOS && name === 'onClick') {
trapClickOnNonInteractiveElement(dom);
}
}
delegatedRoots.items.set(dom, nextEvent);
}
else if (delegatedRoots) {
if (delegatedRoots.items.has(dom)) {
delegatedRoots.count--;
delegatedRoots.items.delete(dom);
if (delegatedRoots.count === 0) {
document.removeEventListener(normalizeEventName(name), delegatedRoots.docEvent);
delegatedEvents.delete(name);
}
}
}
}
function dispatchEvent(event, dom, items, count, eventData) {
var eventsToTrigger = items.get(dom);
if (eventsToTrigger) {
count--;
// linkEvent object
eventData.dom = dom;
if (eventsToTrigger.event) {
eventsToTrigger.event(eventsToTrigger.data, event);
}
else {
eventsToTrigger(event);
}
if (eventData.stopPropagation) {
return;
}
}
if (count > 0) {
var parentDom = dom.parentNode;
// Html Nodes can be nested fe: span inside button in that scenario browser does not handle disabled attribute on parent,
// because the event listener is on document.body
if (parentDom && parentDom.disabled !== true || parentDom === document.body) {
dispatchEvent(event, parentDom, items, count, eventData);
}
}
}
function normalizeEventName(name) {
return name.substr(2).toLowerCase();
}
function attachEventToDocument(name, delegatedRoots) {
var docEvent = function (event) {
var eventData = {
stopPropagation: false,
dom: document
};
// we have to do this as some browsers recycle the same Event between calls
// so we need to make the property configurable
Object.defineProperty(event, 'currentTarget', {
configurable: true,
get: function get() {
return eventData.dom;
}
});
event.stopPropagation = function () {
eventData.stopPropagation = true;
};
var count = delegatedRoots.count;
if (count > 0) {
dispatchEvent(event, event.target, delegatedRoots.items, count, eventData);
}
};
document.addEventListener(normalizeEventName(name), docEvent);
return docEvent;
}
function emptyFn() { }
function trapClickOnNonInteractiveElement(dom) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
// Just set it using the onclick property so that we don't have to manage any
// bookkeeping for it. Not sure if we need to clear it when the listener is
// removed.
// TODO: Only do this for the relevant Safaris maybe?
dom.onclick = emptyFn;
}
function isCheckedType(type) {
return type === 'checkbox' || type === 'radio';
}
function isControlled(props) {
var usesChecked = isCheckedType(props.type);
return usesChecked ? !isNullOrUndef(props.checked) : !isNullOrUndef(props.value);
}
function onTextInputChange(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var dom = vNode.dom;
if (events.onInput) {
var event = events.onInput;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
else if (events.oninput) {
events.oninput(e);
}
// the user may have updated the vNode from the above onInput events
// so we need to get it from the context of `this` again
applyValue(this.vNode, dom);
}
function wrappedOnChange(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var event = events.onChange;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
function onCheckboxChange(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var dom = vNode.dom;
if (events.onClick) {
var event = events.onClick;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
else if (events.onclick) {
events.onclick(e);
}
// the user may have updated the vNode from the above onClick events
// so we need to get it from the context of `this` again
applyValue(this.vNode, dom);
}
function handleAssociatedRadioInputs(name) {
var inputs = document.querySelectorAll(("input[type=\"radio\"][name=\"" + name + "\"]"));
[].forEach.call(inputs, function (dom) {
var inputWrapper = wrappers.get(dom);
if (inputWrapper) {
var props = inputWrapper.vNode.props;
if (props) {
dom.checked = inputWrapper.vNode.props.checked;
}
}
});
}
function processInput(vNode, dom) {
var props = vNode.props || EMPTY_OBJ;
applyValue(vNode, dom);
if (isControlled(props)) {
var inputWrapper = wrappers.get(dom);
if (!inputWrapper) {
inputWrapper = {
vNode: vNode
};
if (isCheckedType(props.type)) {
dom.onclick = onCheckboxChange.bind(inputWrapper);
dom.onclick.wrapped = true;
}
else {
dom.oninput = onTextInputChange.bind(inputWrapper);
dom.oninput.wrapped = true;
}
if (props.onChange) {
dom.onchange = wrappedOnChange.bind(inputWrapper);
dom.onchange.wrapped = true;
}
wrappers.set(dom, inputWrapper);
}
inputWrapper.vNode = vNode;
return true;
}
return false;
}
function applyValue(vNode, dom) {
var props = vNode.props || EMPTY_OBJ;
var type = props.type;
var value = props.value;
var checked = props.checked;
var multiple = props.multiple;
var defaultValue = props.defaultValue;
var hasValue = !isNullOrUndef(value);
if (type && type !== dom.type) {
dom.type = type;
}
if (multiple && multiple !== dom.multiple) {
dom.multiple = multiple;
}
if (!isNullOrUndef(defaultValue) && !hasValue) {
dom.defaultValue = defaultValue + '';
}
if (isCheckedType(type)) {
if (hasValue) {
dom.value = value;
}
if (!isNullOrUndef(checked)) {
dom.checked = checked;
}
if (type === 'radio' && props.name) {
handleAssociatedRadioInputs(props.name);
}
}
else {
if (hasValue && dom.value !== value) {
dom.value = value;
}
else if (!isNullOrUndef(checked)) {
dom.checked = checked;
}
}
}
function isControlled$1(props) {
return !isNullOrUndef(props.value);
}
function updateChildOptionGroup(vNode, value) {
var type = vNode.type;
if (type === 'optgroup') {
var children = vNode.children;
if (isArray(children)) {
for (var i = 0, len = children.length; i < len; i++) {
updateChildOption(children[i], value);
}
}
else if (isVNode(children)) {
updateChildOption(children, value);
}
}
else {
updateChildOption(vNode, value);
}
}
function updateChildOption(vNode, value) {
var props = vNode.props || EMPTY_OBJ;
var dom = vNode.dom;
// we do this as multiple may have changed
dom.value = props.value;
if ((isArray(value) && value.indexOf(props.value) !== -1) || props.value === value) {
dom.selected = true;
}
else if (!isNullOrUndef(value) || !isNullOrUndef(props.selected)) {
dom.selected = props.selected || false;
}
}
function onSelectChange(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var dom = vNode.dom;
if (events.onChange) {
var event = events.onChange;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
else if (events.onchange) {
events.onchange(e);
}
// the user may have updated the vNode from the above onChange events
// so we need to get it from the context of `this` again
applyValue$1(this.vNode, dom, false);
}
function processSelect(vNode, dom, mounting) {
var props = vNode.props || EMPTY_OBJ;
applyValue$1(vNode, dom, mounting);
if (isControlled$1(props)) {
var selectWrapper = wrappers.get(dom);
if (!selectWrapper) {
selectWrapper = {
vNode: vNode
};
dom.onchange = onSelectChange.bind(selectWrapper);
dom.onchange.wrapped = true;
wrappers.set(dom, selectWrapper);
}
selectWrapper.vNode = vNode;
return true;
}
return false;
}
function applyValue$1(vNode, dom, mounting) {
var props = vNode.props || EMPTY_OBJ;
if (props.multiple !== dom.multiple) {
dom.multiple = props.multiple;
}
var children = vNode.children;
if (!isInvalid(children)) {
var value = props.value;
if (mounting && isNullOrUndef(value)) {
value = props.defaultValue;
}
if (isArray(children)) {
for (var i = 0, len = children.length; i < len; i++) {
updateChildOptionGroup(children[i], value);
}
}
else if (isVNode(children)) {
updateChildOptionGroup(children, value);
}
}
}
function isControlled$2(props) {
return !isNullOrUndef(props.value);
}
function wrappedOnChange$1(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var event = events.onChange;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
function onTextareaInputChange(e) {
var vNode = this.vNode;
var events = vNode.events || EMPTY_OBJ;
var dom = vNode.dom;
if (events.onInput) {
var event = events.onInput;
if (event.event) {
event.event(event.data, e);
}
else {
event(e);
}
}
else if (events.oninput) {
events.oninput(e);
}
// the user may have updated the vNode from the above onInput events
// so we need to get it from the context of `this` again
applyValue$2(this.vNode, dom, false);
}
function processTextarea(vNode, dom, mounting) {
var props = vNode.props || EMPTY_OBJ;
applyValue$2(vNode, dom, mounting);
var textareaWrapper = wrappers.get(dom);
if (isControlled$2(props)) {
if (!textareaWrapper) {
textareaWrapper = {
vNode: vNode
};
dom.oninput = onTextareaInputChange.bind(textareaWrapper);
dom.oninput.wrapped = true;
if (props.onChange) {
dom.onchange = wrappedOnChange$1.bind(textareaWrapper);
dom.onchange.wrapped = true;
}
wrappers.set(dom, textareaWrapper);
}
textareaWrapper.vNode = vNode;
return true;
}
return false;
}
function applyValue$2(vNode, dom, mounting) {
var props = vNode.props || EMPTY_OBJ;
var value = props.value;
var domValue = dom.value;
if (isNullOrUndef(value)) {
if (mounting) {
var defaultValue = props.defaultValue;
if (!isNullOrUndef(defaultValue)) {
if (defaultValue !== domValue) {
dom.value = defaultValue;
}
}
else if (domValue !== '') {
dom.value = '';
}
}
}
else {
/* There is value so keep it controlled */
if (domValue !== value) {
dom.value = value;
}
}
}
var wrappers = new Map();
function processElement(flags, vNode, dom, mounting) {
if (flags & 512 /* InputElement */) {
return processInput(vNode, dom);
}
if (flags & 2048 /* SelectElement */) {
return processSelect(vNode, dom, mounting);
}
if (flags & 1024 /* TextareaElement */) {
return processTextarea(vNode, dom, mounting);
}
return false;
}
function normalizeChildNodes(parentDom) {
var dom = parentDom.firstChild;
while (dom) {
if (dom.nodeType === 8) {
if (dom.data === '!') {
var placeholder = document.createTextNode('');
parentDom.replaceChild(placeholder, dom);
dom = dom.nextSibling;
}
else {
var lastDom = dom.previousSibling;
parentDom.removeChild(dom);
dom = lastDom || parentDom.firstChild;
}
}
else {
dom = dom.nextSibling;
}
}
}
function hydrateComponent(vNode, dom, lifecycle, context, isSVG, isClass) {
var type = vNode.type;
var ref = vNode.ref;
vNode.dom = dom;
var props = vNode.props || EMPTY_OBJ;
if (isClass) {
var _isSVG = dom.namespaceURI === svgNS;
var instance = createClassComponentInstance(vNode, type, props, context, _isSVG);
var input = instance._lastInput;
instance._vComponent = vNode;
instance._vNode = vNode;
hydrate(input, dom, lifecycle, instance._childContext, _isSVG);
mountClassComponentCallbacks(vNode, ref, instance, lifecycle);
options.findDOMNodeEnabled && componentToDOMNodeMap.set(instance, dom);
vNode.children = instance;
}
else {
var input$1 = createFunctionalComponentInput(vNode, type, props, context);
hydrate(input$1, dom, lifecycle, context, isSVG);
vNode.children = input$1;
vNode.dom = input$1.dom;
mountFunctionalComponentCallbacks(ref, dom, lifecycle);
}
return dom;
}
function hydrateElement(vNode, dom, lifecycle, context, isSVG) {
var children = vNode.children;
var props = vNode.props;
var events = vNode.events;
var flags = vNode.flags;
var ref = vNode.ref;
if (isSVG || (flags & 128 /* SvgElement */)) {
isSVG = true;
}
if (dom.nodeType !== 1 || dom.tagName.toLowerCase() !== vNode.type) {
{
warning('Inferno hydration: Server-side markup doesn\'t match client-side markup or Initial render target is not empty');
}
var newDom = mountElement(vNode, null, lifecycle, context, isSVG);
vNode.dom = newDom;
replaceChild(dom.parentNode, newDom, dom);
return newDom;
}
vNode.dom = dom;
if (children) {
hydrateChildren(children, dom, lifecycle, context, isSVG);
}
var hasControlledValue = false;
if (!(flags & 2 /* HtmlElement */)) {
hasControlledValue = processElement(flags, vNode, dom, false);
}
if (props) {
for (var prop in props) {
patchProp(prop, null, props[prop], dom, isSVG, hasControlledValue);
}
}
if (events) {
for (var name in events) {
patchEvent(name, null, events[name], dom);
}
}
if (ref) {
mountRef(dom, ref, lifecycle);
}
return dom;
}
function hydrateChildren(children, parentDom, lifecycle, context, isSVG) {
normalizeChildNodes(parentDom);
var dom = parentDom.firstChild;
if (isArray(children)) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
if (!isNull(child) && isObject(child)) {
if (dom) {
dom = hydrate(child, dom, lifecycle, context, isSVG);
dom = dom.nextSibling;
}
else {
mount(child, parentDom, lifecycle, context, isSVG);
}
}
}
}
else if (isStringOrNumber(children)) {
if (dom && dom.nodeType === 3) {
if (dom.nodeValue !== children) {
dom.nodeValue = children;
}
}
else if (children) {
parentDom.textContent = children;
}
dom = dom.nextSibling;
}
else if (isObject(children)) {
hydrate(children, dom, lifecycle, context, isSVG);
dom = dom.nextSibling;
}
// clear any other DOM nodes, there should be only a single entry for the root
while (dom) {
var nextSibling = dom.nextSibling;
parentDom.removeChild(dom);
dom = nextSibling;
}
}
function hydrateText(vNode, dom) {
if (dom.nodeType !== 3) {
var newDom = mountText(vNode, null);
vNode.dom = newDom;
replaceChild(dom.parentNode, newDom, dom);
return newDom;
}
var text = vNode.children;
if (dom.nodeValue !== text) {
dom.nodeValue = text;
}
vNode.dom = dom;
return dom;
}
function hydrateVoid(vNode, dom) {
vNode.dom = dom;
return dom;
}
function hydrate(vNode, dom, lifecycle, context, isSVG) {
var flags = vNode.flags;
if (flags & 28 /* Component */) {
return hydrateComponent(vNode, dom, lifecycle, context, isSVG, flags & 4 /* ComponentClass */);
}
else if (flags & 3970 /* Element */) {
return hydrateElement(vNode, dom, lifecycle, context, isSVG);
}
else if (flags & 1 /* Text */) {
return hydrateText(vNode, dom);
}
else if (flags & 4096 /* Void */) {
return hydrateVoid(vNode, dom);
}
else {
{
throwError(("hydrate() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\"."));
}
throwError();
}
}
function hydrateRoot(input, parentDom, lifecycle) {
var dom = parentDom && parentDom.firstChild;
if (dom) {
hydrate(input, dom, lifecycle, EMPTY_OBJ, false);
dom = parentDom.firstChild;
// clear any other DOM nodes, there should be only a single entry for the root
while (dom = dom.nextSibling) {
parentDom.removeChild(dom);
}
return true;
}
return false;
}
var componentPools = new Map();
var elementPools = new Map();
function recycleElement(vNode, lifecycle, context, isSVG) {
var tag = vNode.type;
var pools = elementPools.get(tag);
if (!isUndefined(pools)) {
var key = vNode.key;
var pool = key === null ? pools.nonKeyed : pools.keyed.get(key);
if (!isUndefined(pool)) {
var recycledVNode = pool.pop();
if (!isUndefined(recycledVNode)) {
patchElement(recycledVNode, vNode, null, lifecycle, context, isSVG, true);
return vNode.dom;
}
}
}
return null;
}
function poolElement(vNode) {
var tag = vNode.type;
var key = vNode.key;
var pools = elementPools.get(tag);
if (isUndefined(pools)) {
pools = {
nonKeyed: [],
keyed: new Map()
};
elementPools.set(tag, pools);
}
if (isNull(key)) {
pools.nonKeyed.push(vNode);
}
else {
var pool = pools.keyed.get(key);
if (isUndefined(pool)) {
pool = [];
pools.keyed.set(key, pool);
}
pool.push(vNode);
}
}
function recycleComponent(vNode, lifecycle, context, isSVG) {
var type = vNode.type;
var pools = componentPools.get(type);
if (!isUndefined(pools)) {
var key = vNode.key;
var pool = key === null ? pools.nonKeyed : pools.keyed.get(key);
if (!isUndefined(pool)) {
var recycledVNode = pool.pop();
if (!isUndefined(recycledVNode)) {
var flags = vNode.flags;
var failed = patchComponent(recycledVNode, vNode, null, lifecycle, context, isSVG, flags & 4 /* ComponentClass */, true);
if (!failed) {
return vNode.dom;
}
}
}
}
return null;
}
function poolComponent(vNode) {
var hooks = vNode.ref;
var nonRecycleHooks = hooks && (hooks.onComponentWillMount ||
hooks.onComponentWillUnmount ||
hooks.onComponentDidMount ||
hooks.onComponentWillUpdate ||
hooks.onComponentDidUpdate);
if (nonRecycleHooks) {
return;
}
var type = vNode.type;
var key = vNode.key;
var pools = componentPools.get(type);
if (isUndefined(pools)) {
pools = {
nonKeyed: [],
keyed: new Map()
};
componentPools.set(type, pools);
}
if (isNull(key)) {
pools.nonKeyed.push(vNode);
}
else {
var pool = pools.keyed.get(key);
if (isUndefined(pool)) {
pool = [];
pools.keyed.set(key, pool);
}
pool.push(vNode);
}
}
function unmount(vNode, parentDom, lifecycle, canRecycle, isRecycling) {
var flags = vNode.flags;
if (flags & 28 /* Component */) {
unmountComponent(vNode, parentDom, lifecycle, canRecycle, isRecycling);
}
else if (flags & 3970 /* Element */) {
unmountElement(vNode, parentDom, lifecycle, canRecycle, isRecycling);
}
else if (flags & (1 /* Text */ | 4096 /* Void */)) {
unmountVoidOrText(vNode, parentDom);
}
}
function unmountVoidOrText(vNode, parentDom) {
if (parentDom) {
removeChild(parentDom, vNode.dom);
}
}
function unmountComponent(vNode, parentDom, lifecycle, canRecycle, isRecycling) {
var instance = vNode.children;
var flags = vNode.flags;
var isStatefulComponent$$1 = flags & 4;
var ref = vNode.ref;
var dom = vNode.dom;
if (!isRecycling) {
if (isStatefulComponent$$1) {
if (!instance._unmounted) {
instance._ignoreSetState = true;
options.beforeUnmount && options.beforeUnmount(vNode);
instance.componentWillUnmount && instance.componentWillUnmount();
if (ref && !isRecycling) {
ref(null);
}
instance._unmounted = true;
options.findDOMNodeEnabled && componentToDOMNodeMap.delete(instance);
unmount(instance._lastInput, null, instance._lifecycle, false, isRecycling);
}
}
else {
if (!isNullOrUndef(ref)) {
if (!isNullOrUndef(ref.onComponentWillUnmount)) {
ref.onComponentWillUnmount(dom);
}
}
unmount(instance, null, lifecycle, false, isRecycling);
}
}
if (parentDom) {
var lastInput = instance._lastInput;
if (isNullOrUndef(lastInput)) {
lastInput = instance;
}
removeChild(parentDom, dom);
}
if (options.recyclingEnabled && !isStatefulComponent$$1 && (parentDom || canRecycle)) {
poolComponent(vNode);
}
}
function unmountElement(vNode, parentDom, lifecycle, canRecycle, isRecycling) {
var dom = vNode.dom;
var ref = vNode.ref;
var events = vNode.events;
if (ref && !isRecycling) {
unmountRef(ref);
}
var children = vNode.children;
if (!isNullOrUndef(children)) {
unmountChildren$1(children, lifecycle, isRecycling);
}
if (!isNull(events)) {
for (var name in events) {
// do not add a hasOwnProperty check here, it affects performance
patchEvent(name, events[name], null, dom);
events[name] = null;
}
}
if (parentDom) {
removeChild(parentDom, dom);
}
if (options.recyclingEnabled && (parentDom || canRecycle)) {
poolElement(vNode);
}
}
function unmountChildren$1(children, lifecycle, isRecycling) {
if (isArray(children)) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
if (!isInvalid(child) && isObject(child)) {
unmount(child, null, lifecycle, false, isRecycling);
}
}
}
else if (isObject(children)) {
unmount(children, null, lifecycle, false, isRecycling);
}
}
function unmountRef(ref) {
if (isFunction(ref)) {
ref(null);
}
else {
if (isInvalid(ref)) {
return;
}
{
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
throwError();
}
}
// rather than use a Map, like we did before, we can use an array here
// given there shouldn't be THAT many roots on the page, the difference
// in performance is huge: https://esbench.com/bench/5802a691330ab09900a1a2da
var roots = [];
var componentToDOMNodeMap = new Map();
options.roots = roots;
function findDOMNode(ref) {
if (!options.findDOMNodeEnabled) {
{
throwError('findDOMNode() has been disabled, use Inferno.options.findDOMNodeEnabled = true; enabled findDOMNode(). Warning this can significantly impact performance!');
}
throwError();
}
var dom = ref && ref.nodeType ? ref : null;
return componentToDOMNodeMap.get(ref) || dom;
}
function getRoot(dom) {
for (var i = 0, len = roots.length; i < len; i++) {
var root = roots[i];
if (root.dom === dom) {
return root;
}
}
return null;
}
function setRoot(dom, input, lifecycle) {
var root = {
dom: dom,
input: input,
lifecycle: lifecycle
};
roots.push(root);
return root;
}
function removeRoot(root) {
for (var i = 0, len = roots.length; i < len; i++) {
if (roots[i] === root) {
roots.splice(i, 1);
return;
}
}
}
{
if (isBrowser && document.body === null) {
warning('Inferno warning: you cannot initialize inferno without "document.body". Wait on "DOMContentLoaded" event, add script to bottom of body, or use async/defer attributes on script tag.');
}
}
var documentBody = isBrowser ? document.body : null;
function render(input, parentDom) {
if (documentBody === parentDom) {
{
throwError('you cannot render() to the "document.body". Use an empty element as a container instead.');
}
throwError();
}
if (input === NO_OP) {
return;
}
var root = getRoot(parentDom);
if (isNull(root)) {
var lifecycle = new Lifecycle();
if (!isInvalid(input)) {
if (input.dom) {
input = cloneVNode(input);
}
if (!hydrateRoot(input, parentDom, lifecycle)) {
mount(input, parentDom, lifecycle, EMPTY_OBJ, false);
}
root = setRoot(parentDom, input, lifecycle);
lifecycle.trigger();
}
}
else {
var lifecycle$1 = root.lifecycle;
lifecycle$1.listeners = [];
if (isNullOrUndef(input)) {
unmount(root.input, parentDom, lifecycle$1, false, false);
removeRoot(root);
}
else {
if (input.dom) {
input = cloneVNode(input);
}
patch(root.input, input, parentDom, lifecycle$1, EMPTY_OBJ, false, false);
}
lifecycle$1.trigger();
root.input = input;
}
if (root) {
var rootInput = root.input;
if (rootInput && (rootInput.flags & 28 /* Component */)) {
return rootInput.children;
}
}
}
function createRenderer(parentDom) {
return function renderer(lastInput, nextInput) {
if (!parentDom) {
parentDom = lastInput;
}
render(nextInput, parentDom);
};
}
function patch(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling) {
if (lastVNode !== nextVNode) {
var lastFlags = lastVNode.flags;
var nextFlags = nextVNode.flags;
if (nextFlags & 28 /* Component */) {
if (lastFlags & 28 /* Component */) {
patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, nextFlags & 4 /* ComponentClass */, isRecycling);
}
else {
replaceVNode(parentDom, mountComponent(nextVNode, null, lifecycle, context, isSVG, nextFlags & 4 /* ComponentClass */), lastVNode, lifecycle, isRecycling);
}
}
else if (nextFlags & 3970 /* Element */) {
if (lastFlags & 3970 /* Element */) {
patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
}
else {
replaceVNode(parentDom, mountElement(nextVNode, null, lifecycle, context, isSVG), lastVNode, lifecycle, isRecycling);
}
}
else if (nextFlags & 1 /* Text */) {
if (lastFlags & 1 /* Text */) {
patchText(lastVNode, nextVNode);
}
else {
replaceVNode(parentDom, mountText(nextVNode, null), lastVNode, lifecycle, isRecycling);
}
}
else if (nextFlags & 4096 /* Void */) {
if (lastFlags & 4096 /* Void */) {
patchVoid(lastVNode, nextVNode);
}
else {
replaceVNode(parentDom, mountVoid(nextVNode, null), lastVNode, lifecycle, isRecycling);
}
}
else {
// Error case: mount new one replacing old one
replaceLastChildAndUnmount(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
}
}
}
function unmountChildren(children, dom, lifecycle, isRecycling) {
if (isVNode(children)) {
unmount(children, dom, lifecycle, true, isRecycling);
}
else if (isArray(children)) {
removeAllChildren(dom, children, lifecycle, isRecycling);
}
else {
dom.textContent = '';
}
}
function patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling) {
var nextTag = nextVNode.type;
var lastTag = lastVNode.type;
if (lastTag !== nextTag) {
replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
}
else {
var dom = lastVNode.dom;
var lastProps = lastVNode.props;
var nextProps = nextVNode.props;
var lastChildren = lastVNode.children;
var nextChildren = nextVNode.children;
var lastFlags = lastVNode.flags;
var nextFlags = nextVNode.flags;
var nextRef = nextVNode.ref;
var lastEvents = lastVNode.events;
var nextEvents = nextVNode.events;
nextVNode.dom = dom;
if (isSVG || (nextFlags & 128 /* SvgElement */)) {
isSVG = true;
}
if (lastChildren !== nextChildren) {
patchChildren(lastFlags, nextFlags, lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
}
var hasControlledValue = false;
if (!(nextFlags & 2 /* HtmlElement */)) {
hasControlledValue = processElement(nextFlags, nextVNode, dom, false);
}
// inlined patchProps -- starts --
if (lastProps !== nextProps) {
var lastPropsOrEmpty = lastProps || EMPTY_OBJ;
var nextPropsOrEmpty = nextProps || EMPTY_OBJ;
if (nextPropsOrEmpty !== EMPTY_OBJ) {
for (var prop in nextPropsOrEmpty) {
// do not add a hasOwnProperty check here, it affects performance
var nextValue = nextPropsOrEmpty[prop];
var lastValue = lastPropsOrEmpty[prop];
if (isNullOrUndef(nextValue)) {
removeProp(prop, nextValue, dom);
}
else {
patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue);
}
}
}
if (lastPropsOrEmpty !== EMPTY_OBJ) {
for (var prop$1 in lastPropsOrEmpty) {
// do not add a hasOwnProperty check here, it affects performance
if (isNullOrUndef(nextPropsOrEmpty[prop$1])) {
removeProp(prop$1, lastPropsOrEmpty[prop$1], dom);
}
}
}
}
// inlined patchProps -- ends --
if (lastEvents !== nextEvents) {
patchEvents(lastEvents, nextEvents, dom);
}
if (nextRef) {
if (lastVNode.ref !== nextRef || isRecycling) {
mountRef(dom, nextRef, lifecycle);
}
}
}
}
function patchChildren(lastFlags, nextFlags, lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling) {
var patchArray = false;
var patchKeyed = false;
if (nextFlags & 64 /* HasNonKeyedChildren */) {
patchArray = true;
}
else if ((lastFlags & 32 /* HasKeyedChildren */) && (nextFlags & 32 /* HasKeyedChildren */)) {
patchKeyed = true;
patchArray = true;
}
else if (isInvalid(nextChildren)) {
unmountChildren(lastChildren, dom, lifecycle, isRecycling);
}
else if (isInvalid(lastChildren)) {
if (isStringOrNumber(nextChildren)) {
setTextContent(dom, nextChildren);
}
else {
if (isArray(nextChildren)) {
mountArrayChildren(nextChildren, dom, lifecycle, context, isSVG);
}
else {
mount(nextChildren, dom, lifecycle, context, isSVG);
}
}
}
else if (isStringOrNumber(nextChildren)) {
if (isStringOrNumber(lastChildren)) {
updateTextContent(dom, nextChildren);
}
else {
unmountChildren(lastChildren, dom, lifecycle, isRecycling);
setTextContent(dom, nextChildren);
}
}
else if (isArray(nextChildren)) {
if (isArray(lastChildren)) {
patchArray = true;
if (isKeyed(lastChildren, nextChildren)) {
patchKeyed = true;
}
}
else {
unmountChildren(lastChildren, dom, lifecycle, isRecycling);
mountArrayChildren(nextChildren, dom, lifecycle, context, isSVG);
}
}
else if (isArray(lastChildren)) {
removeAllChildren(dom, lastChildren, lifecycle, isRecycling);
mount(nextChildren, dom, lifecycle, context, isSVG);
}
else if (isVNode(nextChildren)) {
if (isVNode(lastChildren)) {
patch(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
}
else {
unmountChildren(lastChildren, dom, lifecycle, isRecycling);
mount(nextChildren, dom, lifecycle, context, isSVG);
}
}
if (patchArray) {
if (patchKeyed) {
patchKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
}
else {
patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling);
}
}
}
function patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isClass, isRecycling) {
var lastType = lastVNode.type;
var nextType = nextVNode.type;
var lastKey = lastVNode.key;
var nextKey = nextVNode.key;
if (lastType !== nextType || lastKey !== nextKey) {
replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isRecycling);
return false;
}
else {
var nextProps = nextVNode.props || EMPTY_OBJ;
if (isClass) {
var instance = lastVNode.children;
if (instance._unmounted) {
if (isNull(parentDom)) {
return true;
}
replaceChild(parentDom, mountComponent(nextVNode, null, lifecycle, context, isSVG, nextVNode.flags & 4 /* ComponentClass */), lastVNode.dom);
}
else {
var lastState = instance.state;
var nextState = instance.state;
var lastProps = instance.props;
var childContext = instance.getChildContext();
nextVNode.children = instance;
instance._isSVG = isSVG;
instance._syncSetState = false;
if (isNullOrUndef(childContext)) {
childContext = context;
}
else {
childContext = assign({}, context, childContext);
}
var lastInput = instance._lastInput;
var nextInput = instance._updateComponent(lastState, nextState, lastProps, nextProps, context, false, false);
var didUpdate = true;
instance._childContext = childContext;
if (isInvalid(nextInput)) {
nextInput = createVoidVNode();
}
else if (nextInput === NO_OP) {
nextInput = lastInput;
didUpdate = false;
}
else if (isStringOrNumber(nextInput)) {
nextInput = createTextVNode(nextInput, null);
}
else if (isArray(nextInput)) {
{
throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
}
throwError();
}
else if (isObject(nextInput) && nextInput.dom) {
nextInput = cloneVNode(nextInput);
}
if (nextInput.flags & 28 /* Component */) {
nextInput.parentVNode = nextVNode;
}
else if (lastInput.flags & 28 /* Component */) {
lastInput.parentVNode = nextVNode;
}
instance._lastInput = nextInput;
instance._vNode = nextVNode;
if (didUpdate) {
patch(lastInput, nextInput, parentDom, lifecycle, childContext, isSVG, isRecycling);
instance.componentDidUpdate(lastProps, lastState);
options.afterUpdate && options.afterUpdate(nextVNode);
options.findDOMNodeEnabled && componentToDOMNodeMap.set(instance, nextInput.dom);
}
instance._syncSetState = true;
nextVNode.dom = nextInput.dom;
}
}
else {
var shouldUpdate = true;
var lastProps$1 = lastVNode.props;
var nextHooks = nextVNode.ref;
var nextHooksDefined = !isNullOrUndef(nextHooks);
var lastInput$1 = lastVNode.children;
var nextInput$1 = lastInput$1;
nextVNode.dom = lastVNode.dom;
nextVNode.children = lastInput$1;
if (lastKey !== nextKey) {
shouldUpdate = true;
}
else {
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentShouldUpdate)) {
shouldUpdate = nextHooks.onComponentShouldUpdate(lastProps$1, nextProps);
}
}
if (shouldUpdate !== false) {
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentWillUpdate)) {
nextHooks.onComponentWillUpdate(lastProps$1, nextProps);
}
nextInput$1 = nextType(nextProps, context);
if (isInvalid(nextInput$1)) {
nextInput$1 = createVoidVNode();
}
else if (isStringOrNumber(nextInput$1) && nextInput$1 !== NO_OP) {
nextInput$1 = createTextVNode(nextInput$1, null);
}
else if (isArray(nextInput$1)) {
{
throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
}
throwError();
}
else if (isObject(nextInput$1) && nextInput$1.dom) {
nextInput$1 = cloneVNode(nextInput$1);
}
if (nextInput$1 !== NO_OP) {
patch(lastInput$1, nextInput$1, parentDom, lifecycle, context, isSVG, isRecycling);
nextVNode.children = nextInput$1;
if (nextHooksDefined && !isNullOrUndef(nextHooks.onComponentDidUpdate)) {
nextHooks.onComponentDidUpdate(lastProps$1, nextProps);
}
nextVNode.dom = nextInput$1.dom;
}
}
if (nextInput$1.flags & 28 /* Component */) {
nextInput$1.parentVNode = nextVNode;
}
else if (lastInput$1.flags & 28 /* Component */) {
lastInput$1.parentVNode = nextVNode;
}
}
}
return false;
}
function patchText(lastVNode, nextVNode) {
var nextText = nextVNode.children;
var dom = lastVNode.dom;
nextVNode.dom = dom;
if (lastVNode.children !== nextText) {
dom.nodeValue = nextText;
}
}
function patchVoid(lastVNode, nextVNode) {
nextVNode.dom = lastVNode.dom;
}
function patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, isRecycling) {
var lastChildrenLength = lastChildren.length;
var nextChildrenLength = nextChildren.length;
var commonLength = lastChildrenLength > nextChildrenLength ? nextChildrenLength : lastChildrenLength;
var i = 0;
for (; i < commonLength; i++) {
var nextChild = nextChildren[i];
if (nextChild.dom) {
nextChild = nextChildren[i] = cloneVNode(nextChild);
}
patch(lastChildren[i], nextChild, dom, lifecycle, context, isSVG, isRecycling);
}
if (lastChildrenLength < nextChildrenLength) {
for (i = commonLength; i < nextChildrenLength; i++) {
var nextChild$1 = nextChildren[i];
if (nextChild$1.dom) {
nextChild$1 = nextChildren[i] = cloneVNode(nextChild$1);
}
appendChild(dom, mount(nextChild$1, null, lifecycle, context, isSVG));
}
}
else if (nextChildrenLength === 0) {
removeAllChildren(dom, lastChildren, lifecycle, isRecycling);
}
else if (lastChildrenLength > nextChildrenLength) {
for (i = commonLength; i < lastChildrenLength; i++) {
unmount(lastChildren[i], dom, lifecycle, false, isRecycling);
}
}
}
function patchKeyedChildren(a, b, dom, lifecycle, context, isSVG, isRecycling) {
var aLength = a.length;
var bLength = b.length;
var aEnd = aLength - 1;
var bEnd = bLength - 1;
var aStart = 0;
var bStart = 0;
var i;
var j;
var aNode;
var bNode;
var nextNode;
var nextPos;
var node;
if (aLength === 0) {
if (bLength !== 0) {
mountArrayChildren(b, dom, lifecycle, context, isSVG);
}
return;
}
else if (bLength === 0) {
removeAllChildren(dom, a, lifecycle, isRecycling);
return;
}
var aStartNode = a[aStart];
var bStartNode = b[bStart];
var aEndNode = a[aEnd];
var bEndNode = b[bEnd];
if (bStartNode.dom) {
b[bStart] = bStartNode = cloneVNode(bStartNode);
}
if (bEndNode.dom) {
b[bEnd] = bEndNode = cloneVNode(bEndNode);
}
// Step 1
/* eslint no-constant-condition: 0 */
outer: while (true) {
// Sync nodes with the same key at the beginning.
while (aStartNode.key === bStartNode.key) {
patch(aStartNode, bStartNode, dom, lifecycle, context, isSVG, isRecycling);
aStart++;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aStartNode = a[aStart];
bStartNode = b[bStart];
if (bStartNode.dom) {
b[bStart] = bStartNode = cloneVNode(bStartNode);
}
}
// Sync nodes with the same key at the end.
while (aEndNode.key === bEndNode.key) {
patch(aEndNode, bEndNode, dom, lifecycle, context, isSVG, isRecycling);
aEnd--;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aEndNode = a[aEnd];
bEndNode = b[bEnd];
if (bEndNode.dom) {
b[bEnd] = bEndNode = cloneVNode(bEndNode);
}
}
// Move and sync nodes from right to left.
if (aEndNode.key === bStartNode.key) {
patch(aEndNode, bStartNode, dom, lifecycle, context, isSVG, isRecycling);
insertOrAppend(dom, bStartNode.dom, aStartNode.dom);
aEnd--;
bStart++;
aEndNode = a[aEnd];
bStartNode = b[bStart];
if (bStartNode.dom) {
b[bStart] = bStartNode = cloneVNode(bStartNode);
}
continue;
}
// Move and sync nodes from left to right.
if (aStartNode.key === bEndNode.key) {
patch(aStartNode, bEndNode, dom, lifecycle, context, isSVG, isRecycling);
nextPos = bEnd + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : null;
insertOrAppend(dom, bEndNode.dom, nextNode);
aStart++;
bEnd--;
aStartNode = a[aStart];
bEndNode = b[bEnd];
if (bEndNode.dom) {
b[bEnd] = bEndNode = cloneVNode(bEndNode);
}
continue;
}
break;
}
if (aStart > aEnd) {
if (bStart <= bEnd) {
nextPos = bEnd + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : null;
while (bStart <= bEnd) {
node = b[bStart];
if (node.dom) {
b[bStart] = node = cloneVNode(node);
}
bStart++;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode);
}
}
}
else if (bStart > bEnd) {
while (aStart <= aEnd) {
unmount(a[aStart++], dom, lifecycle, false, isRecycling);
}
}
else {
aLength = aEnd - aStart + 1;
bLength = bEnd - bStart + 1;
var sources = new Array(bLength);
// Mark all nodes as inserted.
for (i = 0; i < bLength; i++) {
sources[i] = -1;
}
var moved = false;
var pos = 0;
var patched = 0;
// When sizes are small, just loop them through
if ((bLength <= 4) || (aLength * bLength <= 16)) {
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLength) {
for (j = bStart; j <= bEnd; j++) {
bNode = b[j];
if (aNode.key === bNode.key) {
sources[j - bStart] = i;
if (pos > j) {
moved = true;
}
else {
pos = j;
}
if (bNode.dom) {
b[j] = bNode = cloneVNode(bNode);
}
patch(aNode, bNode, dom, lifecycle, context, isSVG, isRecycling);
patched++;
a[i] = null;
break;
}
}
}
}
}
else {
var keyIndex = new Map();
// Map keys by their index in array
for (i = bStart; i <= bEnd; i++) {
keyIndex.set(b[i].key, i);
}
// Try to patch same keys
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLength) {
j = keyIndex.get(aNode.key);
if (!isUndefined(j)) {
bNode = b[j];
sources[j - bStart] = i;
if (pos > j) {
moved = true;
}
else {
pos = j;
}
if (bNode.dom) {
b[j] = bNode = cloneVNode(bNode);
}
patch(aNode, bNode, dom, lifecycle, context, isSVG, isRecycling);
patched++;
a[i] = null;
}
}
}
}
// fast-path: if nothing patched remove all old and add all new
if (aLength === a.length && patched === 0) {
removeAllChildren(dom, a, lifecycle, isRecycling);
while (bStart < bLength) {
node = b[bStart];
if (node.dom) {
b[bStart] = node = cloneVNode(node);
}
bStart++;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), null);
}
}
else {
i = aLength - patched;
while (i > 0) {
aNode = a[aStart++];
if (!isNull(aNode)) {
unmount(aNode, dom, lifecycle, true, isRecycling);
i--;
}
}
if (moved) {
var seq = lis_algorithm(sources);
j = seq.length - 1;
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
if (node.dom) {
b[pos] = node = cloneVNode(node);
}
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : null;
insertOrAppend(dom, mount(node, dom, lifecycle, context, isSVG), nextNode);
}
else {
if (j < 0 || i !== seq[j]) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : null;
insertOrAppend(dom, node.dom, nextNode);
}
else {
j--;
}
}
}
}
else if (patched !== bLength) {
// when patched count doesn't match b length we need to insert those new ones
// loop backwards so we can use insertBefore
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
if (node.dom) {
b[pos] = node = cloneVNode(node);
}
nextPos = pos + 1;
nextNode = nextPos < b.length ? b[nextPos].dom : null;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode);
}
}
}
}
}
}
// // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
function lis_algorithm(arr) {
var p = arr.slice(0);
var result = [0];
var i;
var j;
var u;
var v;
var c;
var len = arr.length;
for (i = 0; i < len; i++) {
var arrI = arr[i];
if (arrI === -1) {
continue;
}
j = result[result.length - 1];
if (arr[j] < arrI) {
p[i] = j;
result.push(i);
continue;
}
u = 0;
v = result.length - 1;
while (u < v) {
c = ((u + v) / 2) | 0;
if (arr[result[c]] < arrI) {
u = c + 1;
}
else {
v = c;
}
}
if (arrI < arr[result[u]]) {
if (u > 0) {
p[i] = result[u - 1];
}
result[u] = i;
}
}
u = result.length;
v = result[u - 1];
while (u-- > 0) {
result[u] = v;
v = p[v];
}
return result;
}
function patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue) {
if (prop in skipProps || (hasControlledValue && prop === 'value')) {
return;
}
else if (prop in booleanProps) {
dom[prop] = !!nextValue;
}
else if (prop in strictProps) {
var value = isNullOrUndef(nextValue) ? '' : nextValue;
if (dom[prop] !== value) {
dom[prop] = value;
}
}
else if (lastValue !== nextValue) {
if (isAttrAnEvent(prop)) {
patchEvent(prop, lastValue, nextValue, dom);
}
else if (isNullOrUndef(nextValue)) {
dom.removeAttribute(prop);
}
else if (prop === 'className') {
if (isSVG) {
dom.setAttribute('class', nextValue);
}
else {
dom.className = nextValue;
}
}
else if (prop === 'style') {
patchStyle(lastValue, nextValue, dom);
}
else if (prop === 'dangerouslySetInnerHTML') {
var lastHtml = lastValue && lastValue.__html;
var nextHtml = nextValue && nextValue.__html;
if (lastHtml !== nextHtml) {
if (!isNullOrUndef(nextHtml)) {
dom.innerHTML = nextHtml;
}
}
}
else {
var ns = isSVG ? namespaces[prop] : false;
if (ns) {
dom.setAttributeNS(ns, prop, nextValue);
}
else {
dom.setAttribute(prop, nextValue);
}
}
}
}
function patchEvents(lastEvents, nextEvents, dom) {
lastEvents = lastEvents || EMPTY_OBJ;
nextEvents = nextEvents || EMPTY_OBJ;
if (nextEvents !== EMPTY_OBJ) {
for (var name in nextEvents) {
// do not add a hasOwnProperty check here, it affects performance
patchEvent(name, lastEvents[name], nextEvents[name], dom);
}
}
if (lastEvents !== EMPTY_OBJ) {
for (var name$1 in lastEvents) {
// do not add a hasOwnProperty check here, it affects performance
if (isNullOrUndef(nextEvents[name$1])) {
patchEvent(name$1, lastEvents[name$1], null, dom);
}
}
}
}
function patchEvent(name, lastValue, nextValue, dom) {
if (lastValue !== nextValue) {
var nameLowerCase = name.toLowerCase();
var domEvent = dom[nameLowerCase];
// if the function is wrapped, that means it's been controlled by a wrapper
if (domEvent && domEvent.wrapped) {
return;
}
if (delegatedProps[name]) {
handleEvent(name, lastValue, nextValue, dom);
}
else {
if (lastValue !== nextValue) {
if (!isFunction(nextValue) && !isNullOrUndef(nextValue)) {
var linkEvent = nextValue.event;
if (linkEvent && isFunction(linkEvent)) {
if (!dom._data) {
dom[nameLowerCase] = function (e) {
linkEvent(e.currentTarget._data, e);
};
}
dom._data = nextValue.data;
}
else {
{
throwError(("an event on a VNode \"" + name + "\". was not a function or a valid linkEvent."));
}
throwError();
}
}
else {
dom[nameLowerCase] = nextValue;
}
}
}
}
}
// We are assuming here that we come from patchProp routine
// -nextAttrValue cannot be null or undefined
function patchStyle(lastAttrValue, nextAttrValue, dom) {
var domStyle = dom.style;
if (isString(nextAttrValue)) {
domStyle.cssText = nextAttrValue;
return;
}
for (var style in nextAttrValue) {
// do not add a hasOwnProperty check here, it affects performance
var value = nextAttrValue[style];
if (isNumber(value) && !(style in isUnitlessNumber)) {
domStyle[style] = value + 'px';
}
else {
domStyle[style] = value;
}
}
if (!isNullOrUndef(lastAttrValue)) {
for (var style$1 in lastAttrValue) {
if (isNullOrUndef(nextAttrValue[style$1])) {
domStyle[style$1] = '';
}
}
}
}
function removeProp(prop, lastValue, dom) {
if (prop === 'className') {
dom.removeAttribute('class');
}
else if (prop === 'value') {
dom.value = '';
}
else if (prop === 'style') {
dom.removeAttribute('style');
}
else if (isAttrAnEvent(prop)) {
handleEvent(name, lastValue, null, dom);
}
else {
dom.removeAttribute(prop);
}
}
function mount(vNode, parentDom, lifecycle, context, isSVG) {
var flags = vNode.flags;
if (flags & 3970 /* Element */) {
return mountElement(vNode, parentDom, lifecycle, context, isSVG);
}
else if (flags & 28 /* Component */) {
return mountComponent(vNode, parentDom, lifecycle, context, isSVG, flags & 4 /* ComponentClass */);
}
else if (flags & 4096 /* Void */) {
return mountVoid(vNode, parentDom);
}
else if (flags & 1 /* Text */) {
return mountText(vNode, parentDom);
}
else {
{
if (typeof vNode === 'object') {
throwError(("mount() received an object that's not a valid VNode, you should stringify it first. Object: \"" + (JSON.stringify(vNode)) + "\"."));
}
else {
throwError(("mount() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\"."));
}
}
throwError();
}
}
function mountText(vNode, parentDom) {
var dom = document.createTextNode(vNode.children);
vNode.dom = dom;
if (parentDom) {
appendChild(parentDom, dom);
}
return dom;
}
function mountVoid(vNode, parentDom) {
var dom = document.createTextNode('');
vNode.dom = dom;
if (parentDom) {
appendChild(parentDom, dom);
}
return dom;
}
function mountElement(vNode, parentDom, lifecycle, context, isSVG) {
if (options.recyclingEnabled) {
var dom$1 = recycleElement(vNode, lifecycle, context, isSVG);
if (!isNull(dom$1)) {
if (!isNull(parentDom)) {
appendChild(parentDom, dom$1);
}
return dom$1;
}
}
var flags = vNode.flags;
if (isSVG || (flags & 128 /* SvgElement */)) {
isSVG = true;
}
var dom = documentCreateElement(vNode.type, isSVG);
var children = vNode.children;
var props = vNode.props;
var events = vNode.events;
var ref = vNode.ref;
vNode.dom = dom;
if (!isInvalid(children)) {
if (isStringOrNumber(children)) {
setTextContent(dom, children);
}
else if (isArray(children)) {
mountArrayChildren(children, dom, lifecycle, context, isSVG);
}
else if (isVNode(children)) {
mount(children, dom, lifecycle, context, isSVG);
}
}
var hasControlledValue = false;
if (!(flags & 2 /* HtmlElement */)) {
hasControlledValue = processElement(flags, vNode, dom, true);
}
if (!isNull(props)) {
for (var prop in props) {
// do not add a hasOwnProperty check here, it affects performance
patchProp(prop, null, props[prop], dom, isSVG, hasControlledValue);
}
}
if (!isNull(events)) {
for (var name in events) {
// do not add a hasOwnProperty check here, it affects performance
patchEvent(name, null, events[name], dom);
}
}
if (!isNull(ref)) {
mountRef(dom, ref, lifecycle);
}
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
return dom;
}
function mountArrayChildren(children, dom, lifecycle, context, isSVG) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
// Verify can string/number be here. might cause de-opt. - Normalization takes care of it.
if (!isInvalid(child)) {
if (child.dom) {
children[i] = child = cloneVNode(child);
}
mount(children[i], dom, lifecycle, context, isSVG);
}
}
}
function mountComponent(vNode, parentDom, lifecycle, context, isSVG, isClass) {
if (options.recyclingEnabled) {
var dom$1 = recycleComponent(vNode, lifecycle, context, isSVG);
if (!isNull(dom$1)) {
if (!isNull(parentDom)) {
appendChild(parentDom, dom$1);
}
return dom$1;
}
}
var type = vNode.type;
var props = vNode.props || EMPTY_OBJ;
var ref = vNode.ref;
var dom;
if (isClass) {
var instance = createClassComponentInstance(vNode, type, props, context, isSVG);
var input = instance._lastInput;
instance._vNode = vNode;
vNode.dom = dom = mount(input, null, lifecycle, instance._childContext, isSVG);
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
mountClassComponentCallbacks(vNode, ref, instance, lifecycle);
options.findDOMNodeEnabled && componentToDOMNodeMap.set(instance, dom);
vNode.children = instance;
}
else {
var input$1 = createFunctionalComponentInput(vNode, type, props, context);
vNode.dom = dom = mount(input$1, null, lifecycle, context, isSVG);
vNode.children = input$1;
mountFunctionalComponentCallbacks(ref, dom, lifecycle);
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
}
return dom;
}
function mountClassComponentCallbacks(vNode, ref, instance, lifecycle) {
if (ref) {
if (isFunction(ref)) {
ref(instance);
}
else {
{
if (isStringOrNumber(ref)) {
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
else if (isObject(ref) && (vNode.flags & 4 /* ComponentClass */)) {
throwError('functional component lifecycle events are not supported on ES2015 class components.');
}
else {
throwError(("a bad value for \"ref\" was used on component: \"" + (JSON.stringify(ref)) + "\""));
}
}
throwError();
}
}
var cDM = instance.componentDidMount;
var afterMount = options.afterMount;
if (!isUndefined(cDM) || !isNull(afterMount)) {
lifecycle.addListener(function () {
afterMount && afterMount(vNode);
cDM && instance.componentDidMount();
instance._syncSetState = true;
});
}
else {
instance._syncSetState = true;
}
}
function mountFunctionalComponentCallbacks(ref, dom, lifecycle) {
if (ref) {
if (!isNullOrUndef(ref.onComponentWillMount)) {
ref.onComponentWillMount();
}
if (!isNullOrUndef(ref.onComponentDidMount)) {
lifecycle.addListener(function () { return ref.onComponentDidMount(dom); });
}
}
}
function mountRef(dom, value, lifecycle) {
if (isFunction(value)) {
lifecycle.addListener(function () { return value(dom); });
}
else {
if (isInvalid(value)) {
return;
}
{
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
throwError();
}
}
// We need EMPTY_OBJ defined in one place.
// Its used for comparison so we cant inline it into shared
var EMPTY_OBJ = {};
{
Object.freeze(EMPTY_OBJ);
}
function createClassComponentInstance(vNode, Component, props, context, isSVG) {
if (isUndefined(context)) {
context = EMPTY_OBJ; // Context should not be mutable
}
var instance = new Component(props, context);
instance.context = context;
if (instance.props === EMPTY_OBJ) {
instance.props = props;
}
instance._patch = patch;
if (options.findDOMNodeEnabled) {
instance._componentToDOMNodeMap = componentToDOMNodeMap;
}
instance._unmounted = false;
instance._pendingSetState = true;
instance._isSVG = isSVG;
if (isFunction(instance.componentWillMount)) {
instance.componentWillMount();
}
var childContext = instance.getChildContext();
if (isNullOrUndef(childContext)) {
instance._childContext = context;
}
else {
instance._childContext = assign({}, context, childContext);
}
options.beforeRender && options.beforeRender(instance);
var input = instance.render(props, instance.state, context);
options.afterRender && options.afterRender(instance);
if (isArray(input)) {
{
throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
}
throwError();
}
else if (isInvalid(input)) {
input = createVoidVNode();
}
else if (isStringOrNumber(input)) {
input = createTextVNode(input, null);
}
else {
if (input.dom) {
input = cloneVNode(input);
}
if (input.flags & 28 /* Component */) {
// if we have an input that is also a component, we run into a tricky situation
// where the root vNode needs to always have the correct DOM entry
// so we break monomorphism on our input and supply it our vNode as parentVNode
// we can optimise this in the future, but this gets us out of a lot of issues
input.parentVNode = vNode;
}
}
instance._pendingSetState = false;
instance._lastInput = input;
return instance;
}
function replaceLastChildAndUnmount(lastInput, nextInput, parentDom, lifecycle, context, isSVG, isRecycling) {
replaceVNode(parentDom, mount(nextInput, null, lifecycle, context, isSVG), lastInput, lifecycle, isRecycling);
}
function replaceVNode(parentDom, dom, vNode, lifecycle, isRecycling) {
unmount(vNode, null, lifecycle, false, isRecycling);
// we cannot cache nodeType here as vNode might be re-assigned below
if (vNode.flags & 28 /* Component */) {
// if we are accessing a stateful or stateless component, we want to access their last rendered input
// accessing their DOM node is not useful to us here
vNode = vNode.children._lastInput || vNode.children;
}
replaceChild(parentDom, dom, vNode.dom);
}
function createFunctionalComponentInput(vNode, component, props, context) {
var input = component(props, context);
if (isArray(input)) {
{
throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
}
throwError();
}
else if (isInvalid(input)) {
input = createVoidVNode();
}
else if (isStringOrNumber(input)) {
input = createTextVNode(input, null);
}
else {
if (input.dom) {
input = cloneVNode(input);
}
if (input.flags & 28 /* Component */) {
// if we have an input that is also a component, we run into a tricky situation
// where the root vNode needs to always have the correct DOM entry
// so we break monomorphism on our input and supply it our vNode as parentVNode
// we can optimise this in the future, but this gets us out of a lot of issues
input.parentVNode = vNode;
}
}
return input;
}
function setTextContent(dom, text) {
if (text !== '') {
dom.textContent = text;
}
else {
dom.appendChild(document.createTextNode(''));
}
}
function updateTextContent(dom, text) {
dom.firstChild.nodeValue = text;
}
function appendChild(parentDom, dom) {
parentDom.appendChild(dom);
}
function insertOrAppend(parentDom, newNode, nextNode) {
if (isNullOrUndef(nextNode)) {
appendChild(parentDom, newNode);
}
else {
parentDom.insertBefore(newNode, nextNode);
}
}
function documentCreateElement(tag, isSVG) {
if (isSVG === true) {
return document.createElementNS(svgNS, tag);
}
else {
return document.createElement(tag);
}
}
function replaceWithNewNode(lastNode, nextNode, parentDom, lifecycle, context, isSVG, isRecycling) {
unmount(lastNode, null, lifecycle, false, isRecycling);
var dom = mount(nextNode, null, lifecycle, context, isSVG);
nextNode.dom = dom;
replaceChild(parentDom, dom, lastNode.dom);
}
function replaceChild(parentDom, nextDom, lastDom) {
if (!parentDom) {
parentDom = lastDom.parentNode;
}
parentDom.replaceChild(nextDom, lastDom);
}
function removeChild(parentDom, dom) {
parentDom.removeChild(dom);
}
function removeAllChildren(dom, children, lifecycle, isRecycling) {
dom.textContent = '';
if (!options.recyclingEnabled || (options.recyclingEnabled && !isRecycling)) {
removeChildren(null, children, lifecycle, isRecycling);
}
}
function removeChildren(dom, children, lifecycle, isRecycling) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
if (!isInvalid(child)) {
unmount(child, dom, lifecycle, true, isRecycling);
}
}
}
function isKeyed(lastChildren, nextChildren) {
return nextChildren.length && !isNullOrUndef(nextChildren[0]) && !isNullOrUndef(nextChildren[0].key)
&& lastChildren.length && !isNullOrUndef(lastChildren[0]) && !isNullOrUndef(lastChildren[0].key);
}
function createVNode(flags, type, props, children, events, key, ref, noNormalise) {
if (flags & 16 /* ComponentUnknown */) {
flags = isStatefulComponent(type) ? 4 /* ComponentClass */ : 8 /* ComponentFunction */;
}
var vNode = {
children: isUndefined(children) ? null : children,
dom: null,
events: events || null,
flags: flags,
key: isUndefined(key) ? null : key,
props: props || null,
ref: ref || null,
type: type
};
if (!noNormalise) {
normalize(vNode);
}
if (options.createVNode) {
options.createVNode(vNode);
}
return vNode;
}
function cloneVNode(vNodeToClone, props) {
var arguments$1 = arguments;
var restParamLength = arguments.length - 2; // children
var children;
// Manually handle restParam for children, because babel always creates array
// Not creating array allows us to fastPath out of recursion
if (restParamLength > 0) {
if (!props) {
props = {};
}
if (restParamLength === 1) {
children = arguments[2];
}
else {
children = [];
while (restParamLength-- > 0) {
children[restParamLength] = arguments$1[restParamLength + 2];
}
}
if (isUndefined(props.children)) {
props.children = children;
}
else {
if (isArray(children)) {
if (isArray(props.children)) {
props.children = props.children.concat(children);
}
else {
props.children = [props.children].concat(children);
}
}
else {
if (isArray(props.children)) {
props.children.push(children);
}
else {
props.children = [props.children];
props.children.push(children);
}
}
}
}
var newVNode;
if (isArray(vNodeToClone)) {
var tmpArray = [];
for (var i = 0, len = vNodeToClone.length; i < len; i++) {
tmpArray.push(cloneVNode(vNodeToClone[i]));
}
newVNode = tmpArray;
}
else {
var flags = vNodeToClone.flags;
var events = vNodeToClone.events || (props && props.events) || null;
var key = !isNullOrUndef(vNodeToClone.key) ? vNodeToClone.key : (props ? props.key : null);
var ref = vNodeToClone.ref || (props ? props.ref : null);
if (flags & 28 /* Component */) {
newVNode = createVNode(flags, vNodeToClone.type, (!vNodeToClone.props && !props) ? EMPTY_OBJ : assign({}, vNodeToClone.props, props), null, events, key, ref, true);
var newProps = newVNode.props;
if (newProps) {
var newChildren = newProps.children;
// we need to also clone component children that are in props
// as the children may also have been hoisted
if (newChildren) {
if (isArray(newChildren)) {
var len$1 = newChildren.length;
if (len$1 > 0) {
var tmpArray$1 = [];
for (var i$1 = 0; i$1 < len$1; i$1++) {
var child = newChildren[i$1];
if (!isInvalid(child) && isVNode(child)) {
tmpArray$1.push(cloneVNode(child));
}
}
newProps.children = tmpArray$1;
}
}
else if (isVNode(newChildren)) {
newProps.children = cloneVNode(newChildren);
}
}
}
newVNode.children = null;
}
else if (flags & 3970 /* Element */) {
children = (props && props.children) || vNodeToClone.children;
newVNode = createVNode(flags, vNodeToClone.type, (!vNodeToClone.props && !props) ? EMPTY_OBJ : assign({}, vNodeToClone.props, props), children, events, key, ref, !children);
}
else if (flags & 1 /* Text */) {
newVNode = createTextVNode(vNodeToClone.children, key);
}
}
return newVNode;
}
function createVoidVNode() {
return createVNode(4096 /* Void */);
}
function createTextVNode(text, key) {
return createVNode(1 /* Text */, null, null, text, null, key);
}
function isVNode(o) {
return !!o.flags;
}
function linkEvent(data, event) {
return { data: data, event: event };
}
{
var testFunc = function testFn() { };
if ((testFunc.name || testFunc.toString()).indexOf('testFn') === -1) {
warning(('It looks like you\'re using a minified copy of the development build ' +
'of Inferno. When deploying Inferno apps to production, make sure to use ' +
'the production build which skips development warnings and is faster. ' +
'See http://infernojs.org for more details.'));
}
}
// This will be replaced by rollup
var version = '1.3.0-rc.10';
// we duplicate it so it plays nicely with different module loading systems
var index = {
linkEvent: linkEvent,
// core shapes
createVNode: createVNode,
// cloning
cloneVNode: cloneVNode,
// used to shared common items between Inferno libs
NO_OP: NO_OP,
EMPTY_OBJ: EMPTY_OBJ,
// DOM
render: render,
findDOMNode: findDOMNode,
createRenderer: createRenderer,
options: options,
version: version
};
exports.version = version;
exports['default'] = index;
exports.linkEvent = linkEvent;
exports.createVNode = createVNode;
exports.cloneVNode = cloneVNode;
exports.NO_OP = NO_OP;
exports.EMPTY_OBJ = EMPTY_OBJ;
exports.render = render;
exports.findDOMNode = findDOMNode;
exports.createRenderer = createRenderer;
exports.options = options;
exports.internal_isUnitlessNumber = isUnitlessNumber;
exports.internal_normalize = normalize;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
ej.addCulture( "bn", {
name: "bn",
englishName: "Bangla",
nativeName: "বাংলা",
language: "bn",
numberFormat: {
groupSizes: [3,2],
percent: {
pattern: ["-n%","n %"],
groupSizes: [3,2]
},
currency: {
pattern: ["$ -n","$ n"],
groupSizes: [3,2],
symbol: "₹"
}
},
calendars: {
standard: {
"/": "-",
":": ".",
firstDay: 1,
days: {
names: ["রবিবার","সোমবার","মঙ্গলবার","বুধবার","বৃহস্পতিবার","শুক্রবার","শনিবার"],
namesAbbr: ["রবি.","সোম.","মঙ্গল.","বুধ.","বৃহস্পতি.","শুক্র.","শনি."],
namesShort: ["র","স","ম","বু","বৃ","শু","শ"]
},
months: {
names: ["জানুয়ারী","ফেব্রুয়ারী","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগস্ট","সেপ্টেম্বর","অক্টোবর","নভেম্বর","ডিসেম্বর",""],
namesAbbr: ["জানু.","ফেব্রু.","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগ.","সেপ্টে.","অক্টো.","নভে.","ডিসে.",""]
},
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy",
t: "HH.mm",
T: "HH.mm.ss",
f: "dd MMMM yyyy HH.mm",
F: "dd MMMM yyyy HH.mm.ss",
M: "d MMMM",
Y: "MMMM, yyyy"
}
}
}
});
|
run_spec(__dirname, { parser: "parse5" });
|
require("../lib/jasmine-promise");
var Http = require("../../http");
var Apps = require("../../http-apps");
var FS = require("../../fs");
describe("directory lists", function () {
it("should be fine in plain text", function () {
var fixture = FS.join(module.directory || __dirname, "fixtures");
var app = new Apps.Chain()
.use(Apps.Cap)
.use(Apps.ListDirectories)
.use(function () {
return Apps.FileTree(fixture);
})
.end()
return Http.Server(app)
.listen(0)
.then(function (server) {
var port = server.address().port;
return Http.read({
url: "http://127.0.0.1:" + port + "/",
headers: {
accept: "text/plain"
},
charset: 'utf-8'
})
.then(function (content) {
expect(content).toEqual("01234.txt\n1234.txt\n5678.txt\n9012/\n");
})
.finally(server.stop);
});
});
it("should be fine in html", function () {
var fixture = FS.join(module.directory || __dirname, "fixtures");
var app = new Apps.Chain()
.use(Apps.Cap)
.use(Apps.HandleHtmlFragmentResponses)
.use(Apps.ListDirectories)
.use(function () {
return Apps.FileTree(fixture);
})
.end()
return Http.Server(app)
.listen(0)
.then(function (server) {
var port = server.address().port;
return Http.read({
url: "http://127.0.0.1:" + port + "/",
headers: {
accept: "text/html"
},
charset: 'utf-8'
})
.then(function (content) {
expect(content).toEqual(
"<!doctype html>\n" +
"<html>\n" +
" <head>\n" +
" <title>Directory Index</title>\n" +
" </head>\n" +
" <body>\n" +
" <ul class=\"directory-index\">\n" +
" <li class=\"entry file\"><a href=\"01234.txt\">01234.txt</a></li>\n" +
" <li class=\"entry file\"><a href=\"1234.txt\">1234.txt</a></li>\n" +
" <li class=\"entry file\"><a href=\"5678.txt\">5678.txt</a></li>\n" +
" <li class=\"entry directory\"><a href=\"9012/\">9012/</a></li>\n" +
" </ul>\n" +
" </body>\n" +
"</html>\n"
);
})
.finally(server.stop);
});
});
});
|
Meteor.methods({
deleteUserOwnAccount: function(password) {
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' });
}
if (!RocketChat.settings.get('Accounts_AllowDeleteOwnAccount')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'deleteUserOwnAccount' });
}
const userId = Meteor.userId();
const user = RocketChat.models.Users.findOneById(userId);
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' });
}
if (user.services && user.services.password && s.trim(user.services.password.bcrypt)) {
const result = Accounts._checkPassword(user, { digest: password, algorithm: 'sha-256' });
if (result.error) {
throw new Meteor.Error('error-invalid-password', 'Invalid password', { method: 'deleteUserOwnAccount' });
}
} else if (user.username !== s.trim(password)) {
throw new Meteor.Error('error-invalid-username', 'Invalid username', { method: 'deleteUserOwnAccount' });
}
Meteor.defer(function() {
RocketChat.deleteUser(userId);
});
return true;
}
});
|
/*
* jquery.flot.tooltip
*
* description: easy-to-use tooltips for Flot charts
* version: 0.8.4
* authors: Krzysztof Urbas @krzysu [myviews.pl],Evan Steinkerchner @Roundaround
* website: https://github.com/krzysu/flot.tooltip
*
* build on 2014-08-04
* released under MIT License, 2012
*/
(function ($) {
// plugin options, default values
var defaultOptions = {
tooltip: false,
tooltipOpts: {
id: "flotTip",
content: "%s | X: %x | Y: %y",
// allowed templates are:
// %s -> series label,
// %lx -> x axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
// %ly -> y axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
// %x -> X value,
// %y -> Y value,
// %x.2 -> precision of X value,
// %p -> percent
xDateFormat: null,
yDateFormat: null,
monthNames: null,
dayNames: null,
shifts: {
x: 10,
y: 20
},
defaultTheme: true,
lines: {
track: false,
threshold: 0.05
},
// callbacks
onHover: function (flotItem, $tooltipEl) {},
$compat: false
}
};
// object
var FlotTooltip = function (plot) {
// variables
this.tipPosition = {x: 0, y: 0};
this.init(plot);
};
// main plugin function
FlotTooltip.prototype.init = function (plot) {
var that = this;
// detect other flot plugins
var plotPluginsLength = $.plot.plugins.length;
this.plotPlugins = [];
if (plotPluginsLength) {
for (var p = 0; p < plotPluginsLength; p++) {
this.plotPlugins.push($.plot.plugins[p].name);
}
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
// get plot options
that.plotOptions = plot.getOptions();
// if not enabled return
if (that.plotOptions.tooltip === false || typeof that.plotOptions.tooltip === 'undefined') return;
// shortcut to access tooltip options
that.tooltipOptions = that.plotOptions.tooltipOpts;
if (that.tooltipOptions.$compat) {
that.wfunc = 'width';
that.hfunc = 'height';
} else {
that.wfunc = 'innerWidth';
that.hfunc = 'innerHeight';
}
// create tooltip DOM element
var $tip = that.getDomElement();
// bind event
$( plot.getPlaceholder() ).bind("plothover", plothover);
$(eventHolder).bind('mousemove', mouseMove);
});
plot.hooks.shutdown.push(function (plot, eventHolder){
$(plot.getPlaceholder()).unbind("plothover", plothover);
$(eventHolder).unbind("mousemove", mouseMove);
});
function mouseMove(e){
var pos = {};
pos.x = e.pageX;
pos.y = e.pageY;
plot.setTooltipPosition(pos);
}
function plothover(event, pos, item) {
// Simple distance formula.
var lineDistance = function (p1x, p1y, p2x, p2y) {
return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y));
};
// Here is some voodoo magic for determining the distance to a line form a given point {x, y}.
var dotLineLength = function (x, y, x0, y0, x1, y1, o) {
if (o && !(o =
function (x, y, x0, y0, x1, y1) {
if (typeof x0 !== 'undefined') return { x: x0, y: y };
else if (typeof y0 !== 'undefined') return { x: x, y: y0 };
var left,
tg = -1 / ((y1 - y0) / (x1 - x0));
return {
x: left = (x1 * (x * tg - y + y0) + x0 * (x * -tg + y - y1)) / (tg * (x1 - x0) + y0 - y1),
y: tg * left - tg * x + y
};
} (x, y, x0, y0, x1, y1),
o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))
) {
var l1 = lineDistance(x, y, x0, y0), l2 = lineDistance(x, y, x1, y1);
return l1 > l2 ? l2 : l1;
} else {
var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
}
};
if (item) {
plot.showTooltip(item, pos);
} else if (that.plotOptions.series.lines.show && that.tooltipOptions.lines.track === true) {
var closestTrace = {
distance: -1
};
$.each(plot.getData(), function (i, series) {
var xBeforeIndex = 0,
xAfterIndex = -1;
// Our search here assumes our data is sorted via the x-axis.
// TODO: Improve efficiency somehow - search smaller sets of data.
for (var j = 1; j < series.data.length; j++) {
if (series.data[j - 1][0] <= pos.x && series.data[j][0] >= pos.x) {
xBeforeIndex = j - 1;
xAfterIndex = j;
}
}
if (xAfterIndex === -1) {
plot.hideTooltip();
return;
}
var pointPrev = { x: series.data[xBeforeIndex][0], y: series.data[xBeforeIndex][1] },
pointNext = { x: series.data[xAfterIndex][0], y: series.data[xAfterIndex][1] };
var distToLine = dotLineLength(pos.x, pos.y, pointPrev.x, pointPrev.y, pointNext.x, pointNext.y, false);
if (distToLine < that.tooltipOptions.lines.threshold) {
var closestIndex = lineDistance(pointPrev.x, pointPrev.y, pos.x, pos.y) <
lineDistance(pos.x, pos.y, pointNext.x, pointNext.y) ? xBeforeIndex : xAfterIndex;
var pointSize = series.datapoints.pointsize;
// Calculate the point on the line vertically closest to our cursor.
var pointOnLine = [
pos.x,
pointPrev.y + ((pointNext.y - pointPrev.y) * ((pos.x - pointPrev.x) / (pointNext.x - pointPrev.x)))
];
var item = {
datapoint: pointOnLine,
dataIndex: closestIndex,
series: series,
seriesIndex: i
};
if (closestTrace.distance === -1 || distToLine < closestTrace.distance) {
closestTrace = {
distance: distToLine,
item: item
};
}
}
});
if (closestTrace.distance !== -1)
plot.showTooltip(closestTrace.item, pos);
else
plot.hideTooltip();
} else {
plot.hideTooltip();
}
}
// Quick little function for setting the tooltip position.
plot.setTooltipPosition = function (pos) {
var $tip = that.getDomElement();
var totalTipWidth = $tip.outerWidth() + that.tooltipOptions.shifts.x;
var totalTipHeight = $tip.outerHeight() + that.tooltipOptions.shifts.y;
if ((pos.x - $(window).scrollLeft()) > ($(window)[that.wfunc]() - totalTipWidth)) {
pos.x -= totalTipWidth;
}
if ((pos.y - $(window).scrollTop()) > ($(window)[that.hfunc]() - totalTipHeight)) {
pos.y -= totalTipHeight;
}
that.tipPosition.x = pos.x;
that.tipPosition.y = pos.y;
};
// Quick little function for showing the tooltip.
plot.showTooltip = function (target, position) {
var $tip = that.getDomElement();
// convert tooltip content template to real tipText
var tipText = that.stringFormat(that.tooltipOptions.content, target);
$tip.html(tipText);
plot.setTooltipPosition({ x: position.pageX, y: position.pageY });
$tip.css({
left: that.tipPosition.x + that.tooltipOptions.shifts.x,
top: that.tipPosition.y + that.tooltipOptions.shifts.y
}).show();
// run callback
if (typeof that.tooltipOptions.onHover === 'function') {
that.tooltipOptions.onHover(target, $tip);
}
};
// Quick little function for hiding the tooltip.
plot.hideTooltip = function () {
that.getDomElement().hide().html('');
};
};
/**
* get or create tooltip DOM element
* @return jQuery object
*/
FlotTooltip.prototype.getDomElement = function () {
var $tip = $('#' + this.tooltipOptions.id);
if( $tip.length === 0 ){
$tip = $('<div />').attr('id', this.tooltipOptions.id);
$tip.appendTo('body').hide().css({position: 'absolute'});
if(this.tooltipOptions.defaultTheme) {
$tip.css({
'background': '#fff',
'z-index': '1040',
'padding': '0.4em 0.6em',
'border-radius': '0.5em',
'font-size': '0.8em',
'border': '1px solid #111',
'display': 'none',
'white-space': 'nowrap'
});
}
}
return $tip;
};
/**
* core function, create tooltip content
* @param {string} content - template with tooltip content
* @param {object} item - Flot item
* @return {string} real tooltip content for current item
*/
FlotTooltip.prototype.stringFormat = function (content, item) {
var percentPattern = /%p\.{0,1}(\d{0,})/;
var seriesPattern = /%s/;
var xLabelPattern = /%lx/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
var yLabelPattern = /%ly/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
var xPattern = /%x\.{0,1}(\d{0,})/;
var yPattern = /%y\.{0,1}(\d{0,})/;
var xPatternWithoutPrecision = "%x";
var yPatternWithoutPrecision = "%y";
var customTextPattern = "%ct";
var x, y, customText, p;
// for threshold plugin we need to read data from different place
if (typeof item.series.threshold !== "undefined") {
x = item.datapoint[0];
y = item.datapoint[1];
customText = item.datapoint[2];
} else if (typeof item.series.lines !== "undefined" && item.series.lines.steps) {
x = item.series.datapoints.points[item.dataIndex * 2];
y = item.series.datapoints.points[item.dataIndex * 2 + 1];
// TODO: where to find custom text in this variant?
customText = "";
} else {
x = item.series.data[item.dataIndex][0];
y = item.series.data[item.dataIndex][1];
customText = item.series.data[item.dataIndex][2];
}
// I think this is only in case of threshold plugin
if (item.series.label === null && item.series.originSeries) {
item.series.label = item.series.originSeries.label;
}
// if it is a function callback get the content string
if (typeof(content) === 'function') {
content = content(item.series.label, x, y, item);
}
// percent match for pie charts and stacked percent
if (typeof (item.series.percent) !== 'undefined') {
p = item.series.percent;
} else if (typeof (item.series.percents) !== 'undefined') {
p = item.series.percents[item.dataIndex];
}
if (typeof p === 'number') {
content = this.adjustValPrecision(percentPattern, content, p);
}
// series match
if (typeof(item.series.label) !== 'undefined') {
content = content.replace(seriesPattern, item.series.label);
} else {
//remove %s if label is undefined
content = content.replace(seriesPattern, "");
}
// x axis label match
if (this.hasAxisLabel('xaxis', item)) {
content = content.replace(xLabelPattern, item.series.xaxis.options.axisLabel);
} else {
//remove %lx if axis label is undefined or axislabels plugin not present
content = content.replace(xLabelPattern, "");
}
// y axis label match
if (this.hasAxisLabel('yaxis', item)) {
content = content.replace(yLabelPattern, item.series.yaxis.options.axisLabel);
} else {
//remove %ly if axis label is undefined or axislabels plugin not present
content = content.replace(yLabelPattern, "");
}
// time mode axes with custom dateFormat
if (this.isTimeMode('xaxis', item) && this.isXDateFormat(item)) {
content = content.replace(xPattern, this.timestampToDate(x, this.tooltipOptions.xDateFormat, item.series.xaxis.options));
}
if (this.isTimeMode('yaxis', item) && this.isYDateFormat(item)) {
content = content.replace(yPattern, this.timestampToDate(y, this.tooltipOptions.yDateFormat, item.series.yaxis.options));
}
// set precision if defined
if (typeof x === 'number') {
content = this.adjustValPrecision(xPattern, content, x);
}
if (typeof y === 'number') {
content = this.adjustValPrecision(yPattern, content, y);
}
// change x from number to given label, if given
if (typeof item.series.xaxis.ticks !== 'undefined') {
var ticks;
if (this.hasRotatedXAxisTicks(item)) {
// xaxis.ticks will be an empty array if tickRotor is being used, but the values are available in rotatedTicks
ticks = 'rotatedTicks';
} else {
ticks = 'ticks';
}
// see https://github.com/krzysu/flot.tooltip/issues/65
var tickIndex = item.dataIndex + item.seriesIndex;
if (item.series.xaxis[ticks].length > tickIndex && !this.isTimeMode('xaxis', item)) {
var valueX = (this.isCategoriesMode('xaxis', item)) ? item.series.xaxis[ticks][tickIndex].label : item.series.xaxis[ticks][tickIndex].v;
if (valueX === x) {
content = content.replace(xPattern, item.series.xaxis[ticks][tickIndex].label);
}
}
}
// change y from number to given label, if given
if (typeof item.series.yaxis.ticks !== 'undefined') {
for (var index in item.series.yaxis.ticks) {
if (item.series.yaxis.ticks.hasOwnProperty(index)) {
var valueY = (this.isCategoriesMode('yaxis', item)) ? item.series.yaxis.ticks[index].label : item.series.yaxis.ticks[index].v;
if (valueY === y) {
content = content.replace(yPattern, item.series.yaxis.ticks[index].label);
}
}
}
}
// if no value customization, use tickFormatter by default
if (typeof item.series.xaxis.tickFormatter !== 'undefined') {
//escape dollar
content = content.replace(xPatternWithoutPrecision, item.series.xaxis.tickFormatter(x, item.series.xaxis).replace(/\$/g, '$$'));
}
if (typeof item.series.yaxis.tickFormatter !== 'undefined') {
//escape dollar
content = content.replace(yPatternWithoutPrecision, item.series.yaxis.tickFormatter(y, item.series.yaxis).replace(/\$/g, '$$'));
}
if (customText)
content = content.replace(customTextPattern, customText);
return content;
};
// helpers just for readability
FlotTooltip.prototype.isTimeMode = function (axisName, item) {
return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'time');
};
FlotTooltip.prototype.isXDateFormat = function (item) {
return (typeof this.tooltipOptions.xDateFormat !== 'undefined' && this.tooltipOptions.xDateFormat !== null);
};
FlotTooltip.prototype.isYDateFormat = function (item) {
return (typeof this.tooltipOptions.yDateFormat !== 'undefined' && this.tooltipOptions.yDateFormat !== null);
};
FlotTooltip.prototype.isCategoriesMode = function (axisName, item) {
return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'categories');
};
//
FlotTooltip.prototype.timestampToDate = function (tmst, dateFormat, options) {
var theDate = $.plot.dateGenerator(tmst, options);
return $.plot.formatDate(theDate, dateFormat, this.tooltipOptions.monthNames, this.tooltipOptions.dayNames);
};
//
FlotTooltip.prototype.adjustValPrecision = function (pattern, content, value) {
var precision;
var matchResult = content.match(pattern);
if( matchResult !== null ) {
if(RegExp.$1 !== '') {
precision = RegExp.$1;
value = value.toFixed(precision);
// only replace content if precision exists, in other case use thickformater
content = content.replace(pattern, value);
}
}
return content;
};
// other plugins detection below
// check if flot-axislabels plugin (https://github.com/markrcote/flot-axislabels) is used and that an axis label is given
FlotTooltip.prototype.hasAxisLabel = function (axisName, item) {
return ($.inArray(this.plotPlugins, 'axisLabels') !== -1 && typeof item.series[axisName].options.axisLabel !== 'undefined' && item.series[axisName].options.axisLabel.length > 0);
};
// check whether flot-tickRotor, a plugin which allows rotation of X-axis ticks, is being used
FlotTooltip.prototype.hasRotatedXAxisTicks = function (item) {
return ($.inArray(this.plotPlugins, 'tickRotor') !== -1 && typeof item.series.xaxis.rotatedTicks !== 'undefined');
};
//
var init = function (plot) {
new FlotTooltip(plot);
};
// define Flot plugin
$.plot.plugins.push({
init: init,
options: defaultOptions,
name: 'tooltip',
version: '0.8.4'
});
})(jQuery);
|
(function($) {
var csscls = PhpDebugBar.utils.makecsscls('phpdebugbar-widgets-');
/**
* Widget for the displaying sql queries
*
* Options:
* - data
*/
var SQLQueriesWidget = PhpDebugBar.Widgets.SQLQueriesWidget = PhpDebugBar.Widget.extend({
className: csscls('sqlqueries'),
render: function() {
this.$status = $('<div />').addClass(csscls('status')).appendTo(this.$el);
this.$list = new PhpDebugBar.Widgets.ListWidget({ itemRenderer: function(li, stmt) {
$('<code />').addClass(csscls('sql')).html(PhpDebugBar.Widgets.highlight(stmt.sql, 'sql')).appendTo(li);
if (stmt.duration_str) {
$('<span title="Duration" />').addClass(csscls('duration')).text(stmt.duration_str).appendTo(li);
}
if (stmt.memory_str) {
$('<span title="Memory usage" />').addClass(csscls('memory')).text(stmt.memory_str).appendTo(li);
}
if (typeof(stmt.is_success) != 'undefined' && !stmt.is_success) {
li.addClass(csscls('error'));
li.append($('<span />').addClass(csscls('error')).text("[" + stmt.error_code + "] " + stmt.error_message));
} else if (typeof(stmt.row_count) != 'undefined') {
$('<span title="Row count" />').addClass(csscls('row-count')).text(stmt.row_count).appendTo(li);
}
if (typeof(stmt.stmt_id) != 'undefined' && stmt.stmt_id) {
$('<span title="Prepared statement ID" />').addClass(csscls('stmt-id')).text(stmt.stmt_id).appendTo(li);
}
if (stmt.params && !$.isEmptyObject(stmt.params)) {
var table = $('<table><tr><th colspan="2">Params</th></tr></table>').addClass(csscls('params')).appendTo(li);
for (var key in stmt.params) {
if (typeof stmt.params[key] !== 'function') {
table.append('<tr><td class="' + csscls('name') + '">' + key + '</td><td class="' + csscls('value') +
'">' + stmt.params[key] + '</td></tr>');
}
}
li.css('cursor', 'pointer').click(function() {
if (table.is(':visible')) {
table.hide();
} else {
table.show();
}
});
}
}});
this.$list.$el.appendTo(this.$el);
this.bindAttr('data', function(data) {
this.$list.set('data', data.statements);
this.$status.empty();
// Search for duplicate statements.
for (var sql = {}, duplicate = 0, i = 0; i < data.statements.length; i++) {
var stmt = data.statements[i].sql;
if (data.statements[i].params && !$.isEmptyObject(data.statements[i].params)) {
stmt += ' {' + $.param(data.statements[i].params, false) + '}';
}
sql[stmt] = sql[stmt] || { keys: [] };
sql[stmt].keys.push(i);
}
// Add classes to all duplicate SQL statements.
for (var stmt in sql) {
if (sql[stmt].keys.length > 1) {
duplicate++;
for (var i = 0; i < sql[stmt].keys.length; i++) {
this.$list.$el.find('.' + csscls('list-item')).eq(sql[stmt].keys[i])
.addClass(csscls('sql-duplicate')).addClass(csscls('sql-duplicate-'+duplicate));
}
}
}
var t = $('<span />').text(data.nb_statements + " statements were executed").appendTo(this.$status);
if (data.nb_failed_statements) {
t.append(", " + data.nb_failed_statements + " of which failed");
}
if (duplicate) {
t.append(", " + duplicate + " of which were duplicated");
}
if (data.accumulated_duration_str) {
this.$status.append($('<span title="Accumulated duration" />').addClass(csscls('duration')).text(data.accumulated_duration_str));
}
if (data.memory_usage_str) {
this.$status.append($('<span title="Memory usage" />').addClass(csscls('memory')).text(data.memory_usage_str));
}
});
}
});
})(PhpDebugBar.$);
|
/**
* Livechat Trigger model
*/
class LivechatTrigger extends RocketChat.models._Base {
constructor() {
super();
this._initModel('livechat_trigger');
}
// FIND
save(data) {
const trigger = this.findOne();
if (trigger) {
return this.update({ _id: trigger._id }, { $set: data });
} else {
return this.insert(data);
}
}
removeAll() {
this.remove({});
}
}
RocketChat.models.LivechatTrigger = new LivechatTrigger();
|
// Copyright 2013 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 A pool of forward channel requests to enable real-time
* messaging from the client to server.
*
* @visibility {:internal}
*/
goog.provide('goog.labs.net.webChannel.ForwardChannelRequestPool');
goog.require('goog.array');
goog.require('goog.string');
goog.require('goog.structs.Set');
goog.scope(function() {
// type checking only (no require)
var ChannelRequest = goog.labs.net.webChannel.ChannelRequest;
/**
* This class represents the state of all forward channel requests.
*
* @param {number=} opt_maxPoolSize The maximum pool size.
*
* @constructor
* @final
*/
goog.labs.net.webChannel.ForwardChannelRequestPool = function(opt_maxPoolSize) {
/**
* THe max pool size as configured.
*
* @private {number}
*/
this.maxPoolSizeConfigured_ = opt_maxPoolSize ||
goog.labs.net.webChannel.ForwardChannelRequestPool.MAX_POOL_SIZE_;
/**
* The current size limit of the request pool. This limit is meant to be
* read-only after the channel is fully opened.
*
* If SPDY is enabled, set it to the max pool size, which is also
* configurable.
*
* @private {number}
*/
this.maxSize_ = ForwardChannelRequestPool.isSpdyEnabled_() ?
this.maxPoolSizeConfigured_ :
1;
/**
* The container for all the pending request objects.
*
* @private {goog.structs.Set<ChannelRequest>}
*/
this.requestPool_ = null;
if (this.maxSize_ > 1) {
this.requestPool_ = new goog.structs.Set();
}
/**
* The single request object when the pool size is limited to one.
*
* @private {ChannelRequest}
*/
this.request_ = null;
};
var ForwardChannelRequestPool =
goog.labs.net.webChannel.ForwardChannelRequestPool;
/**
* The default size limit of the request pool.
*
* @private {number}
*/
ForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;
/**
* @return {boolean} True if SPDY is enabled for the current page using
* chrome specific APIs.
* @private
*/
ForwardChannelRequestPool.isSpdyEnabled_ = function() {
return !!(
goog.global.chrome && goog.global.chrome.loadTimes &&
goog.global.chrome.loadTimes() &&
goog.global.chrome.loadTimes().wasFetchedViaSpdy);
};
/**
* Once we know the client protocol (from the handshake), check if we need
* enable the request pool accordingly. This is more robust than using
* browser-internal APIs (specific to Chrome).
*
* @param {string} clientProtocol The client protocol
*/
ForwardChannelRequestPool.prototype.applyClientProtocol = function(
clientProtocol) {
if (this.requestPool_) {
return;
}
if (goog.string.contains(clientProtocol, 'spdy') ||
goog.string.contains(clientProtocol, 'quic')) {
this.maxSize_ = this.maxPoolSizeConfigured_;
this.requestPool_ = new goog.structs.Set();
if (this.request_) {
this.addRequest(this.request_);
this.request_ = null;
}
}
};
/**
* @return {boolean} True if the pool is full.
*/
ForwardChannelRequestPool.prototype.isFull = function() {
if (this.request_) {
return true;
}
if (this.requestPool_) {
return this.requestPool_.getCount() >= this.maxSize_;
}
return false;
};
/**
* @return {number} The current size limit.
*/
ForwardChannelRequestPool.prototype.getMaxSize = function() {
return this.maxSize_;
};
/**
* @return {number} The number of pending requests in the pool.
*/
ForwardChannelRequestPool.prototype.getRequestCount = function() {
if (this.request_) {
return 1;
}
if (this.requestPool_) {
return this.requestPool_.getCount();
}
return 0;
};
/**
* @param {ChannelRequest} req The channel request.
* @return {boolean} True if the request is a included inside the pool.
*/
ForwardChannelRequestPool.prototype.hasRequest = function(req) {
if (this.request_) {
return this.request_ == req;
}
if (this.requestPool_) {
return this.requestPool_.contains(req);
}
return false;
};
/**
* Adds a new request to the pool.
*
* @param {!ChannelRequest} req The new channel request.
*/
ForwardChannelRequestPool.prototype.addRequest = function(req) {
if (this.requestPool_) {
this.requestPool_.add(req);
} else {
this.request_ = req;
}
};
/**
* Removes the given request from the pool.
*
* @param {ChannelRequest} req The channel request.
* @return {boolean} Whether the request has been removed from the pool.
*/
ForwardChannelRequestPool.prototype.removeRequest = function(req) {
if (this.request_ && this.request_ == req) {
this.request_ = null;
return true;
}
if (this.requestPool_ && this.requestPool_.contains(req)) {
this.requestPool_.remove(req);
return true;
}
return false;
};
/**
* Clears the pool and cancel all the pending requests.
*/
ForwardChannelRequestPool.prototype.cancel = function() {
if (this.request_) {
this.request_.cancel();
this.request_ = null;
return;
}
if (this.requestPool_ && !this.requestPool_.isEmpty()) {
goog.array.forEach(
this.requestPool_.getValues(), function(val) { val.cancel(); });
this.requestPool_.clear();
}
};
/**
* @return {boolean} Whether there are any pending requests.
*/
ForwardChannelRequestPool.prototype.hasPendingRequest = function() {
return (this.request_ != null) ||
(this.requestPool_ != null && !this.requestPool_.isEmpty());
};
/**
* Cancels all pending requests and force the completion of channel requests.
*
* Need go through the standard onRequestComplete logic to expose the max-retry
* failure in the standard way.
*
* @param {!function(!ChannelRequest)} onComplete The completion callback.
* @return {boolean} true if any request has been forced to complete.
*/
ForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {
if (this.request_ != null) {
this.request_.cancel();
onComplete(this.request_);
return true;
}
if (this.requestPool_ && !this.requestPool_.isEmpty()) {
goog.array.forEach(this.requestPool_.getValues(), function(val) {
val.cancel();
onComplete(val);
});
return true;
}
return false;
};
}); // goog.scope
|
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
var setupCustomJSON = function(JSON) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}
function _isUndefined(what) {
return typeof what === 'undefined';
}
var UNKNOWN_FUNCTION = '?';
function computeStackTraceWrapper(options) {
var debug = false,
sourceCache = {};
var remoteFetching = options.remoteFetching;
var linesOfContext = options.linesOfContext;
var tracekitReport = options.tracekitReport;
/**
* Attempts to retrieve source code via XMLHttpRequest, which is used
* to look up anonymous function names.
* @param {string} url URL of source code.
* @return {string} Source contents.
*/
function loadSource(url) {
if (!remoteFetching) { //Only attempt request if remoteFetching is on.
return '';
}
try {
var getXHR = function() {
try {
return new window.XMLHttpRequest();
} catch (e) {
// explicitly bubble up the exception if not found
return new window.ActiveXObject('Microsoft.XMLHTTP');
}
};
var request = getXHR();
request.open('GET', url, false);
request.send('');
return request.responseText;
} catch (e) {
return '';
}
}
/**
* Retrieves source code from the source code cache.
* @param {string} url URL of source code.
* @return {Array.<string>} Source contents.
*/
function getSource(url) {
if (!sourceCache.hasOwnProperty(url)) {
// URL needs to be able to fetched within the acceptable domain. Otherwise,
// cross-domain errors will be triggered.
var source = '';
if (url.indexOf(document.domain) !== -1) {
source = loadSource(url);
}
sourceCache[url] = source ? source.split('\n') : [];
}
return sourceCache[url];
}
/**
* Tries to use an externally loaded copy of source code to determine
* the name of a function by looking at the name of the variable it was
* assigned to, if any.
* @param {string} url URL of source code.
* @param {(string|number)} lineNo Line number in source code.
* @return {string} The function name, if discoverable.
*/
function guessFunctionName(url, lineNo) {
var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/,
reGuessFunction = /['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,
line = '',
maxLines = 10,
source = getSource(url),
m;
if (!source.length) {
return UNKNOWN_FUNCTION;
}
// Walk backwards from the first line in the function until we find the line which
// matches the pattern above, which is the function definition
for (var i = 0; i < maxLines; ++i) {
line = source[lineNo - i] + line;
if (!_isUndefined(line)) {
if ((m = reGuessFunction.exec(line))) {
return m[1];
} else if ((m = reFunctionArgNames.exec(line))) {
return m[1];
}
}
}
return UNKNOWN_FUNCTION;
}
/**
* Retrieves the surrounding lines from where an exception occurred.
* @param {string} url URL of source code.
* @param {(string|number)} line Line number in source code to centre
* around for context.
* @return {?Array.<string>} Lines of source code.
*/
function gatherContext(url, line) {
var source = getSource(url);
if (!source.length) {
return null;
}
var context = [],
// linesBefore & linesAfter are inclusive with the offending line.
// if linesOfContext is even, there will be one extra line
// *before* the offending line.
linesBefore = Math.floor(linesOfContext / 2),
// Add one extra line if linesOfContext is odd
linesAfter = linesBefore + (linesOfContext % 2),
start = Math.max(0, line - linesBefore - 1),
end = Math.min(source.length, line + linesAfter - 1);
line -= 1; // convert to 0-based index
for (var i = start; i < end; ++i) {
if (!_isUndefined(source[i])) {
context.push(source[i]);
}
}
return context.length > 0 ? context : null;
}
/**
* Escapes special characters, except for whitespace, in a string to be
* used inside a regular expression as a string literal.
* @param {string} text The string.
* @return {string} The escaped string literal.
*/
function escapeRegExp(text) {
return text.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g, '\\$&');
}
/**
* Escapes special characters in a string to be used inside a regular
* expression as a string literal. Also ensures that HTML entities will
* be matched the same as their literal friends.
* @param {string} body The string.
* @return {string} The escaped string.
*/
function escapeCodeAsRegExpForMatchingInsideHTML(body) {
return escapeRegExp(body).replace('<', '(?:<|<)').replace('>', '(?:>|>)').replace('&', '(?:&|&)').replace('"', '(?:"|")').replace(/\s+/g, '\\s+');
}
/**
* Determines where a code fragment occurs in the source code.
* @param {RegExp} re The function definition.
* @param {Array.<string>} urls A list of URLs to search.
* @return {?Object.<string, (string|number)>} An object containing
* the url, line, and column number of the defined function.
*/
function findSourceInUrls(re, urls) {
var source, m;
for (var i = 0, j = urls.length; i < j; ++i) {
// console.log('searching', urls[i]);
if ((source = getSource(urls[i])).length) {
source = source.join('\n');
if ((m = re.exec(source))) {
// console.log('Found function in ' + urls[i]);
return {
'url': urls[i],
'line': source.substring(0, m.index).split('\n').length,
'column': m.index - source.lastIndexOf('\n', m.index) - 1
};
}
}
}
// console.log('no match');
return null;
}
/**
* Determines at which column a code fragment occurs on a line of the
* source code.
* @param {string} fragment The code fragment.
* @param {string} url The URL to search.
* @param {(string|number)} line The line number to examine.
* @return {?number} The column number.
*/
function findSourceInLine(fragment, url, line) {
var source = getSource(url),
re = new RegExp('\\b' + escapeRegExp(fragment) + '\\b'),
m;
line -= 1;
if (source && source.length > line && (m = re.exec(source[line]))) {
return m.index;
}
return null;
}
/**
* Determines where a function was defined within the source code.
* @param {(Function|string)} func A function reference or serialized
* function definition.
* @return {?Object.<string, (string|number)>} An object containing
* the url, line, and column number of the defined function.
*/
function findSourceByFunctionBody(func) {
var urls = [window.location.href],
scripts = document.getElementsByTagName('script'),
body,
code = '' + func,
codeRE = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,
eventRE = /^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,
re,
parts,
result;
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
if (script.src) {
urls.push(script.src);
}
}
if (!(parts = codeRE.exec(code))) {
re = new RegExp(escapeRegExp(code).replace(/\s+/g, '\\s+'));
}
// not sure if this is really necessary, but I don’t have a test
// corpus large enough to confirm that and it was in the original.
else {
var name = parts[1] ? '\\s+' + parts[1] : '',
args = parts[2].split(',').join('\\s*,\\s*');
body = escapeRegExp(parts[3]).replace(/;$/, ';?'); // semicolon is inserted if the function ends with a comment.replace(/\s+/g, '\\s+');
re = new RegExp('function' + name + '\\s*\\(\\s*' + args + '\\s*\\)\\s*{\\s*' + body + '\\s*}');
}
// look for a normal function definition
if ((result = findSourceInUrls(re, urls))) {
return result;
}
// look for an old-school event handler function
if ((parts = eventRE.exec(code))) {
var event = parts[1];
body = escapeCodeAsRegExpForMatchingInsideHTML(parts[2]);
// look for a function defined in HTML as an onXXX handler
re = new RegExp('on' + event + '=[\\\'"]\\s*' + body + '\\s*[\\\'"]', 'i');
if ((result = findSourceInUrls(re, urls[0]))) {
return result;
}
// look for ???
re = new RegExp(body);
if ((result = findSourceInUrls(re, urls))) {
return result;
}
}
return null;
}
// Contents of Exception in various browsers.
//
// SAFARI:
// ex.message = Can't find variable: qq
// ex.line = 59
// ex.sourceId = 580238192
// ex.sourceURL = http://...
// ex.expressionBeginOffset = 96
// ex.expressionCaretOffset = 98
// ex.expressionEndOffset = 98
// ex.name = ReferenceError
//
// FIREFOX:
// ex.message = qq is not defined
// ex.fileName = http://...
// ex.lineNumber = 59
// ex.stack = ...stack trace... (see the example below)
// ex.name = ReferenceError
//
// CHROME:
// ex.message = qq is not defined
// ex.name = ReferenceError
// ex.type = not_defined
// ex.arguments = ['aa']
// ex.stack = ...stack trace...
//
// INTERNET EXPLORER:
// ex.message = ...
// ex.name = ReferenceError
//
// OPERA:
// ex.message = ...message... (see the example below)
// ex.name = ReferenceError
// ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message)
// ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
/**
* Computes stack trace information from the stack property.
* Chrome and Gecko use this property.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceFromStackProp(ex) {
if (!ex.stack) {
return null;
}
var chrome = /^\s*at (?:((?:\[object object\])?\S+(?: \[as \S+\])?) )?\(?((?:file|http|https):.*?):(\d+)(?::(\d+))?\)?\s*$/i,
gecko = /^\s*(\S*)(?:\((.*?)\))?@((?:file|http|https).*?):(\d+)(?::(\d+))?\s*$/i,
lines = ex.stack.split('\n'),
stack = [],
parts,
element,
reference = /^(.*) is undefined$/.exec(ex.message);
for (var i = 0, j = lines.length; i < j; ++i) {
if ((parts = gecko.exec(lines[i]))) {
element = {
'url': parts[3],
'func': parts[1] || UNKNOWN_FUNCTION,
'args': parts[2] ? parts[2].split(',') : '',
'line': +parts[4],
'column': parts[5] ? +parts[5] : null
};
} else if ((parts = chrome.exec(lines[i]))) {
element = {
'url': parts[2],
'func': parts[1] || UNKNOWN_FUNCTION,
'line': +parts[3],
'column': parts[4] ? +parts[4] : null
};
} else {
continue;
}
if (!element.func && element.line) {
element.func = guessFunctionName(element.url, element.line);
}
if (element.line) {
element.context = gatherContext(element.url, element.line);
}
stack.push(element);
}
if (stack[0] && stack[0].line && !stack[0].column && reference) {
stack[0].column = findSourceInLine(reference[1], stack[0].url, stack[0].line);
}
if (!stack.length) {
return null;
}
return {
'mode': 'stack',
'name': ex.name,
'message': ex.message,
'url': document.location.href,
'stack': stack,
'useragent': navigator.userAgent
};
}
/**
* Computes stack trace information from the stacktrace property.
* Opera 10 uses this property.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceFromStacktraceProp(ex) {
// Access and store the stacktrace property before doing ANYTHING
// else to it because Opera is not very good at providing it
// reliably in other circumstances.
var stacktrace = ex.stacktrace;
var testRE = / line (\d+), column (\d+) in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\) in (.*):\s*$/i,
lines = stacktrace.split('\n'),
stack = [],
parts;
for (var i = 0, j = lines.length; i < j; i += 2) {
if ((parts = testRE.exec(lines[i]))) {
var element = {
'line': +parts[1],
'column': +parts[2],
'func': parts[3] || parts[4],
'args': parts[5] ? parts[5].split(',') : [],
'url': parts[6]
};
if (!element.func && element.line) {
element.func = guessFunctionName(element.url, element.line);
}
if (element.line) {
try {
element.context = gatherContext(element.url, element.line);
} catch (exc) {}
}
if (!element.context) {
element.context = [lines[i + 1]];
}
stack.push(element);
}
}
if (!stack.length) {
return null;
}
return {
'mode': 'stacktrace',
'name': ex.name,
'message': ex.message,
'url': document.location.href,
'stack': stack,
'useragent': navigator.userAgent
};
}
/**
* NOT TESTED.
* Computes stack trace information from an error message that includes
* the stack trace.
* Opera 9 and earlier use this method if the option to show stack
* traces is turned on in opera:config.
* @param {Error} ex
* @return {?Object.<string, *>} Stack information.
*/
function computeStackTraceFromOperaMultiLineMessage(ex) {
// Opera includes a stack trace into the exception message. An example is:
//
// Statement on line 3: Undefined variable: undefinedFunc
// Backtrace:
// Line 3 of linked script file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.js: In function zzz
// undefinedFunc(a);
// Line 7 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function yyy
// zzz(x, y, z);
// Line 3 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function xxx
// yyy(a, a, a);
// Line 1 of function script
// try { xxx('hi'); return false; } catch(ex) { TraceKit.report(ex); }
// ...
var lines = ex.message.split('\n');
if (lines.length < 4) {
return null;
}
var lineRE1 = /^\s*Line (\d+) of linked script ((?:file|http|https)\S+)(?:: in function (\S+))?\s*$/i,
lineRE2 = /^\s*Line (\d+) of inline#(\d+) script in ((?:file|http|https)\S+)(?:: in function (\S+))?\s*$/i,
lineRE3 = /^\s*Line (\d+) of function script\s*$/i,
stack = [],
scripts = document.getElementsByTagName('script'),
inlineScriptBlocks = [],
parts,
i,
len,
source;
for (i in scripts) {
if (scripts.hasOwnProperty(i) && !scripts[i].src) {
inlineScriptBlocks.push(scripts[i]);
}
}
for (i = 2, len = lines.length; i < len; i += 2) {
var item = null;
if ((parts = lineRE1.exec(lines[i]))) {
item = {
'url': parts[2],
'func': parts[3],
'line': +parts[1]
};
} else if ((parts = lineRE2.exec(lines[i]))) {
item = {
'url': parts[3],
'func': parts[4]
};
var relativeLine = (+parts[1]); // relative to the start of the <SCRIPT> block
var script = inlineScriptBlocks[parts[2] - 1];
if (script) {
source = getSource(item.url);
if (source) {
source = source.join('\n');
var pos = source.indexOf(script.innerText);
if (pos >= 0) {
item.line = relativeLine + source.substring(0, pos).split('\n').length;
}
}
}
} else if ((parts = lineRE3.exec(lines[i]))) {
var url = window.location.href.replace(/#.*$/, ''),
line = parts[1];
var re = new RegExp(escapeCodeAsRegExpForMatchingInsideHTML(lines[i + 1]));
source = findSourceInUrls(re, [url]);
item = {
'url': url,
'line': source ? source.line : line,
'func': ''
};
}
if (item) {
if (!item.func) {
item.func = guessFunctionName(item.url, item.line);
}
var context = gatherContext(item.url, item.line);
var midline = (context ? context[Math.floor(context.length / 2)] : null);
if (context && midline.replace(/^\s*/, '') === lines[i + 1].replace(/^\s*/, '')) {
item.context = context;
} else {
// if (context) alert("Context mismatch. Correct midline:\n" + lines[i+1] + "\n\nMidline:\n" + midline + "\n\nContext:\n" + context.join("\n") + "\n\nURL:\n" + item.url);
item.context = [lines[i + 1]];
}
stack.push(item);
}
}
if (!stack.length) {
return null; // could not parse multiline exception message as Opera stack trace
}
return {
'mode': 'multiline',
'name': ex.name,
'message': lines[0],
'url': document.location.href,
'stack': stack,
'useragent': navigator.userAgent
};
}
/**
* Adds information about the first frame to incomplete stack traces.
* Safari and IE require this to get complete data on the first frame.
* @param {Object.<string, *>} stackInfo Stack trace information from
* one of the compute* methods.
* @param {string} url The URL of the script that caused an error.
* @param {(number|string)} lineNo The line number of the script that
* caused an error.
* @param {string=} message The error generated by the browser, which
* hopefully contains the name of the object that caused the error.
* @return {boolean} Whether or not the stack information was
* augmented.
*/
function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) {
var initial = {
'url': url,
'line': lineNo
};
if (initial.url && initial.line) {
stackInfo.incomplete = false;
if (!initial.func) {
initial.func = guessFunctionName(initial.url, initial.line);
}
if (!initial.context) {
initial.context = gatherContext(initial.url, initial.line);
}
var reference = / '([^']+)' /.exec(message);
if (reference) {
initial.column = findSourceInLine(reference[1], initial.url, initial.line);
}
if (stackInfo.stack.length > 0) {
if (stackInfo.stack[0].url === initial.url) {
if (stackInfo.stack[0].line === initial.line) {
return false; // already in stack trace
} else if (!stackInfo.stack[0].line && stackInfo.stack[0].func === initial.func) {
stackInfo.stack[0].line = initial.line;
stackInfo.stack[0].context = initial.context;
return false;
}
}
}
stackInfo.stack.unshift(initial);
stackInfo.partial = true;
return true;
} else {
stackInfo.incomplete = true;
}
return false;
}
/**
* Computes stack trace information by walking the arguments.caller
* chain at the time the exception occurred. This will cause earlier
* frames to be missed but is the only way to get any stack trace in
* Safari and IE. The top frame is restored by
* {@link augmentStackTraceWithInitialElement}.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceByWalkingCallerChain(ex, depth) {
var functionName = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,
stack = [],
funcs = {},
recursion = false,
parts,
item,
source;
for (var curr = computeStackTraceByWalkingCallerChain.caller; curr && !recursion; curr = curr.caller) {
if (curr === computeStackTrace || curr === tracekitReport) {
// console.log('skipping internal function');
continue;
}
item = {
'url': null,
'func': UNKNOWN_FUNCTION,
'line': null,
'column': null
};
if (curr.name) {
item.func = curr.name;
} else if ((parts = functionName.exec(curr.toString()))) {
item.func = parts[1];
}
if ((source = findSourceByFunctionBody(curr))) {
item.url = source.url;
item.line = source.line;
if (item.func === UNKNOWN_FUNCTION) {
item.func = guessFunctionName(item.url, item.line);
}
var reference = / '([^']+)' /.exec(ex.message || ex.description);
if (reference) {
item.column = findSourceInLine(reference[1], source.url, source.line);
}
}
if (funcs['' + curr]) {
recursion = true;
}else{
funcs['' + curr] = true;
}
stack.push(item);
}
if (depth) {
// console.log('depth is ' + depth);
// console.log('stack is ' + stack.length);
stack.splice(0, depth);
}
var result = {
'mode': 'callers',
'name': ex.name,
'message': ex.message,
'url': document.location.href,
'stack': stack,
'useragent': navigator.userAgent
};
augmentStackTraceWithInitialElement(result, ex.sourceURL || ex.fileName, ex.line || ex.lineNumber, ex.message || ex.description);
return result;
}
/**
* Computes a stack trace for an exception.
* @param {Error} ex
* @param {(string|number)=} depth
*/
function computeStackTrace(ex, depth) {
var stack = null;
depth = (depth == null ? 0 : +depth);
try {
// This must be tried first because Opera 10 *destroys*
// its stacktrace property if you try to access the stack
// property first!!
stack = computeStackTraceFromStacktraceProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceFromStackProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceFromOperaMultiLineMessage(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceByWalkingCallerChain(ex, depth + 1);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
return {
'mode': 'failed'
};
}
/**
* Logs a stacktrace starting from the previous call and working down.
* @param {(number|string)=} depth How many frames deep to trace.
* @return {Object.<string, *>} Stack trace information.
*/
function computeStackTraceOfCaller(depth) {
depth = (depth == null ? 0 : +depth) + 1; // "+ 1" because "ofCaller" should drop one frame
try {
throw new Error();
} catch (ex) {
return computeStackTrace(ex, depth + 1);
}
}
computeStackTrace.augmentStackTraceWithInitialElement = augmentStackTraceWithInitialElement;
computeStackTrace.guessFunctionName = guessFunctionName;
computeStackTrace.gatherContext = gatherContext;
computeStackTrace.ofCaller = computeStackTraceOfCaller;
return computeStackTrace;
}
var Util = {
// modified from https://github.com/jquery/jquery/blob/master/src/core.js#L127
merge: function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = true;
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && typeof target !== 'function') {
target = {};
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) !== null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (copy.constructor == Object || (copyIsArray = (copy.constructor == Array)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && src.constructor == Array ? src : [];
} else {
clone = src && src.constructor == Object ? src : {};
}
// Never move original objects, clone them
target[name] = Util.merge(clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
},
copy: function(obj) {
var dest;
if (typeof obj === 'object') {
if (obj.constructor == Object) {
dest = {};
} else if (obj.constructor == Array) {
dest = [];
}
}
Util.merge(dest, obj);
return dest;
},
parseUriOptions: {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
},
parseUri: function(str) {
if (!str || (typeof str !== 'string' && !(str instanceof String))) {
throw new Error('Util.parseUri() received invalid input');
}
var o = Util.parseUriOptions;
var m = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
var uri = {};
var i = 14;
while (i--) {
uri[o.key[i]] = m[i] || "";
}
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) {
uri[o.q.name][$1] = $2;
}
});
return uri;
},
sanitizeUrl: function(url) {
if (!url || (typeof url !== 'string' && !(url instanceof String))) {
throw new Error('Util.sanitizeUrl() received invalid input');
}
var baseUrlParts = Util.parseUri(url);
// remove a trailing # if there is no anchor
if (baseUrlParts.anchor === '') {
baseUrlParts.source = baseUrlParts.source.replace('#', '');
}
url = baseUrlParts.source.replace('?' + baseUrlParts.query, '');
return url;
},
traverse: function(obj, func) {
var k;
var v;
var i;
var isObj = typeof obj === 'object';
var keys = [];
if (isObj) {
if (obj.constructor === Object) {
for (k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
} else if (obj.constructor === Array) {
for (i = 0; i < obj.length; ++i) {
keys.push(i);
}
}
}
for (i = 0; i < keys.length; ++i) {
k = keys[i];
v = obj[k];
isObj = typeof v === 'object';
if (isObj) {
if (v === null) {
obj[k] = func(k, v);
} else if (v.constructor === Object) {
obj[k] = Util.traverse(v, func);
} else if (v.constructor === Array) {
obj[k] = Util.traverse(v, func);
} else {
obj[k] = func(k, v);
}
} else {
obj[k] = func(k, v);
}
}
return obj;
},
redact: function(val) {
val = String(val);
return new Array(val.length + 1).join('*');
},
// from http://stackoverflow.com/a/8809472/1138191
uuid4: function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
}
};
var RollbarJSON = {};
var testData = {a:[{b:1}]};
try {
var serialized = JSON.stringify(testData);
if (serialized !== '{"a":[{"b":1}]}') {
setupCustomJSON(RollbarJSON);
} else {
RollbarJSON.stringify = JSON.stringify;
RollbarJSON.parse = JSON.parse;
}
} catch (e) {
setupCustomJSON(RollbarJSON);
}
var XHR = {
XMLHttpFactories: [
function () {return new XMLHttpRequest();},
function () {return new ActiveXObject("Msxml2.XMLHTTP");},
function () {return new ActiveXObject("Msxml3.XMLHTTP");},
function () {return new ActiveXObject("Microsoft.XMLHTTP");}
],
createXMLHTTPObject: function() {
var xmlhttp = false;
var factories = XHR.XMLHttpFactories;
var i;
var numFactories = factories.length;
for (i = 0; i < numFactories; i++) {
try {
xmlhttp = factories[i]();
break;
} catch (e) {
// pass
}
}
return xmlhttp;
},
post: function(url, accessToken, payload, callback) {
if (typeof payload !== 'object') {
throw new Error('Expected an object to POST');
}
payload = RollbarJSON.stringify(payload);
callback = callback || function() {};
var request = XHR.createXMLHTTPObject();
if (request) {
try {
try {
var onreadystatechange = function(args) {
try {
if (onreadystatechange && request.readyState === 4) {
onreadystatechange = undefined;
// TODO(cory): have the notifier log an internal error on non-200 response codes
if (request.status === 200) {
callback(null, RollbarJSON.parse(request.responseText));
} else if (typeof(request.status) === "number" &&
request.status >= 400 && request.status < 600) {
// return valid http status codes
callback(new Error(request.status.toString()));
} else {
// IE will return a status 12000+ on some sort of connection failure,
// so we return a blank error
// http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx
callback(new Error());
}
}
} catch (ex) {
//jquery source mentions firefox may error out while accessing the
//request members if there is a network error
//https://github.com/jquery/jquery/blob/a938d7b1282fc0e5c52502c225ae8f0cef219f0a/src/ajax/xhr.js#L111
var exc;
if (typeof ex === 'object' && ex.stack) {
exc = ex;
} else {
exc = new Error(ex);
}
callback(exc);
}
};
request.open('POST', url, true);
if (request.setRequestHeader) {
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('X-Rollbar-Access-Token', accessToken);
}
request.onreadystatechange = onreadystatechange;
request.send(payload);
} catch (e1) {
// Sending using the normal xmlhttprequest object didn't work, try XDomainRequest
if (typeof XDomainRequest !== "undefined") {
var ontimeout = function(args) {
callback(new Error());
};
var onerror = function(args) {
callback(new Error());
};
var onload = function(args) {
callback(null, RollbarJSON.parse(request.responseText));
};
request = new XDomainRequest();
request.onprogress = function() {};
request.ontimeout = ontimeout;
request.onerror = onerror;
request.onload = onload;
request.open('POST', url, true);
request.send(payload);
}
}
} catch (e2) {
callback(e2);
}
}
}
};
// Updated by the build process to match package.json
Notifier.NOTIFIER_VERSION = '1.0.1';
Notifier.DEFAULT_ENDPOINT = 'api.rollbar.com/api/1/';
Notifier.DEFAULT_SCRUB_FIELDS = ["passwd","password","secret","confirm_password","password_confirmation"];
Notifier.DEFAULT_LOG_LEVEL = 'debug';
Notifier.DEFAULT_REPORT_LEVEL = 'debug';
Notifier.DEFAULT_UNCAUGHT_ERROR_LEVEL = 'warning';
Notifier.DEFAULT_ITEMS_PER_MIN = 60;
Notifier.DEFAULT_MAX_ITEMS = 0;
Notifier.LEVELS = {
debug: 0,
info: 1,
warning: 2,
error: 3,
critical: 4
};
// This is the global queue where all notifiers will put their
// payloads to be sent to Rollbar.
window._rollbarPayloadQueue = [];
// This contains global options for all Rollbar notifiers.
window._globalRollbarOptions = {
startTime: (new Date()).getTime(),
maxItems: Notifier.DEFAULT_MAX_ITEMS,
itemsPerMinute: Notifier.DEFAULT_ITEMS_PER_MIN
};
var TK = computeStackTraceWrapper({remoteFetching: false, linesOfContext: 3});
var _topLevelNotifier;
function Notifier(parentNotifier) {
// Save the first notifier so we can use it to send system messages like
// when the rate limit is reached.
_topLevelNotifier = _topLevelNotifier || this;
var protocol = window.location.protocol;
if (protocol.indexOf('http') !== 0) {
protocol = 'https:';
}
var endpoint = protocol + '//' + Notifier.DEFAULT_ENDPOINT;
this.options = {
endpoint: endpoint,
environment: 'production',
scrubFields: Util.copy(Notifier.DEFAULT_SCRUB_FIELDS),
checkIgnore: null,
logLevel: Notifier.DEFAULT_LOG_LEVEL,
reportLevel: Notifier.DEFAULT_REPORT_LEVEL,
uncaughtErrorLevel: Notifier.DEFAULT_UNCAUGHT_ERROR_LEVEL,
payload: {}
};
this.lastError = null;
this.plugins = {};
this.parentNotifier = parentNotifier;
this.logger = function() {
if (window.console && window.console.log) {
var args = ['Rollbar internal error:'].concat(Array.prototype.slice.call(arguments, 0));
window.console.log(args);
}
};
if (parentNotifier) {
// If the parent notifier has the shimId
// property it means that it's a Rollbar shim.
if (parentNotifier.hasOwnProperty('shimId')) {
// After we set this, the shim is just a proxy to this
// Notifier instance.
parentNotifier.notifier = this;
} else {
this.logger = parentNotifier.logger;
this.configure(parentNotifier.options);
}
}
}
Notifier._generateLogFn = function(level) {
return _wrapNotifierFn(function _logFn() {
var args = this._getLogArgs(arguments);
return this._log(level || args.level || this.options.logLevel || Notifier.DEFAULT_LOG_LEVEL,
args.message, args.err, args.custom, args.callback);
});
};
/*
* Returns an Object with keys:
* {
* message: String,
* err: Error,
* custom: Object
* }
*/
Notifier.prototype._getLogArgs = function(args) {
var level = this.options.logLevel || Notifier.DEFAULT_LOG_LEVEL;
var ts;
var message;
var err;
var custom;
var callback;
var argT;
var arg;
for (var i = 0; i < args.length; ++i) {
arg = args[i];
argT = typeof arg;
if (argT === 'string') {
message = arg;
} else if (argT === 'function') {
callback = _wrapNotifierFn(arg, this); // wrap the callback in a try/catch block
} else if (arg && argT === 'object') {
if (arg.constructor.name === 'Date') {
ts = arg;
} else if (arg instanceof Error || arg.prototype === Error.prototype || arg.hasOwnProperty('stack')) {
err = arg;
} else {
custom = arg;
}
}
}
// TODO(cory): somehow pass in timestamp too...
return {
level: level,
message: message,
err: err,
custom: custom,
callback: callback
};
};
Notifier.prototype._route = function(path) {
var endpoint = this.options.endpoint;
var endpointTrailingSlash = /\/$/.test(endpoint);
var pathBeginningSlash = /^\//.test(path);
if (endpointTrailingSlash && pathBeginningSlash) {
path = path.substring(1);
} else if (!endpointTrailingSlash && !pathBeginningSlash) {
path = '/' + path;
}
return endpoint + path;
};
/*
* Given a queue containing each call to the shim, call the
* corresponding method on this instance.
*
* shim queue contains:
*
* {shim: Rollbar, method: 'info', args: ['hello world', exc], ts: Date}
*/
Notifier.prototype._processShimQueue = function(shimQueue) {
// implement me
var shim;
var obj;
var tmp;
var method;
var args;
var shimToNotifier = {};
var parentShim;
var parentNotifier;
var notifier;
// For each of the messages in the shimQueue we need to:
// 1. get/create the notifier for that shim
// 2. apply the message to the notifier
while ((obj = shimQueue.shift())) {
shim = obj.shim;
method = obj.method;
args = obj.args;
parentShim = shim.parentShim;
// Get the current notifier based on the shimId
notifier = shimToNotifier[shim.shimId];
if (!notifier) {
// If there is no notifier associated with the shimId
// Check to see if there's a parent shim
if (parentShim) {
// If there is a parent shim, get the parent notifier
// and create a new notifier for the current shim.
parentNotifier = shimToNotifier[parentShim.shimId];
// Create a new Notifier which will process all of the shim's
// messages
notifier = new Notifier(parentNotifier);
} else {
// If there is no parent, assume the shim is the top
// level shim and thus, should use this as the notifier.
notifier = this;
}
// Save off the shimId->notifier mapping
shimToNotifier[shim.shimId] = notifier;
}
if (notifier[method] && typeof notifier[method] === 'function') {
notifier[method].apply(notifier, args);
}
}
};
/*
* Builds and returns an Object that will be enqueued onto the
* window._rollbarPayloadQueue array to be sent to Rollbar.
*/
Notifier.prototype._buildPayload = function(ts, level, message, stackInfo, custom) {
var accessToken = this.options.accessToken;
// NOTE(cory): DEPRECATED
// Pass in {payload: {environment: 'production'}} instead of just {environment: 'production'}
var environment = this.options.environment;
var notifierOptions = Util.copy(this.options.payload);
var uuid = Util.uuid4();
if (Notifier.LEVELS[level] === undefined) {
throw new Error('Invalid level');
}
if (!message && !stackInfo && !custom) {
throw new Error('No message, stack info or custom data');
}
var payloadData = {
environment: environment,
endpoint: this.options.endpoint,
uuid: uuid,
level: level,
platform: 'browser',
framework: 'browser-js',
language: 'javascript',
body: this._buildBody(message, stackInfo, custom),
request: {
url: window.location.href,
query_string: window.location.search,
user_ip: "$remote_ip"
},
client: {
runtime_ms: ts.getTime() - window._globalRollbarOptions.startTime,
timestamp: Math.round(ts.getTime() / 1000),
javascript: {
browser: window.navigator.userAgent,
language: window.navigator.language,
cookie_enabled: window.navigator.cookieEnabled,
screen: {
width: window.screen.width,
height: window.screen.height
},
plugins: this._getBrowserPlugins()
}
},
server: {},
notifier: {
name: 'rollbar-browser-js',
version: Notifier.NOTIFIER_VERSION
}
};
if (notifierOptions.body) {
delete notifierOptions.body;
}
// Overwrite the options from configure() with the payload
// data.
var payload = {
access_token: accessToken,
data: Util.merge(payloadData, notifierOptions)
};
// Only scrub the data section since we never want to scrub "access_token"
// even if it's in the scrub fields
this._scrub(payload.data);
return payload;
};
Notifier.prototype._buildBody = function(message, stackInfo, custom) {
var body;
if (stackInfo && stackInfo.mode !== 'failed') {
body = this._buildPayloadBodyTrace(message, stackInfo, custom);
} else {
body = this._buildPayloadBodyMessage(message, custom);
}
return body;
};
Notifier.prototype._buildPayloadBodyMessage = function(message, custom) {
if (!message) {
if (custom) {
message = RollbarJSON.stringify(custom);
} else {
message = '';
}
}
var result = {
body: message
};
if (custom) {
result.extra = Util.copy(custom);
}
return {
message: result
};
};
Notifier.prototype._buildPayloadBodyTrace = function(description, stackInfo, custom) {
var guess = _guessErrorClass(stackInfo.message);
var className = stackInfo.name || guess[0];
var message = guess[1];
var trace = {
exception: {
'class': className,
message: message
}
};
if (description) {
trace.exception.description = description || 'uncaught exception';
}
// Transform a TraceKit stackInfo object into a Rollbar trace
if (stackInfo.stack) {
var stackFrame;
var frame;
var code;
var pre;
var post;
var contextLength;
var i, j, mid;
trace.frames = [];
for (i = 0; i < stackInfo.stack.length; ++i) {
stackFrame = stackInfo.stack[i];
frame = {
filename: stackFrame.url ? Util.sanitizeUrl(stackFrame.url) : '(unknown)',
lineno: stackFrame.line || null,
method: (!stackFrame.func || stackFrame.func === '?') ? '[anonymous]' : stackFrame.func,
colno: stackFrame.column
};
code = pre = post = null;
contextLength = stackFrame.context ? stackFrame.context.length : 0;
if (contextLength) {
mid = Math.floor(contextLength / 2);
pre = stackFrame.context.slice(0, mid);
code = stackFrame.context[mid];
post = stackFrame.context.slice(mid);
}
if (code) {
frame.code = code;
}
if (pre || post) {
frame.context = {};
if (pre && pre.length) {
frame.context.pre = pre;
}
if (post && post.length) {
frame.context.post = post;
}
}
if (stackFrame.args) {
frame.args = stackFrame.args;
}
trace.frames.push(frame);
}
if (custom) {
trace.extra = Util.copy(custom);
}
return {trace: trace};
} else {
// no frames - not useful as a trace. just report as a message.
return this._buildPayloadBodyMessage(className + ': ' + message, custom);
}
};
Notifier.prototype._getBrowserPlugins = function() {
if (!this._browserPlugins) {
var navPlugins = (window.navigator.plugins || []);
var cur;
var numPlugins = navPlugins.length;
var plugins = [];
var i;
for (i = 0; i < numPlugins; ++i) {
cur = navPlugins[i];
plugins.push({name: cur.name, description: cur.description});
}
this._browserPlugins = plugins;
}
return this._browserPlugins;
};
/*
* Does an in-place modification of obj such that:
* 1. All keys that match the notifier's options.scrubFields
* list will be normalized into all '*'
* 2. Any query string params that match the same criteria will have
* their values normalized as well.
*/
Notifier.prototype._scrub = function(obj) {
function redactQueryParam(match, paramPart, dummy1,
dummy2, dummy3, valPart, offset, string) {
return paramPart + Util.redact(valPart);
}
function paramScrubber(v) {
var i;
if (typeof(v) === 'string') {
for (i = 0; i < queryRes.length; ++i) {
v = v.replace(queryRes[i], redactQueryParam);
}
}
return v;
}
function valScrubber(k, v) {
var i;
for (i = 0; i < paramRes.length; ++i) {
if (paramRes[i].test(k)) {
v = Util.redact(v);
break;
}
}
return v;
}
function scrubber(k, v) {
var tmpV = valScrubber(k, v);
if (tmpV === v) {
return paramScrubber(tmpV);
} else {
return tmpV;
}
}
var scrubFields = this.options.scrubFields;
var paramRes = this._getScrubFieldRegexs(scrubFields);
var queryRes = this._getScrubQueryParamRegexs(scrubFields);
Util.traverse(obj, scrubber);
return obj;
};
Notifier.prototype._getScrubFieldRegexs = function(scrubFields) {
var ret = [];
var pat;
for (var i = 0; i < scrubFields.length; ++i) {
pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?';
ret.push(new RegExp(pat, 'i'));
}
return ret;
};
Notifier.prototype._getScrubQueryParamRegexs = function(scrubFields) {
var ret = [];
var pat;
for (var i = 0; i < scrubFields.length; ++i) {
pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?';
ret.push(new RegExp('(' + pat + '=)([^&\\n]+)', 'igm'));
}
return ret;
};
Notifier.prototype._urlIsWhitelisted = function(payload){
var whitelist, trace, frame, filename, frameLength, url, listLength, urlRegex;
var i, j;
try {
whitelist = this.options.hostWhiteList;
trace = payload.data.body.trace;
if (!whitelist || whitelist.length === 0) { return true; }
if (!trace) { return true; }
listLength = whitelist.length;
frameLength = trace.frames.length;
for (i = 0; i < frameLength; i++) {
frame = trace.frames[i];
filename = frame.filename;
if (typeof filename !== "string") { return true; }
for (j = 0; j < listLength; j++) {
url = whitelist[j];
urlRegex = new RegExp(url);
if (urlRegex.test(filename)){
return true;
}
}
}
} catch (e) {
this.configure({hostWhiteList: null});
this.error("Error while reading your configuration's hostWhiteList option. Removing custom hostWhiteList.", e);
return true;
}
return false;
};
Notifier.prototype._enqueuePayload = function(payload, isUncaught, callerArgs, callback) {
var ignoredCallback = function() {
if (callback) {
// If the item was ignored call the callback anyway
var msg = 'This item was not sent to Rollbar because it was ignored. ' +
'This can happen if a custom checkIgnore() function was used ' +
'or if the item\'s level was less than the notifier\' reportLevel. ' +
'See https://rollbar.com/docs/notifier/rollbar.js/configuration for more details.';
callback(null, {err: 0, result: {id: null, uuid: null, message: msg}});
}
};
// Internal checkIgnore will check the level against the minimum
// report level from this.options
if (this._internalCheckIgnore(isUncaught, callerArgs, payload)) {
ignoredCallback();
return;
}
// Users can set their own ignore criteria using this.options.checkIgnore()
try {
if (this.options.checkIgnore &&
typeof this.options.checkIgnore === 'function' &&
this.options.checkIgnore(isUncaught, callerArgs, payload)) {
ignoredCallback();
return;
}
} catch (e) {
// Disable the custom checkIgnore and report errors in the checkIgnore function
this.configure({checkIgnore: null});
this.error('Error while calling custom checkIgnore() function. Removing custom checkIgnore().', e);
}
if(!this._urlIsWhitelisted(payload)) {
return;
}
window._rollbarPayloadQueue.push({
callback: callback,
accessToken: this.options.accessToken,
endpointUrl: this._route('item/'),
payload: payload
});
};
Notifier.prototype._internalCheckIgnore = function(isUncaught, callerArgs, payload) {
var level = callerArgs[0];
var levelVal = Notifier.LEVELS[level] || 0;
var reportLevel = Notifier.LEVELS[this.options.reportLevel] || 0;
if (levelVal < reportLevel) {
return true;
}
var plugins = this.options ? this.options.plugins : {};
if (plugins && plugins.jquery && plugins.jquery.ignoreAjaxErrors &&
payload.body.message) {
return payload.body.messagejquery_ajax_error;
}
return false;
};
/*
* Logs stuff to Rollbar using the default
* logging level.
*
* Can be called with the following, (order doesn't matter but type does):
* - message: String
* - err: Error object, must have a .stack property or it will be
* treated as custom data
* - custom: Object containing custom data to be sent along with
* the item
* - callback: Function to call once the item is reported to Rollbar
* - isUncaught: True if this error originated from an uncaught exception handler
* - ignoreRateLimit: True if this item should be allowed despite rate limit checks
*/
Notifier.prototype._log = function(level, message, err, custom, callback, isUncaught, ignoreRateLimit) {
var stackInfo = null;
if (err) {
// If we've already calculated the stack trace for the error, use it.
// This can happen for wrapped errors that don't have a "stack" property.
stackInfo = err._tkStackTrace ? err._tkStackTrace : TK(err);
// Don't report the same error more than once
if (err === this.lastError) {
return;
}
this.lastError = err;
}
var payload = this._buildPayload(new Date(), level, message, stackInfo, custom);
if (ignoreRateLimit) {
payload.ignoreRateLimit = true;
}
this._enqueuePayload(payload, isUncaught ? true : false, [level, message, err, custom], callback);
};
Notifier.prototype.log = Notifier._generateLogFn();
Notifier.prototype.debug = Notifier._generateLogFn('debug');
Notifier.prototype.info = Notifier._generateLogFn('info');
Notifier.prototype.warn = Notifier._generateLogFn('warning'); // for console.warn() compatibility
Notifier.prototype.warning = Notifier._generateLogFn('warning');
Notifier.prototype.error = Notifier._generateLogFn('error');
Notifier.prototype.critical = Notifier._generateLogFn('critical');
// Adapted from tracekit.js
Notifier.prototype.uncaughtError = _wrapNotifierFn(function(message, url, lineNo, colNo, err) {
if (err && err.stack) {
this._log(this.options.uncaughtErrorLevel, message, err, null, null, true);
return;
}
// NOTE(cory): sometimes users will trigger an "error" event
// on the window object directly which will result in errMsg
// being an Object instead of a string.
//
if (url && url.stack) {
this._log(this.options.uncaughtErrorLevel, message, url, null, null, true);
return;
}
var location = {
'url': url || '',
'line': lineNo
};
location.func = TK.guessFunctionName(location.url, location.line);
location.context = TK.gatherContext(location.url, location.line);
var stack = {
'mode': 'onerror',
'message': message || 'uncaught exception',
'url': document.location.href,
'stack': [location],
'useragent': navigator.userAgent
};
if (err) {
stack = err._tkStackTrace || TK(err);
}
var payload = this._buildPayload(new Date(), this.options.uncaughtErrorLevel, message, stack);
this._enqueuePayload(payload, true, [this.options.uncaughtErrorLevel, message, url, lineNo, colNo, err]);
});
Notifier.prototype.global = _wrapNotifierFn(function(options) {
options = options || {};
Util.merge(window._globalRollbarOptions, options);
if (options.maxItems !== undefined) {
rateLimitCounter = 0;
}
if (options.itemsPerMinute !== undefined) {
rateLimitPerMinCounter = 0;
}
});
Notifier.prototype.configure = _wrapNotifierFn(function(options) {
// TODO(cory): only allow non-payload keys that we understand
// Make a copy of the options object for this notifier
Util.merge(this.options, options);
});
/*
* Create a new Notifier instance which has the same options
* as the current notifier + options to override them.
*/
Notifier.prototype.scope = _wrapNotifierFn(function(payloadOptions) {
var scopedNotifier = new Notifier(this);
Util.merge(scopedNotifier.options.payload, payloadOptions);
return scopedNotifier;
});
Notifier.prototype.wrap = function(f) {
var _this = this;
if (typeof f !== 'function') {
return f;
}
// If the given function is already a wrapped function, just
// return it instead of wrapping twice
if (f._isWrap) {
return f;
}
if (!f._wrapped) {
f._wrapped = function () {
try {
f.apply(this, arguments);
} catch(e) {
if (!e.stack) {
e._tkStackTrace = TK(e);
}
window._rollbarWrappedError = e;
throw e;
}
};
f._wrapped._isWrap = true;
for (var prop in f) {
if (f.hasOwnProperty(prop)) {
f._wrapped[prop] = f[prop];
}
}
}
return f._wrapped;
};
/***** Misc *****/
function _wrapNotifierFn(fn, ctx) {
return function() {
var self = ctx || this;
try {
return fn.apply(self, arguments);
} catch (e) {
if (self) {
self.logger(e);
}
}
};
}
var ERR_CLASS_REGEXP = new RegExp('^(([a-zA-Z0-9-_$ ]*): *)?(Uncaught )?([a-zA-Z0-9-_$ ]*): ');
function _guessErrorClass(errMsg) {
if (!errMsg) {
return ["Unknown error. There was no error message to display.", ""];
}
var errClassMatch = errMsg.match(ERR_CLASS_REGEXP);
var errClass = '(unknown)';
if (errClassMatch) {
errClass = errClassMatch[errClassMatch.length - 1];
errMsg = errMsg.replace((errClassMatch[errClassMatch.length - 2] || '') + errClass + ':', '');
errMsg = errMsg.replace(/(^[\s]+|[\s]+$)/g, '');
}
return [errClass, errMsg];
}
/***** Payload processor *****/
var payloadProcessorTimeout;
Notifier.processPayloads = function(immediate) {
if (!payloadProcessorTimeout || immediate) {
_payloadProcessorTimer(immediate);
}
};
function _payloadProcessorTimer(immediate) {
var payloadObj;
while ((payloadObj = window._rollbarPayloadQueue.shift())) {
_processPayload(payloadObj.endpointUrl, payloadObj.accessToken, payloadObj.payload, payloadObj.callback);
}
if (!immediate) {
payloadProcessorTimeout = setTimeout(_payloadProcessorTimer, 1000);
}
}
var rateLimitStartTime = new Date().getTime();
var rateLimitCounter = 0;
var rateLimitPerMinCounter = 0;
function _processPayload(url, accessToken, payload, callback) {
callback = callback || function cb() {};
var now = new Date().getTime();
if (now - rateLimitStartTime >= 60000) {
rateLimitStartTime = now;
rateLimitPerMinCounter = 0;
}
// Check to see if we have a rate limit set or if
// the rate limit has been met/exceeded.
var globalRateLimit = window._globalRollbarOptions.maxItems;
var globalRateLimitPerMin = window._globalRollbarOptions.itemsPerMinute;
var checkOverRateLimit = function() { return !payload.ignoreRateLimit && globalRateLimit >= 1 && rateLimitCounter >= globalRateLimit; };
var checkOverRateLimitPerMin = function() { return !payload.ignoreRateLimit && globalRateLimitPerMin >= 1 && rateLimitPerMinCounter >= globalRateLimitPerMin; };
if (checkOverRateLimit()) {
callback(new Error(globalRateLimit + ' max items reached'));
return;
} else if (checkOverRateLimitPerMin()) {
callback(new Error(globalRateLimitPerMin + ' items per minute reached'));
return;
} else {
rateLimitCounter++;
rateLimitPerMinCounter++;
// Check to see if we have just reached the rate limit. If so, notify the customer.
if (checkOverRateLimit()) {
_topLevelNotifier._log(_topLevelNotifier.options.uncaughtErrorLevel, //level
'maxItems has been hit. Ignoring errors for the remainder of the current page load.', // message
null, // err
{maxItems: globalRateLimit}, // custom
null, // callback
false, // isUncaught
true); // ignoreRateLimit
}
// remove this key since it's only used for internal notifier logic
if (payload.ignoreRateLimit) {
delete payload.ignoreRateLimit;
}
}
// There's either no rate limit or we haven't met it yet so
// go ahead and send it.
XHR.post(url, accessToken, payload, function xhrCallback(err, resp) {
if (err) {
return callback(err);
}
// TODO(cory): parse resp as JSON
return callback(null, resp);
});
}
// Create the global notifier
var globalNotifier = new Notifier();
// Stub out the wrapped error which is set
window._rollbarWrappedError = null;
// Global window.onerror handler
function _rollbarWindowOnError(client, old, args) {
if (!args[4] && window._rollbarWrappedError) {
args[4] = window._rollbarWrappedError;
window._rollbarWrappedError = null;
}
globalNotifier.uncaughtError.apply(globalNotifier, args);
if (old) {
old.apply(window, args);
}
}
function _extendListenerPrototype(client, prototype) {
if (prototype.hasOwnProperty && prototype.hasOwnProperty('addEventListener')) {
var oldAddEventListener = prototype.addEventListener;
prototype.addEventListener = function(event, callback, bubble) {
oldAddEventListener.call(this, event, client.wrap(callback), bubble);
};
var oldRemoveEventListener = prototype.removeEventListener;
prototype.removeEventListener = function(event, callback, bubble) {
oldRemoveEventListener.call(this, event, callback._wrapped || callback, bubble);
};
}
}
// Add an init() method to do the same things that the shim would do
globalNotifier.init = function(config) {
this.configure(config);
if (config.captureUncaught) {
// Set the global onerror handler
var old = window.onerror;
window.onerror = function() {
var args = Array.prototype.slice.call(arguments, 0);
_rollbarWindowOnError(globalNotifier, old, args);
};
// Adapted from https://github.com/bugsnag/bugsnag-js
var globals = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource',
'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController',
'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue',
'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget',
'XMLHttpRequestUpload'];
var i;
var global;
for (i = 0; i < globals.length; ++i) {
global = globals[i];
if (window[global] && window[global].prototype) {
_extendListenerPrototype(this, window[global].prototype);
}
}
}
// Finally, start processing payloads using the global notifier
Notifier.processPayloads();
};
module.exports = globalNotifier;
|
(function($) {
$.extend($.summernote.lang, {
'da-DK': {
font: {
bold: 'Fed',
italic: 'Kursiv',
underline: 'Understreget',
clear: 'Fjern formatering',
height: 'Højde',
name: 'Skrifttype',
strikethrough: 'Gennemstreget',
subscript: 'Sænket skrift',
superscript: 'Hævet skrift',
size: 'Skriftstørrelse'
},
image: {
image: 'Billede',
insert: 'Indsæt billede',
resizeFull: 'Original størrelse',
resizeHalf: 'Halv størrelse',
resizeQuarter: 'Kvart størrelse',
floatLeft: 'Venstrestillet',
floatRight: 'Højrestillet',
floatNone: 'Fjern formatering',
shapeRounded: 'Form: Runde kanter',
shapeCircle: 'Form: Cirkel',
shapeThumbnail: 'Form: Miniature',
shapeNone: 'Form: Ingen',
dragImageHere: 'Træk billede hertil',
dropImage: 'Slip billede',
selectFromFiles: 'Vælg billed-fil',
maximumFileSize: 'Maks fil størrelse',
maximumFileSizeError: 'Filen er større end maks tilladte fil størrelse!',
url: 'Billede URL',
remove: 'Fjern billede',
original: 'Original'
},
video: {
video: 'Video',
videoLink: 'Video Link',
insert: 'Indsæt Video',
url: 'Video URL?',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion eller Youku)'
},
link: {
link: 'Link',
insert: 'Indsæt link',
unlink: 'Fjern link',
edit: 'Rediger',
textToDisplay: 'Visningstekst',
url: 'Hvor skal linket pege hen?',
openInNewWindow: 'Åbn i nyt vindue'
},
table: {
table: 'Tabel',
addRowAbove: 'Add row above',
addRowBelow: 'Add row below',
addColLeft: 'Add column left',
addColRight: 'Add column right',
delRow: 'Delete row',
delCol: 'Delete column',
delTable: 'Delete table'
},
hr: {
insert: 'Indsæt horisontal linje'
},
style: {
style: 'Stil',
p: 'p',
blockquote: 'Citat',
pre: 'Kode',
h1: 'Overskrift 1',
h2: 'Overskrift 2',
h3: 'Overskrift 3',
h4: 'Overskrift 4',
h5: 'Overskrift 5',
h6: 'Overskrift 6'
},
lists: {
unordered: 'Punktopstillet liste',
ordered: 'Nummereret liste'
},
options: {
help: 'Hjælp',
fullscreen: 'Fuld skærm',
codeview: 'HTML-Visning'
},
paragraph: {
paragraph: 'Afsnit',
outdent: 'Formindsk indryk',
indent: 'Forøg indryk',
left: 'Venstrestillet',
center: 'Centreret',
right: 'Højrestillet',
justify: 'Blokjuster'
},
color: {
recent: 'Nyligt valgt farve',
more: 'Flere farver',
background: 'Baggrund',
foreground: 'Forgrund',
transparent: 'Transparent',
setTransparent: 'Sæt transparent',
reset: 'Nulstil',
resetToDefault: 'Gendan standardindstillinger'
},
shortcut: {
shortcuts: 'Genveje',
close: 'Luk',
textFormatting: 'Tekstformatering',
action: 'Handling',
paragraphFormatting: 'Afsnitsformatering',
documentStyle: 'Dokumentstil',
extraKeys: 'Extra keys'
},
help: {
'insertParagraph': 'Insert Paragraph',
'undo': 'Undoes the last command',
'redo': 'Redoes the last command',
'tab': 'Tab',
'untab': 'Untab',
'bold': 'Set a bold style',
'italic': 'Set a italic style',
'underline': 'Set a underline style',
'strikethrough': 'Set a strikethrough style',
'removeFormat': 'Clean a style',
'justifyLeft': 'Set left align',
'justifyCenter': 'Set center align',
'justifyRight': 'Set right align',
'justifyFull': 'Set full align',
'insertUnorderedList': 'Toggle unordered list',
'insertOrderedList': 'Toggle ordered list',
'outdent': 'Outdent on current paragraph',
'indent': 'Indent on current paragraph',
'formatPara': 'Change current block\'s format as a paragraph(P tag)',
'formatH1': 'Change current block\'s format as H1',
'formatH2': 'Change current block\'s format as H2',
'formatH3': 'Change current block\'s format as H3',
'formatH4': 'Change current block\'s format as H4',
'formatH5': 'Change current block\'s format as H5',
'formatH6': 'Change current block\'s format as H6',
'insertHorizontalRule': 'Insert horizontal rule',
'linkDialog.show': 'Show Link Dialog'
},
history: {
undo: 'Fortryd',
redo: 'Annuller fortryd'
},
specialChar: {
specialChar: 'SPECIAL CHARACTERS',
select: 'Select Special characters'
}
}
});
})(jQuery);
|
on('change:repeating_sites:site_details_button', function(eventinfo) {
if (eventinfo.newValue == 'on') {
setAttrs({
repeating_sites_site_details: eventinfo.newValue,
repeating_sites_site_theme_domain: 'off',
repeating_sites_site_theme_domain_button: 'off'
});
} else {
setAttrs({
repeating_sites_site_details: eventinfo.newValue,
});
}
});
on('change:repeating_sites:site_theme_domain_button', function(eventinfo) {
if (eventinfo.newValue == 'on') {
setAttrs({
repeating_sites_site_theme_domain: eventinfo.newValue,
repeating_sites_site_details: 'off',
repeating_sites_site_details_button: 'off'
});
} else {
setAttrs({
repeating_sites_site_theme_domain: eventinfo.newValue,
});
}
});
on('change:repeating_sites:theme_select', function(eventinfo) {
setAttrs({
repeating_sites_theme: eventinfo.newValue,
});
});
on('change:repeating_sites:domain_select', function(eventinfo) {
setAttrs({
repeating_sites_domain: eventinfo.newValue,
});
});
|
import React from 'react';
import getRelatedIconClass from '../utils/getRelatedIconClass';
class Section extends React.Component {
render () {
const iconClass = this.props.icon || getRelatedIconClass(this.props.id);
return (
<div className="dashboard-group" data-section-label={this.props.label}>
<div className="dashboard-group__heading">
<span className={`dashboard-group__heading-icon ${iconClass}`} />
{this.props.label}
</div>
{this.props.children}
</div>
);
}
}
Section.propTypes = {
children: React.PropTypes.element.isRequired,
icon: React.PropTypes.string,
id: React.PropTypes.string,
label: React.PropTypes.string.isRequired,
};
export default Section;
|
// dropped
// not used in grappelli
// kept this file to prevent 404
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Operators/Regular/Main.js
*
* Copyright (c) 2013-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['AsanaMathJax_Operators'] = {
directory: 'Operators/Regular',
family: 'AsanaMathJax_Operators',
testString: '\u2206\u220A\u220C\u220E\u220F\u2210\u2211\u221B\u221C\u221F\u222C\u222D\u222E\u222F\u2230',
0x20: [0,0,249,0,0],
0x2206: [697,4,688,27,662],
0x220A: [482,3,511,66,446],
0x220C: [648,107,563,55,509],
0x220E: [406,0,508,52,457],
0x220F: [626,311,994,54,941],
0x2210: [626,311,994,54,941],
0x2211: [620,310,850,62,788],
0x221B: [1048,59,739,63,772],
0x221C: [1045,59,739,63,771],
0x221F: [368,0,498,65,434],
0x222C: [885,442,1132,54,1058],
0x222D: [885,442,1496,54,1422],
0x222E: [885,442,768,54,694],
0x222F: [885,442,1132,54,1058],
0x2230: [885,442,1496,54,1422],
0x2231: [885,442,787,54,713],
0x2232: [885,442,787,54,713],
0x2233: [885,442,787,54,713],
0x2236: [518,-23,249,66,184],
0x2237: [518,-23,570,76,495],
0x2238: [538,-286,668,65,604],
0x2239: [518,-23,890,65,806],
0x223A: [518,-23,668,65,604],
0x223B: [518,-23,668,58,610],
0x223E: [422,-123,729,32,706],
0x223F: [587,3,784,34,750],
0x2244: [596,55,668,65,604],
0x2247: [596,55,668,65,604],
0x2249: [596,55,668,58,611],
0x224B: [614,-14,668,53,614],
0x224C: [587,-134,668,58,610],
0x2254: [518,-23,890,85,826],
0x2255: [518,-23,890,65,806],
0x2258: [587,-134,668,62,604],
0x2259: [646,-134,687,65,623],
0x225A: [646,-134,687,65,623],
0x225B: [652,-134,687,65,623],
0x225D: [658,-134,687,65,623],
0x225E: [632,-134,687,65,623],
0x225F: [751,-134,687,65,623],
0x2262: [596,55,668,65,604],
0x2263: [566,27,668,65,604],
0x226D: [596,55,668,54,616],
0x2274: [712,171,668,65,604],
0x2275: [712,171,668,65,604],
0x2278: [712,171,668,65,604],
0x2279: [712,171,668,65,604],
0x2284: [648,107,668,55,615],
0x2285: [648,107,668,55,615],
0x228C: [603,0,687,65,623],
0x228D: [603,0,687,65,623],
0x229C: [587,46,668,18,652],
0x22A6: [541,0,490,65,425],
0x22A7: [620,-1,709,85,624],
0x22AB: [541,0,748,64,684],
0x22B0: [652,118,748,75,673],
0x22B1: [652,118,748,75,674],
0x22B6: [446,-94,1363,65,1299],
0x22B7: [446,-94,1363,65,1299],
0x22B9: [505,-5,687,96,598],
0x22BD: [620,78,687,65,623],
0x22BE: [410,0,535,63,473],
0x22BF: [368,0,498,65,434],
0x22C0: [626,313,897,86,813],
0x22C1: [626,313,897,86,813],
0x22C2: [626,313,897,86,812],
0x22C3: [626,313,897,86,812],
0x22C7: [547,5,668,59,611],
0x22D5: [714,177,641,65,604],
0x22DC: [615,74,668,65,604],
0x22DD: [615,74,668,65,604],
0x22E2: [712,171,668,55,615],
0x22E3: [712,171,668,55,615],
0x22E4: [602,114,668,55,615],
0x22E5: [602,114,668,55,615],
0x22F0: [570,14,774,95,680],
0x22F2: [580,-22,876,53,824],
0x22F3: [533,-8,563,55,509],
0x22F4: [482,3,511,66,478],
0x22F5: [618,79,563,55,509],
0x22F6: [597,55,563,55,509],
0x22F7: [583,42,511,66,446],
0x22F8: [597,55,563,55,509],
0x22F9: [533,-8,563,55,509],
0x22FA: [580,-22,876,53,824],
0x22FB: [533,-8,563,55,509],
0x22FC: [482,3,511,66,478],
0x22FD: [597,55,563,55,509],
0x22FE: [583,42,511,66,446],
0x22FF: [697,0,617,46,572],
0x2A00: [830,316,1320,86,1235],
0x2A01: [833,316,1320,86,1235],
0x2A02: [833,316,1320,86,1235],
0x2A03: [741,198,897,86,812],
0x2A04: [741,198,897,86,812],
0x2A05: [734,192,897,86,812],
0x2A06: [734,192,897,86,812],
0x2A07: [626,313,1035,86,950],
0x2A08: [626,313,1035,86,950],
0x2A09: [734,192,1098,86,1013],
0x2A0A: [882,434,1158,60,1069],
0x2A0B: [885,442,850,27,764],
0x2A0C: [885,442,1860,54,1786],
0x2A0D: [885,442,768,54,694],
0x2A0E: [885,442,768,54,694],
0x2A0F: [885,442,768,54,694],
0x2A10: [885,442,768,54,694],
0x2A11: [885,442,810,54,736],
0x2A12: [885,442,768,54,694],
0x2A13: [885,442,768,54,694],
0x2A14: [885,442,768,54,694],
0x2A15: [885,442,768,54,694],
0x2A16: [885,442,768,54,694],
0x2A17: [885,442,1005,52,936],
0x2A18: [885,442,768,54,694],
0x2A19: [885,442,768,54,694],
0x2A1A: [885,442,768,54,694],
0x2A1B: [994,442,775,54,701],
0x2A1C: [994,442,775,54,701],
0x2A1D: [515,-23,758,65,694],
0x2A1E: [535,-6,668,65,604],
0x2A1F: [703,355,552,16,521],
0x2A20: [556,10,826,48,770],
0x2A21: [714,171,524,233,478],
0x2A22: [672,129,668,65,604],
0x2A23: [609,68,668,65,604],
0x2A24: [631,88,668,65,604],
0x2A25: [538,180,668,65,604],
0x2A26: [538,178,668,65,604],
0x2A27: [538,95,668,65,604],
0x2A28: [538,0,668,65,604],
0x2A29: [570,-233,605,51,555],
0x2A2A: [289,-74,605,51,555],
0x2A2B: [492,-30,605,51,555],
0x2A2C: [492,-30,605,51,555],
0x2A2D: [587,52,602,26,571],
0x2A2E: [587,52,602,26,571],
0x2A2F: [489,-53,554,59,496],
0x2A30: [688,5,668,59,611],
0x2A31: [545,142,668,59,611],
0x2A32: [547,5,760,58,702],
0x2A33: [554,11,671,53,619],
0x2A34: [587,52,603,54,550],
0x2A35: [587,52,603,54,550],
0x2A36: [634,192,668,18,652],
0x2A37: [587,46,668,18,652],
0x2A38: [587,46,668,18,652],
0x2A39: [559,18,666,44,623],
0x2A3A: [559,18,666,44,623],
0x2A3B: [559,18,666,44,623],
0x2A3C: [360,-88,672,65,608],
0x2A3D: [360,-88,672,65,608],
0x2A3E: [703,166,396,54,344],
0x2A40: [573,30,687,65,623],
0x2A41: [573,30,687,65,623],
0x2A42: [634,91,687,65,623],
0x2A43: [634,91,687,65,623],
0x2A44: [578,25,687,65,623],
0x2A45: [578,25,687,65,623],
0x2A46: [622,80,407,64,344],
0x2A47: [622,80,407,64,344],
0x2A48: [622,80,407,64,344],
0x2A49: [622,80,407,64,344],
0x2A4A: [422,-120,659,64,596],
0x2A4B: [422,-120,659,64,596],
0x2A4C: [601,58,779,64,716],
0x2A4D: [601,58,779,64,716],
0x2A4E: [559,17,687,65,623],
0x2A4F: [559,17,687,65,623],
0x2A50: [601,58,779,64,716],
0x2A51: [570,29,537,57,481],
0x2A52: [570,29,537,57,481],
0x2A53: [563,22,687,65,623],
0x2A54: [563,22,687,65,623],
0x2A55: [563,22,836,65,772],
0x2A56: [563,22,836,65,772],
0x2A57: [598,42,670,66,605],
0x2A58: [598,41,669,66,604],
0x2A59: [621,79,687,65,623],
0x2A5A: [563,22,687,65,623],
0x2A5B: [563,22,687,65,623],
0x2A5C: [563,22,687,65,623],
0x2A5D: [563,22,687,65,623],
0x2A5F: [720,27,687,65,623],
0x2A60: [640,267,687,65,623],
0x2A61: [497,-45,687,65,623],
0x2A62: [636,262,687,65,623],
0x2A63: [645,262,687,65,623],
0x2A64: [535,-6,668,65,604],
0x2A65: [535,-6,668,65,604],
0x2A66: [445,19,668,65,604],
0x2A67: [571,29,668,65,604],
0x2A68: [540,0,668,65,604],
0x2A69: [540,0,668,65,604],
0x2A6A: [429,-113,668,58,611],
0x2A6B: [500,-41,668,58,611],
0x2A6C: [514,-14,668,56,614],
0x2A6D: [581,39,668,65,604],
0x2A6E: [530,-12,668,65,604],
0x2A6F: [649,-51,668,58,611],
0x2A70: [596,55,668,65,604],
0x2A71: [667,126,668,66,604],
0x2A72: [667,126,668,66,604],
0x2A73: [507,-35,668,65,604],
0x2A74: [518,-23,1092,85,1028],
0x2A75: [406,-134,1347,85,1263],
0x2A76: [406,-134,1986,85,1902],
0x2A77: [599,58,668,65,604],
0x2A78: [567,25,668,65,604],
0x2A79: [535,-5,668,65,604],
0x2A7A: [535,-5,668,65,604],
0x2A7B: [623,82,668,65,604],
0x2A7C: [623,82,668,65,604],
0x2A7F: [615,74,668,65,604],
0x2A80: [615,74,668,65,604],
0x2A81: [615,74,668,65,604],
0x2A82: [615,74,668,65,604],
0x2A83: [700,159,668,65,604],
0x2A84: [700,159,668,65,604],
0x2A8D: [672,186,668,65,604],
0x2A8E: [672,186,668,65,604],
0x2A8F: [821,279,668,65,604],
0x2A90: [821,279,668,65,604],
0x2A91: [755,159,668,65,604],
0x2A92: [755,159,668,65,604],
0x2A93: [944,279,668,65,604],
0x2A94: [944,279,668,65,604],
0x2A97: [615,74,668,65,604],
0x2A98: [615,74,668,65,604],
0x2A99: [672,131,668,65,604],
0x2A9A: [672,131,668,65,604],
0x2A9B: [701,147,668,66,605],
0x2A9C: [701,147,668,66,605],
0x2A9D: [605,122,668,65,604],
0x2A9E: [605,122,668,65,604],
0x2A9F: [801,193,668,65,604],
0x2AA0: [801,193,668,65,604],
0x2AA1: [535,-5,668,65,604],
0x2AA2: [535,-5,668,65,604],
0x2AA3: [606,61,965,55,912],
0x2AA4: [535,-5,768,56,713],
0x2AA5: [535,-5,1251,55,1198],
0x2AA6: [535,-7,725,64,661],
0x2AA7: [535,-7,725,64,662],
0x2AA8: [613,74,725,64,661],
0x2AA9: [613,74,725,64,662],
0x2AAA: [553,5,713,65,649],
0x2AAB: [553,5,713,65,649],
0x2AAC: [635,61,713,65,649],
0x2AAD: [635,61,713,65,649],
0x2AAE: [550,8,668,65,604],
0x2AB1: [623,134,668,65,604],
0x2AB2: [623,134,668,65,604],
0x2AB3: [680,139,668,65,604],
0x2AB4: [680,139,668,65,604],
0x2ABB: [553,14,1057,65,993],
0x2ABC: [553,14,1057,65,993],
0x2ABD: [533,-8,668,55,615],
0x2ABE: [533,-8,668,55,615],
0x2ABF: [588,46,465,65,401],
0x2AC0: [588,46,465,65,401],
0x2AC1: [623,81,465,65,401],
0x2AC2: [623,81,465,65,401],
0x2AC3: [645,103,607,65,543],
0x2AC4: [645,103,607,65,543],
0x2AC7: [656,115,668,55,615],
0x2AC8: [656,115,668,55,615],
0x2AC9: [739,227,668,55,615],
0x2ACA: [739,227,668,55,615],
0x2ACD: [543,-2,1145,64,1082],
0x2ACE: [543,-2,1145,64,1082],
0x2ACF: [533,-8,668,55,615],
0x2AD0: [533,-8,668,55,615],
0x2AD1: [603,61,668,55,615],
0x2AD2: [603,61,668,55,615],
0x2AD3: [611,69,407,53,355],
0x2AD4: [611,69,407,53,355],
0x2AD5: [611,69,407,53,355],
0x2AD6: [611,69,407,53,355],
0x2AD7: [410,-130,764,53,711],
0x2AD8: [410,-130,764,53,711],
0x2AD9: [498,-44,613,45,569],
0x2ADA: [656,115,687,65,623],
0x2ADB: [771,150,687,65,623],
0x2ADC: [648,107,687,65,623],
0x2ADD: [571,31,687,65,623],
0x2ADE: [541,0,400,65,337],
0x2ADF: [408,-136,670,65,607],
0x2AE0: [408,-136,670,65,607],
0x2AE1: [579,0,748,65,684],
0x2AE2: [580,39,748,85,664],
0x2AE3: [580,39,859,85,795],
0x2AE4: [580,39,728,85,664],
0x2AE5: [580,39,859,85,795],
0x2AE6: [580,39,730,87,666],
0x2AE7: [473,-70,670,65,607],
0x2AE8: [473,-70,670,65,607],
0x2AE9: [579,37,670,65,607],
0x2AEA: [559,20,748,65,684],
0x2AEB: [559,20,748,65,684],
0x2AEC: [407,-135,672,65,608],
0x2AED: [407,-135,672,65,608],
0x2AEE: [714,171,437,0,438],
0x2AEF: [715,173,521,85,437],
0x2AF0: [714,174,521,85,437],
0x2AF1: [714,174,560,65,496],
0x2AF2: [714,171,644,70,575],
0x2AF3: [714,171,668,58,611],
0x2AF4: [714,171,560,61,500],
0x2AF5: [714,171,691,65,627],
0x2AF6: [709,164,286,85,202],
0x2AF7: [535,-7,668,65,604],
0x2AF8: [535,-7,668,65,604],
0x2AF9: [695,153,668,66,605],
0x2AFA: [695,153,668,66,605],
0x2AFB: [714,169,885,65,821],
0x2AFC: [763,222,620,71,550],
0x2AFD: [714,169,673,65,609],
0x2AFE: [541,0,383,64,320],
0x2AFF: [654,112,383,64,320]
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Operators"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Operators/Regular/Main.js"]
);
|
var EventEmitter = require('events').EventEmitter
var next = process.nextTick
var SubDb = require('./sub')
var Batch = require('./batch')
var fixRange = require('level-fix-range')
var Hooks = require('level-hooks')
module.exports = function (_db, options) {
function DB () {}
DB.prototype = _db
var db = new DB()
if (db.sublevel) return db
options = options || {}
//use \xff (255) as the seperator,
//so that sections of the database will sort after the regular keys
var sep = options.sep = options.sep || '\xff'
db._options = options
Hooks(db)
db.sublevels = {}
db.sublevel = function (prefix, options) {
if(db.sublevels[prefix])
return db.sublevels[prefix]
return new SubDb(db, prefix, options || this._options)
}
db.methods = {}
db.prefix = function (key) {
return '' + (key || '')
}
db.pre = function (range, hook) {
if(!hook)
hook = range, range = {
max : sep
}
return db.hooks.pre(range, hook)
}
db.post = function (range, hook) {
if(!hook)
hook = range, range = {
max : sep
}
return db.hooks.post(range, hook)
}
function safeRange(fun) {
return function (opts) {
opts = opts || {}
opts = fixRange(opts)
if(opts.reverse) opts.start = opts.start || sep
else opts.end = opts.end || sep
return fun.call(db, opts)
}
}
db.readStream =
db.createReadStream = safeRange(db.createReadStream)
db.keyStream =
db.createKeyStream = safeRange(db.createKeyStream)
db.valuesStream =
db.createValueStream = safeRange(db.createValueStream)
var batch = db.batch
db.batch = function (changes, opts, cb) {
if(!Array.isArray(changes))
return new Batch(db)
changes.forEach(function (e) {
if(e.prefix) {
if('function' === typeof e.prefix.prefix)
e.key = e.prefix.prefix(e.key)
else if('string' === typeof e.prefix)
e.key = e.prefix + e.key
}
})
batch.call(db, changes, opts, cb)
}
return db
}
|
'single quotes';
|
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
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 <COPYRIGHT HOLDER> 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.
*/
import { Syntax } from 'estraverse';
import esrecurse from 'esrecurse';
import Reference from './reference';
import Variable from './variable';
import PatternVisitor from './pattern-visitor';
import { ParameterDefinition, Definition } from './definition';
import assert from 'assert';
function traverseIdentifierInPattern(rootPattern, referencer, callback) {
// Call the callback at left hand identifier nodes, and Collect right hand nodes.
var visitor = new PatternVisitor(rootPattern, callback);
visitor.visit(rootPattern);
// Process the right hand nodes recursively.
if (referencer != null) {
visitor.rightHandNodes.forEach(referencer.visit, referencer);
}
}
// Importing ImportDeclaration.
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
// https://github.com/estree/estree/blob/master/es6.md#importdeclaration
// FIXME: Now, we don't create module environment, because the context is
// implementation dependent.
class Importer extends esrecurse.Visitor {
constructor(declaration, referencer) {
super();
this.declaration = declaration;
this.referencer = referencer;
}
visitImport(id, specifier) {
this.referencer.visitPattern(id, (pattern) => {
this.referencer.currentScope().__define(pattern,
new Definition(
Variable.ImportBinding,
pattern,
specifier,
this.declaration,
null,
null
));
});
}
ImportNamespaceSpecifier(node) {
let local = (node.local || node.id);
if (local) {
this.visitImport(local, node);
}
}
ImportDefaultSpecifier(node) {
let local = (node.local || node.id);
this.visitImport(local, node);
}
ImportSpecifier(node) {
let local = (node.local || node.id);
if (node.name) {
this.visitImport(node.name, node);
} else {
this.visitImport(local, node);
}
}
}
// Referencing variables and creating bindings.
export default class Referencer extends esrecurse.Visitor {
constructor(scopeManager) {
super();
this.scopeManager = scopeManager;
this.parent = null;
this.isInnerMethodDefinition = false;
}
currentScope() {
return this.scopeManager.__currentScope;
}
close(node) {
while (this.currentScope() && node === this.currentScope().block) {
this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);
}
}
pushInnerMethodDefinition(isInnerMethodDefinition) {
var previous = this.isInnerMethodDefinition;
this.isInnerMethodDefinition = isInnerMethodDefinition;
return previous;
}
popInnerMethodDefinition(isInnerMethodDefinition) {
this.isInnerMethodDefinition = isInnerMethodDefinition;
}
materializeTDZScope(node, iterationNode) {
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation
// TDZ scope hides the declaration's names.
this.scopeManager.__nestTDZScope(node, iterationNode);
this.visitVariableDeclaration(this.currentScope(), Variable.TDZ, iterationNode.left, 0, true);
}
materializeIterationScope(node) {
// Generate iteration scope for upper ForIn/ForOf Statements.
var letOrConstDecl;
this.scopeManager.__nestForScope(node);
letOrConstDecl = node.left;
this.visitVariableDeclaration(this.currentScope(), Variable.Variable, letOrConstDecl, 0);
this.visitPattern(letOrConstDecl.declarations[0].id, (pattern) => {
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);
});
}
referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
const scope = this.currentScope();
assignments.forEach(assignment => {
scope.__referencing(
pattern,
Reference.WRITE,
assignment.right,
maybeImplicitGlobal,
pattern !== assignment.left,
init);
});
}
visitPattern(node, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {processRightHandNodes: false}
}
traverseIdentifierInPattern(
node,
options.processRightHandNodes ? this : null,
callback);
}
visitFunction(node) {
var i, iz;
// FunctionDeclaration name is defined in upper scope
// NOTE: Not referring variableScope. It is intended.
// Since
// in ES5, FunctionDeclaration should be in FunctionBody.
// in ES6, FunctionDeclaration should be block scoped.
if (node.type === Syntax.FunctionDeclaration) {
// id is defined in upper scope
this.currentScope().__define(node.id,
new Definition(
Variable.FunctionName,
node.id,
node,
null,
null,
null
));
}
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
if (node.type === Syntax.FunctionExpression && node.id) {
this.scopeManager.__nestFunctionExpressionNameScope(node);
}
// Consider this function is in the MethodDefinition.
this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);
// Process parameter declarations.
for (i = 0, iz = node.params.length; i < iz; ++i) {
this.visitPattern(node.params[i], {processRightHandNodes: true}, (pattern, info) => {
this.currentScope().__define(pattern,
new ParameterDefinition(
pattern,
node,
i,
info.rest
));
this.referencingDefaultValue(pattern, info.assignments, null, true);
});
}
// if there's a rest argument, add that
if (node.rest) {
this.visitPattern({
type: 'RestElement',
argument: node.rest
}, (pattern) => {
this.currentScope().__define(pattern,
new ParameterDefinition(
pattern,
node,
node.params.length,
true
));
});
}
// Skip BlockStatement to prevent creating BlockStatement scope.
if (node.body.type === Syntax.BlockStatement) {
this.visitChildren(node.body);
} else {
this.visit(node.body);
}
this.close(node);
}
visitClass(node) {
if (node.type === Syntax.ClassDeclaration) {
this.currentScope().__define(node.id,
new Definition(
Variable.ClassName,
node.id,
node,
null,
null,
null
));
}
// FIXME: Maybe consider TDZ.
this.visit(node.superClass);
this.scopeManager.__nestClassScope(node);
if (node.id) {
this.currentScope().__define(node.id,
new Definition(
Variable.ClassName,
node.id,
node
));
}
this.visit(node.body);
this.close(node);
}
visitProperty(node) {
var previous, isMethodDefinition;
if (node.computed) {
this.visit(node.key);
}
isMethodDefinition = node.type === Syntax.MethodDefinition;
if (isMethodDefinition) {
previous = this.pushInnerMethodDefinition(true);
}
this.visit(node.value);
if (isMethodDefinition) {
this.popInnerMethodDefinition(previous);
}
}
visitForIn(node) {
if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== 'var') {
this.materializeTDZScope(node.right, node);
this.visit(node.right);
this.close(node.right);
this.materializeIterationScope(node);
this.visit(node.body);
this.close(node);
} else {
if (node.left.type === Syntax.VariableDeclaration) {
this.visit(node.left);
this.visitPattern(node.left.declarations[0].id, (pattern) => {
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);
});
} else {
this.visitPattern(node.left, {processRightHandNodes: true}, (pattern, info) => {
var maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern: pattern,
node: node
};
}
this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false);
});
}
this.visit(node.right);
this.visit(node.body);
}
}
visitVariableDeclaration(variableTargetScope, type, node, index, fromTDZ) {
// If this was called to initialize a TDZ scope, this needs to make definitions, but doesn't make references.
var decl, init;
decl = node.declarations[index];
init = decl.init;
this.visitPattern(decl.id, {processRightHandNodes: !fromTDZ}, (pattern, info) => {
variableTargetScope.__define(pattern,
new Definition(
type,
pattern,
decl,
node,
index,
node.kind
));
if (!fromTDZ) {
this.referencingDefaultValue(pattern, info.assignments, null, true);
}
if (init) {
this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true);
}
});
}
AssignmentExpression(node) {
if (PatternVisitor.isPattern(node.left)) {
if (node.operator === '=') {
this.visitPattern(node.left, {processRightHandNodes: true}, (pattern, info) => {
var maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern: pattern,
node: node
};
}
this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);
});
} else {
this.currentScope().__referencing(node.left, Reference.RW, node.right);
}
} else {
this.visit(node.left);
}
this.visit(node.right);
}
CatchClause(node) {
this.scopeManager.__nestCatchScope(node);
this.visitPattern(node.param, {processRightHandNodes: true}, (pattern, info) => {
this.currentScope().__define(pattern,
new Definition(
Variable.CatchClause,
node.param,
node,
null,
null,
null
));
this.referencingDefaultValue(pattern, info.assignments, null, true);
});
this.visit(node.body);
this.close(node);
}
Program(node) {
this.scopeManager.__nestGlobalScope(node);
if (this.scopeManager.__isNodejsScope()) {
// Force strictness of GlobalScope to false when using node.js scope.
this.currentScope().isStrict = false;
this.scopeManager.__nestFunctionScope(node, false);
}
if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
this.scopeManager.__nestModuleScope(node);
}
this.visitChildren(node);
this.close(node);
}
Identifier(node) {
this.currentScope().__referencing(node);
}
UpdateExpression(node) {
if (PatternVisitor.isPattern(node.argument)) {
this.currentScope().__referencing(node.argument, Reference.RW, null);
} else {
this.visitChildren(node);
}
}
MemberExpression(node) {
this.visit(node.object);
if (node.computed) {
this.visit(node.property);
}
}
Property(node) {
this.visitProperty(node);
}
MethodDefinition(node) {
this.visitProperty(node);
}
BreakStatement() {}
ContinueStatement() {}
LabeledStatement(node) {
this.visit(node.body);
}
ForStatement(node) {
// Create ForStatement declaration.
// NOTE: In ES6, ForStatement dynamically generates
// per iteration environment. However, escope is
// a static analyzer, we only generate one scope for ForStatement.
if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== 'var') {
this.scopeManager.__nestForScope(node);
}
this.visitChildren(node);
this.close(node);
}
ClassExpression(node) {
this.visitClass(node);
}
ClassDeclaration(node) {
this.visitClass(node);
}
CallExpression(node) {
// Check this is direct call to eval
if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') {
// NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
// let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
this.currentScope().variableScope.__detectEval();
}
this.visitChildren(node);
}
BlockStatement(node) {
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestBlockScope(node);
}
this.visitChildren(node);
this.close(node);
}
ThisExpression() {
this.currentScope().variableScope.__detectThis();
}
WithStatement(node) {
this.visit(node.object);
// Then nest scope for WithStatement.
this.scopeManager.__nestWithScope(node);
this.visit(node.body);
this.close(node);
}
VariableDeclaration(node) {
var variableTargetScope, i, iz, decl;
variableTargetScope = (node.kind === 'var') ? this.currentScope().variableScope : this.currentScope();
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
decl = node.declarations[i];
this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i);
if (decl.init) {
this.visit(decl.init);
}
}
}
// sec 13.11.8
SwitchStatement(node) {
var i, iz;
this.visit(node.discriminant);
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestSwitchScope(node);
}
for (i = 0, iz = node.cases.length; i < iz; ++i) {
this.visit(node.cases[i]);
}
this.close(node);
}
FunctionDeclaration(node) {
this.visitFunction(node);
}
FunctionExpression(node) {
this.visitFunction(node);
}
ForOfStatement(node) {
this.visitForIn(node);
}
ForInStatement(node) {
this.visitForIn(node);
}
ArrowFunctionExpression(node) {
this.visitFunction(node);
}
ImportDeclaration(node) {
var importer;
assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), 'ImportDeclaration should appear when the mode is ES6 and in the module context.');
importer = new Importer(node, this);
importer.visit(node);
}
visitExportDeclaration(node) {
if (node.source) {
return;
}
if (node.declaration) {
this.visit(node.declaration);
return;
}
this.visitChildren(node);
}
ExportDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportNamedDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportSpecifier(node) {
let local = (node.id || node.local);
this.visit(local);
}
}
/* vim: set sw=4 ts=4 et tw=80 : */
|
(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.mobx = 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){
(function (global){
"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 __());
};
registerGlobals();
exports.extras = {
allowStateChanges: allowStateChanges,
getAtom: getAtom,
getDebugName: getDebugName,
getDependencyTree: getDependencyTree,
getObserverTree: getObserverTree,
isComputingDerivation: isComputingDerivation,
isSpyEnabled: isSpyEnabled,
resetGlobalState: resetGlobalState,
spyReport: spyReport,
spyReportEnd: spyReportEnd,
spyReportStart: spyReportStart,
trackTransitions: trackTransitions
};
exports._ = {
getAdministration: getAdministration,
resetGlobalState: resetGlobalState
};
var actionFieldDecorator = createClassPropertyDecorator(function (target, key, value, args, originalDescriptor) {
var actionName = (args && args.length === 1) ? args[0] : (value.name || key || "<unnamed action>");
var wrappedAction = action(actionName, value);
addHiddenProp(target, key, wrappedAction);
}, function (key) {
return this[key];
}, function () {
invariant(false, "It is not allowed to assign new values to @action fields");
}, false, true);
function action(arg1, arg2, arg3, arg4) {
if (arguments.length === 1 && typeof arg1 === "function")
return createAction(arg1.name || "<unnamed action>", arg1);
if (arguments.length === 2 && typeof arg2 === "function")
return createAction(arg1, arg2);
if (arguments.length === 1 && typeof arg1 === "string")
return namedActionDecorator(arg1);
return namedActionDecorator(arg2).apply(null, arguments);
}
exports.action = action;
function namedActionDecorator(name) {
return function (target, prop, descriptor) {
if (descriptor && typeof descriptor.value === "function") {
descriptor.value = createAction(name, descriptor.value);
descriptor.enumerable = false;
descriptor.configurable = true;
return descriptor;
}
return actionFieldDecorator(name).apply(this, arguments);
};
}
function runInAction(arg1, arg2, arg3) {
var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>";
var fn = typeof arg1 === "function" ? arg1 : arg2;
var scope = typeof arg1 === "function" ? arg2 : arg3;
invariant(typeof fn === "function", "`runInAction` expects a function");
invariant(fn.length === 0, "`runInAction` expects a function without arguments");
invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'");
return executeAction(actionName, fn, scope, undefined);
}
exports.runInAction = runInAction;
function isAction(thing) {
return typeof thing === "function" && thing.isMobxAction === true;
}
exports.isAction = isAction;
function autorun(arg1, arg2, arg3) {
var name, view, scope;
if (typeof arg1 === "string") {
name = arg1;
view = arg2;
scope = arg3;
}
else if (typeof arg1 === "function") {
name = arg1.name || ("Autorun@" + getNextId());
view = arg1;
scope = arg2;
}
assertUnwrapped(view, "autorun methods cannot have modifiers");
invariant(typeof view === "function", "autorun expects a function");
if (scope)
view = view.bind(scope);
var reaction = new Reaction(name, function () {
this.track(reactionRunner);
});
function reactionRunner() {
view(reaction);
}
reaction.schedule();
return reaction.getDisposer();
}
exports.autorun = autorun;
function when(arg1, arg2, arg3, arg4) {
var name, predicate, effect, scope;
if (typeof arg1 === "string") {
name = arg1;
predicate = arg2;
effect = arg3;
scope = arg4;
}
else if (typeof arg1 === "function") {
name = ("When@" + getNextId());
predicate = arg1;
effect = arg2;
scope = arg3;
}
var disposer = autorun(name, function (r) {
if (predicate.call(scope)) {
r.dispose();
var prevUntracked = untrackedStart();
effect.call(scope);
untrackedEnd(prevUntracked);
}
});
return disposer;
}
exports.when = when;
function autorunUntil(predicate, effect, scope) {
deprecated("`autorunUntil` is deprecated, please use `when`.");
return when.apply(null, arguments);
}
exports.autorunUntil = autorunUntil;
function autorunAsync(arg1, arg2, arg3, arg4) {
var name, func, delay, scope;
if (typeof arg1 === "string") {
name = arg1;
func = arg2;
delay = arg3;
scope = arg4;
}
else if (typeof arg1 === "function") {
name = arg1.name || ("AutorunAsync@" + getNextId());
func = arg1;
delay = arg2;
scope = arg3;
}
if (delay === void 0)
delay = 1;
if (scope)
func = func.bind(scope);
var isScheduled = false;
var r = new Reaction(name, function () {
if (!isScheduled) {
isScheduled = true;
setTimeout(function () {
isScheduled = false;
if (!r.isDisposed)
r.track(reactionRunner);
}, delay);
}
});
function reactionRunner() { func(r); }
r.schedule();
return r.getDisposer();
}
exports.autorunAsync = autorunAsync;
function reaction(arg1, arg2, arg3, arg4, arg5, arg6) {
var name, expression, effect, fireImmediately, delay, scope;
if (typeof arg1 === "string") {
name = arg1;
expression = arg2;
effect = arg3;
fireImmediately = arg4;
delay = arg5;
scope = arg6;
}
else {
name = arg1.name || arg2.name || ("Reaction@" + getNextId());
expression = arg1;
effect = arg2;
fireImmediately = arg3;
delay = arg4;
scope = arg5;
}
if (fireImmediately === void 0)
fireImmediately = false;
if (delay === void 0)
delay = 0;
var _a = getValueModeFromValue(expression, ValueMode.Reference), valueMode = _a[0], unwrappedExpression = _a[1];
var compareStructural = valueMode === ValueMode.Structure;
if (scope) {
unwrappedExpression = unwrappedExpression.bind(scope);
effect = action(name, effect.bind(scope));
}
var firstTime = true;
var isScheduled = false;
var nextValue = undefined;
var r = new Reaction(name, function () {
if (delay < 1) {
reactionRunner();
}
else if (!isScheduled) {
isScheduled = true;
setTimeout(function () {
isScheduled = false;
reactionRunner();
}, delay);
}
});
function reactionRunner() {
if (r.isDisposed)
return;
var changed = false;
r.track(function () {
var v = unwrappedExpression(r);
changed = valueDidChange(compareStructural, nextValue, v);
nextValue = v;
});
if (firstTime && fireImmediately)
effect(nextValue, r);
if (!firstTime && changed === true)
effect(nextValue, r);
if (firstTime)
firstTime = false;
}
r.schedule();
return r.getDisposer();
}
exports.reaction = reaction;
var computedDecorator = createClassPropertyDecorator(function (target, name, _, decoratorArgs, originalDescriptor) {
invariant(typeof originalDescriptor !== "undefined", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property.");
var baseValue = originalDescriptor.get;
invariant(typeof baseValue === "function", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");
var compareStructural = false;
if (decoratorArgs && decoratorArgs.length === 1 && decoratorArgs[0].asStructure === true)
compareStructural = true;
var adm = asObservableObject(target, undefined, ValueMode.Recursive);
defineObservableProperty(adm, name, compareStructural ? asStructure(baseValue) : baseValue, false);
}, function (name) {
return this.$mobx.values[name].get();
}, throwingComputedValueSetter, false, true);
function computed(targetOrExpr, keyOrScope, baseDescriptor, options) {
if (arguments.length < 3 && typeof targetOrExpr === "function")
return computedExpr(targetOrExpr, keyOrScope);
invariant(!baseDescriptor || !baseDescriptor.set, "@observable properties cannot have a setter: " + keyOrScope);
return computedDecorator.apply(null, arguments);
}
exports.computed = computed;
function computedExpr(expr, scope) {
var _a = getValueModeFromValue(expr, ValueMode.Recursive), mode = _a[0], value = _a[1];
return new ComputedValue(value, scope, mode === ValueMode.Structure, value.name);
}
function throwingComputedValueSetter() {
throw new Error("[ComputedValue] It is not allowed to assign new values to computed properties.");
}
function createTransformer(transformer, onCleanup) {
invariant(typeof transformer === "function" && transformer.length === 1, "createTransformer expects a function that accepts one argument");
var objectCache = {};
var resetId = globalState.resetId;
var Transformer = (function (_super) {
__extends(Transformer, _super);
function Transformer(sourceIdentifier, sourceObject) {
_super.call(this, function () { return transformer(sourceObject); }, null, false, "Transformer-" + transformer.name + "-" + sourceIdentifier);
this.sourceIdentifier = sourceIdentifier;
this.sourceObject = sourceObject;
}
Transformer.prototype.onBecomeUnobserved = function () {
var lastValue = this.value;
_super.prototype.onBecomeUnobserved.call(this);
delete objectCache[this.sourceIdentifier];
if (onCleanup)
onCleanup(lastValue, this.sourceObject);
};
return Transformer;
}(ComputedValue));
return function (object) {
if (resetId !== globalState.resetId) {
objectCache = {};
resetId = globalState.resetId;
}
var identifier = getMemoizationId(object);
var reactiveTransformer = objectCache[identifier];
if (reactiveTransformer)
return reactiveTransformer.get();
reactiveTransformer = objectCache[identifier] = new Transformer(identifier, object);
return reactiveTransformer.get();
};
}
exports.createTransformer = createTransformer;
function getMemoizationId(object) {
if (object === null || typeof object !== "object")
throw new Error("[mobx] transform expected some kind of object, got: " + object);
var tid = object.$transformId;
if (tid === undefined) {
tid = getNextId();
addHiddenProp(object, "$transformId", tid);
}
return tid;
}
function expr(expr, scope) {
if (!isComputingDerivation())
console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions.");
return computed(expr, scope).get();
}
exports.expr = expr;
function extendObservable(target) {
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments[_i];
}
invariant(arguments.length >= 2, "extendObservable expected 2 or more arguments");
invariant(typeof target === "object", "extendObservable expects an object as first argument");
invariant(!(target instanceof ObservableMap), "extendObservable should not be used on maps, use map.merge instead");
properties.forEach(function (propSet) {
invariant(typeof propSet === "object", "all arguments of extendObservable should be objects");
extendObservableHelper(target, propSet, ValueMode.Recursive, null);
});
return target;
}
exports.extendObservable = extendObservable;
function extendObservableHelper(target, properties, mode, name) {
var adm = asObservableObject(target, name, mode);
for (var key in properties)
if (properties.hasOwnProperty(key)) {
if (target === properties && !isPropertyConfigurable(target, key))
continue;
setObservableObjectInstanceProperty(adm, key, properties[key]);
}
return target;
}
function getDependencyTree(thing, property) {
return nodeToDependencyTree(getAtom(thing, property));
}
function nodeToDependencyTree(node) {
var result = {
name: node.name
};
if (node.observing && node.observing.length > 0)
result.dependencies = unique(node.observing).map(nodeToDependencyTree);
return result;
}
function getObserverTree(thing, property) {
return nodeToObserverTree(getAtom(thing, property));
}
function nodeToObserverTree(node) {
var result = {
name: node.name
};
if (node.observers && node.observers.length > 0)
result.observers = node.observers.asArray().map(nodeToObserverTree);
return result;
}
function intercept(thing, propOrHandler, handler) {
if (typeof handler === "function")
return interceptProperty(thing, propOrHandler, handler);
else
return interceptInterceptable(thing, propOrHandler);
}
exports.intercept = intercept;
function interceptInterceptable(thing, handler) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
return getAdministration(observable(thing)).intercept(handler);
}
return getAdministration(thing).intercept(handler);
}
function interceptProperty(thing, property, handler) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
extendObservable(thing, {
property: thing[property]
});
return interceptProperty(thing, property, handler);
}
return getAdministration(thing, property).intercept(handler);
}
function isObservable(value, property) {
if (value === null || value === undefined)
return false;
if (property !== undefined) {
if (value instanceof ObservableMap || value instanceof ObservableArray)
throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");
else if (isObservableObject(value)) {
var o = value.$mobx;
return o.values && !!o.values[property];
}
return false;
}
return !!value.$mobx || value instanceof BaseAtom || value instanceof Reaction || value instanceof ComputedValue;
}
exports.isObservable = isObservable;
var decoratorImpl = createClassPropertyDecorator(function (target, name, baseValue) {
var prevA = allowStateChangesStart(true);
if (typeof baseValue === "function")
baseValue = asReference(baseValue);
var adm = asObservableObject(target, undefined, ValueMode.Recursive);
defineObservableProperty(adm, name, baseValue, true);
allowStateChangesEnd(prevA);
}, function (name) {
return this.$mobx.values[name].get();
}, function (name, value) {
setPropertyValue(this, name, value);
}, true, false);
function observableDecorator(target, key, baseDescriptor) {
invariant(arguments.length >= 2 && arguments.length <= 3, "Illegal decorator config", key);
assertPropertyConfigurable(target, key);
invariant(!baseDescriptor || !baseDescriptor.get, "@observable can not be used on getters, use @computed instead");
return decoratorImpl.apply(null, arguments);
}
function observable(v, keyOrScope) {
if (v === void 0) { v = undefined; }
if (typeof arguments[1] === "string")
return observableDecorator.apply(null, arguments);
invariant(arguments.length < 3, "observable expects zero, one or two arguments");
if (isObservable(v))
return v;
var _a = getValueModeFromValue(v, ValueMode.Recursive), mode = _a[0], value = _a[1];
var sourceType = mode === ValueMode.Reference ? ValueType.Reference : getTypeOfValue(value);
switch (sourceType) {
case ValueType.Array:
case ValueType.PlainObject:
return makeChildObservable(value, mode);
case ValueType.Reference:
case ValueType.ComplexObject:
return new ObservableValue(value, mode);
case ValueType.ComplexFunction:
throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");
case ValueType.ViewFunction:
deprecated("Use `computed(expr)` instead of `observable(expr)`");
return computed(v, keyOrScope);
}
invariant(false, "Illegal State");
}
exports.observable = observable;
var ValueType;
(function (ValueType) {
ValueType[ValueType["Reference"] = 0] = "Reference";
ValueType[ValueType["PlainObject"] = 1] = "PlainObject";
ValueType[ValueType["ComplexObject"] = 2] = "ComplexObject";
ValueType[ValueType["Array"] = 3] = "Array";
ValueType[ValueType["ViewFunction"] = 4] = "ViewFunction";
ValueType[ValueType["ComplexFunction"] = 5] = "ComplexFunction";
})(ValueType || (ValueType = {}));
function getTypeOfValue(value) {
if (value === null || value === undefined)
return ValueType.Reference;
if (typeof value === "function")
return value.length ? ValueType.ComplexFunction : ValueType.ViewFunction;
if (Array.isArray(value) || value instanceof ObservableArray)
return ValueType.Array;
if (typeof value === "object")
return isPlainObject(value) ? ValueType.PlainObject : ValueType.ComplexObject;
return ValueType.Reference;
}
function observe(thing, propOrCb, cbOrFire, fireImmediately) {
if (typeof cbOrFire === "function")
return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);
else
return observeObservable(thing, propOrCb, cbOrFire);
}
exports.observe = observe;
function observeObservable(thing, listener, fireImmediately) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
return getAdministration(observable(thing)).observe(listener, fireImmediately);
}
return getAdministration(thing).observe(listener, fireImmediately);
}
function observeObservableProperty(thing, property, listener, fireImmediately) {
if (isPlainObject(thing) && !isObservableObject(thing)) {
deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0");
extendObservable(thing, {
property: thing[property]
});
return observeObservableProperty(thing, property, listener, fireImmediately);
}
return getAdministration(thing, property).observe(listener, fireImmediately);
}
function toJS(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
function cache(value) {
if (detectCycles)
__alreadySeen.push([source, value]);
return value;
}
if (source instanceof Date || source instanceof RegExp)
return source;
if (detectCycles && __alreadySeen === null)
__alreadySeen = [];
if (detectCycles && source !== null && typeof source === "object") {
for (var i = 0, l = __alreadySeen.length; i < l; i++)
if (__alreadySeen[i][0] === source)
return __alreadySeen[i][1];
}
if (!source)
return source;
if (Array.isArray(source) || source instanceof ObservableArray) {
var res = cache([]);
var toAdd = source.map(function (value) { return toJS(value, detectCycles, __alreadySeen); });
res.length = toAdd.length;
for (var i = 0, l = toAdd.length; i < l; i++)
res[i] = toAdd[i];
return res;
}
if (source instanceof ObservableMap) {
var res_1 = cache({});
source.forEach(function (value, key) { return res_1[key] = toJS(value, detectCycles, __alreadySeen); });
return res_1;
}
if (isObservable(source) && source.$mobx instanceof ObservableValue)
return toJS(source(), detectCycles, __alreadySeen);
if (source instanceof ObservableValue)
return toJS(source.get(), detectCycles, __alreadySeen);
if (typeof source === "object") {
var res = cache({});
for (var key in source)
res[key] = toJS(source[key], detectCycles, __alreadySeen);
return res;
}
return source;
}
exports.toJS = toJS;
function toJSON(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
deprecated("toJSON is deprecated. Use toJS instead");
return toJS.apply(null, arguments);
}
exports.toJSON = toJSON;
function log(msg) {
console.log(msg);
return msg;
}
function whyRun(thing, prop) {
switch (arguments.length) {
case 0:
thing = globalState.derivationStack[globalState.derivationStack.length - 1];
if (!thing)
return log("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value.");
break;
case 2:
thing = getAtom(thing, prop);
break;
}
thing = getAtom(thing);
if (thing instanceof ComputedValue)
return log(thing.whyRun());
else if (thing instanceof Reaction)
return log(thing.whyRun());
else
invariant(false, "whyRun can only be used on reactions and computed values");
}
exports.whyRun = whyRun;
function createAction(actionName, fn) {
invariant(typeof fn === "function", "`action` can only be invoked on functions");
invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'");
var res = function () {
return executeAction(actionName, fn, this, arguments);
};
res.isMobxAction = true;
return res;
}
function executeAction(actionName, fn, scope, args) {
var ds = globalState.derivationStack;
invariant(!(ds[ds.length - 1] instanceof ComputedValue), "Computed values or transformers should not invoke actions or trigger other side effects");
var notifySpy = isSpyEnabled();
var startTime;
if (notifySpy) {
startTime = Date.now();
var l = (args && args.length) || 0;
var flattendArgs = new Array(l);
if (l > 0)
for (var i = 0; i < l; i++)
flattendArgs[i] = args[i];
spyReportStart({
type: "action",
name: actionName,
fn: fn,
target: scope,
arguments: flattendArgs
});
}
var prevUntracked = untrackedStart();
transactionStart(actionName, scope, false);
var prevAllowStateChanges = allowStateChangesStart(true);
try {
return fn.apply(scope, args);
}
finally {
allowStateChangesEnd(prevAllowStateChanges);
transactionEnd(false);
untrackedEnd(prevUntracked);
if (notifySpy)
spyReportEnd({ time: Date.now() - startTime });
}
}
function useStrict(strict) {
if (arguments.length === 0)
return globalState.strictMode;
else {
invariant(globalState.derivationStack.length === 0, "It is not allowed to set `useStrict` when a derivation is running");
globalState.strictMode = strict;
globalState.allowStateChanges = !strict;
}
}
exports.useStrict = useStrict;
function allowStateChanges(allowStateChanges, func) {
var prev = allowStateChangesStart(allowStateChanges);
var res = func();
allowStateChangesEnd(prev);
return res;
}
function allowStateChangesStart(allowStateChanges) {
var prev = globalState.allowStateChanges;
globalState.allowStateChanges = allowStateChanges;
return prev;
}
function allowStateChangesEnd(prev) {
globalState.allowStateChanges = prev;
}
function propagateAtomReady(atom) {
invariant(atom.isDirty, "atom not dirty");
atom.isDirty = false;
propagateReadiness(atom, true);
}
var BaseAtom = (function () {
function BaseAtom(name) {
if (name === void 0) { name = "Atom@" + getNextId(); }
this.name = name;
this.isDirty = false;
this.staleObservers = [];
this.observers = new SimpleSet();
this.diffValue = 0;
this.lastAccessedBy = 0;
}
BaseAtom.prototype.onBecomeUnobserved = function () {
};
BaseAtom.prototype.reportObserved = function () {
reportObserved(this);
};
BaseAtom.prototype.reportChanged = function () {
if (!this.isDirty) {
this.reportStale();
this.reportReady();
}
};
BaseAtom.prototype.reportStale = function () {
if (!this.isDirty) {
this.isDirty = true;
propagateStaleness(this);
}
};
BaseAtom.prototype.reportReady = function () {
invariant(this.isDirty, "atom not dirty");
if (globalState.inTransaction > 0)
globalState.changedAtoms.push(this);
else {
propagateAtomReady(this);
runReactions();
}
};
BaseAtom.prototype.toString = function () {
return this.name;
};
return BaseAtom;
}());
exports.BaseAtom = BaseAtom;
var Atom = (function (_super) {
__extends(Atom, _super);
function Atom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {
if (name === void 0) { name = "Atom@" + getNextId(); }
if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; }
if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; }
_super.call(this, name);
this.name = name;
this.onBecomeObservedHandler = onBecomeObservedHandler;
this.onBecomeUnobservedHandler = onBecomeUnobservedHandler;
this.isBeingTracked = false;
}
Atom.prototype.reportObserved = function () {
_super.prototype.reportObserved.call(this);
var tracking = globalState.isTracking;
if (tracking && !this.isBeingTracked) {
this.isBeingTracked = true;
this.onBecomeObservedHandler();
}
return tracking;
};
Atom.prototype.onBecomeUnobserved = function () {
this.isBeingTracked = false;
this.onBecomeUnobservedHandler();
};
return Atom;
}(BaseAtom));
exports.Atom = Atom;
var ComputedValue = (function () {
function ComputedValue(derivation, scope, compareStructural, name) {
this.derivation = derivation;
this.scope = scope;
this.compareStructural = compareStructural;
this.isLazy = true;
this.isComputing = false;
this.staleObservers = [];
this.observers = new SimpleSet();
this.observing = [];
this.diffValue = 0;
this.runId = 0;
this.lastAccessedBy = 0;
this.unboundDepsCount = 0;
this.__mapid = "#" + getNextId();
this.dependencyChangeCount = 0;
this.dependencyStaleCount = 0;
this.value = undefined;
this.name = name || "ComputedValue@" + getNextId();
}
ComputedValue.prototype.peek = function () {
this.isComputing = true;
var prevAllowStateChanges = allowStateChangesStart(false);
var res = this.derivation.call(this.scope);
allowStateChangesEnd(prevAllowStateChanges);
this.isComputing = false;
return res;
};
;
ComputedValue.prototype.onBecomeUnobserved = function () {
clearObserving(this);
this.isLazy = true;
this.value = undefined;
};
ComputedValue.prototype.onDependenciesReady = function () {
var changed = this.trackAndCompute();
return changed;
};
ComputedValue.prototype.get = function () {
invariant(!this.isComputing, "Cycle detected in computation " + this.name, this.derivation);
reportObserved(this);
if (this.dependencyStaleCount > 0) {
return this.peek();
}
if (this.isLazy) {
if (isComputingDerivation()) {
this.isLazy = false;
this.trackAndCompute();
}
else {
return this.peek();
}
}
return this.value;
};
ComputedValue.prototype.set = function (_) {
throw new Error("[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value.");
};
ComputedValue.prototype.trackAndCompute = function () {
if (isSpyEnabled()) {
spyReport({
object: this,
type: "compute",
fn: this.derivation,
target: this.scope
});
}
var oldValue = this.value;
var newValue = this.value = trackDerivedFunction(this, this.peek);
return valueDidChange(this.compareStructural, newValue, oldValue);
};
ComputedValue.prototype.observe = function (listener, fireImmediately) {
var _this = this;
var firstTime = true;
var prevValue = undefined;
return autorun(function () {
var newValue = _this.get();
if (!firstTime || fireImmediately) {
var prevU = untrackedStart();
listener(newValue, prevValue);
untrackedEnd(prevU);
}
firstTime = false;
prevValue = newValue;
});
};
ComputedValue.prototype.toJSON = function () {
return this.get();
};
ComputedValue.prototype.toString = function () {
return this.name + "[" + this.derivation.toString() + "]";
};
ComputedValue.prototype.whyRun = function () {
var isTracking = globalState.derivationStack.length > 0;
var observing = unique(this.observing).map(function (dep) { return dep.name; });
var observers = unique(this.observers.asArray()).map(function (dep) { return dep.name; });
var runReason = (this.isComputing
? isTracking
? this.observers.length > 0
? RunReason.INVALIDATED
: RunReason.REQUIRED
: RunReason.PEEK
: RunReason.NOT_RUNNING);
if (runReason === RunReason.REQUIRED) {
var requiredBy = globalState.derivationStack[globalState.derivationStack.length - 2];
if (requiredBy)
observers.push(requiredBy.name);
}
return (("\nWhyRun? computation '" + this.name + "':\n * Running because: " + runReasonTexts[runReason] + " " + ((runReason === RunReason.NOT_RUNNING) && this.dependencyStaleCount > 0 ? "(a next run is scheduled)" : "") + "\n") +
(this.isLazy
?
" * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n"
:
" * This computation will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this.isComputing && isTracking) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n " + joinStrings(observers) + "\n"));
};
return ComputedValue;
}());
var RunReason;
(function (RunReason) {
RunReason[RunReason["PEEK"] = 0] = "PEEK";
RunReason[RunReason["INVALIDATED"] = 1] = "INVALIDATED";
RunReason[RunReason["REQUIRED"] = 2] = "REQUIRED";
RunReason[RunReason["NOT_RUNNING"] = 3] = "NOT_RUNNING";
})(RunReason || (RunReason = {}));
var runReasonTexts = (_a = {},
_a[RunReason.PEEK] = "[peek] The value of this computed value was requested outside an reaction",
_a[RunReason.INVALIDATED] = "[invalidated] Some observables used by this computation did change",
_a[RunReason.REQUIRED] = "[started] This computation is required by another computed value / reaction",
_a[RunReason.NOT_RUNNING] = "[idle] This compution is currently not running",
_a
);
function isComputingDerivation() {
return globalState.derivationStack.length > 0
&& globalState.isTracking;
}
function checkIfStateModificationsAreAllowed() {
if (!globalState.allowStateChanges) {
invariant(false, globalState.strictMode
? "It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended"
: "It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.");
}
}
function notifyDependencyStale(derivation) {
if (++derivation.dependencyStaleCount === 1) {
propagateStaleness(derivation);
}
}
function notifyDependencyReady(derivation, dependencyDidChange) {
invariant(derivation.dependencyStaleCount > 0, "unexpected ready notification");
if (dependencyDidChange)
derivation.dependencyChangeCount += 1;
if (--derivation.dependencyStaleCount === 0) {
if (derivation.dependencyChangeCount > 0) {
derivation.dependencyChangeCount = 0;
var changed = derivation.onDependenciesReady();
propagateReadiness(derivation, changed);
}
else {
propagateReadiness(derivation, false);
}
}
}
function trackDerivedFunction(derivation, f) {
var prevObserving = derivation.observing;
derivation.observing = new Array(prevObserving.length + 100);
derivation.unboundDepsCount = 0;
derivation.runId = ++globalState.runId;
globalState.derivationStack.push(derivation);
var prevTracking = globalState.isTracking;
globalState.isTracking = true;
var hasException = true;
var result;
try {
result = f.call(derivation);
hasException = false;
}
finally {
if (hasException) {
var message = ("[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. " +
"These functions should never throw exceptions as MobX will not always be able to recover from them. " +
("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '" + derivation.name + "'. ") +
"For more details see https://github.com/mobxjs/mobx/issues/462");
if (isSpyEnabled()) {
spyReport({
type: "error",
object: this,
message: message
});
}
console.warn(message);
derivation.unboundDepsCount = 0;
derivation.observing = prevObserving;
resetGlobalState();
}
else {
globalState.isTracking = prevTracking;
globalState.derivationStack.length -= 1;
bindDependencies(derivation, prevObserving);
}
}
return result;
}
function bindDependencies(derivation, prevObserving) {
var prevLength = prevObserving.length;
var observing = derivation.observing;
var newLength = observing.length = derivation.unboundDepsCount;
for (var i = 0; i < prevLength; i++)
prevObserving[i].diffValue = -1;
for (var i = 0; i < newLength; i++) {
var dep = observing[i];
if ((++dep.diffValue) > 0) {
dep.diffValue = 0;
addObserver(dep, derivation);
}
}
for (var i = 0; i < prevLength; i++) {
var dep = prevObserving[i];
if (dep.diffValue < 0) {
dep.diffValue = 0;
removeObserver(dep, derivation);
}
}
}
function clearObserving(derivation) {
var obs = derivation.observing;
var l = obs.length;
for (var i = 0; i < l; i++)
removeObserver(obs[i], derivation);
obs.length = 0;
}
function untracked(action) {
var prev = untrackedStart();
var res = action();
untrackedEnd(prev);
return res;
}
exports.untracked = untracked;
function untrackedStart() {
var prev = globalState.isTracking;
globalState.isTracking = false;
return prev;
}
function untrackedEnd(prev) {
globalState.isTracking = prev;
}
var persistentKeys = ["mobxGuid", "resetId", "spyListeners", "strictMode", "runId"];
var MobXGlobals = (function () {
function MobXGlobals() {
this.version = 3;
this.derivationStack = [];
this.runId = 0;
this.mobxGuid = 0;
this.inTransaction = 0;
this.isTracking = false;
this.isRunningReactions = false;
this.changedAtoms = [];
this.pendingReactions = [];
this.allowStateChanges = true;
this.strictMode = false;
this.resetId = 0;
this.spyListeners = [];
}
return MobXGlobals;
}());
var globalState = (function () {
var res = new MobXGlobals();
if (global.__mobservableTrackingStack || global.__mobservableViewStack)
throw new Error("[mobx] An incompatible version of mobservable is already loaded.");
if (global.__mobxGlobal && global.__mobxGlobal.version !== res.version)
throw new Error("[mobx] An incompatible version of mobx is already loaded.");
if (global.__mobxGlobal)
return global.__mobxGlobal;
return global.__mobxGlobal = res;
})();
function registerGlobals() {
}
function resetGlobalState() {
globalState.resetId++;
var defaultGlobals = new MobXGlobals();
for (var key in defaultGlobals)
if (persistentKeys.indexOf(key) === -1)
globalState[key] = defaultGlobals[key];
globalState.allowStateChanges = !globalState.strictMode;
}
function addObserver(observable, node) {
observable.observers.add(node);
}
function removeObserver(observable, node) {
observable.observers.remove(node);
if (observable.observers.length === 0)
observable.onBecomeUnobserved();
}
function reportObserved(observable) {
if (globalState.isTracking === false)
return;
var derivation = globalState.derivationStack[globalState.derivationStack.length - 1];
if (derivation.runId !== observable.lastAccessedBy) {
observable.lastAccessedBy = derivation.runId;
derivation.observing[derivation.unboundDepsCount++] = observable;
}
}
function propagateStaleness(observable) {
var os = observable.observers.asArray();
var l = os.length;
for (var i = 0; i < l; i++)
notifyDependencyStale(os[i]);
observable.staleObservers = observable.staleObservers.concat(os);
}
function propagateReadiness(observable, valueDidActuallyChange) {
observable.staleObservers.splice(0).forEach(function (o) { return notifyDependencyReady(o, valueDidActuallyChange); });
}
var EMPTY_DERIVATION_SET;
var Reaction = (function () {
function Reaction(name, onInvalidate) {
if (name === void 0) { name = "Reaction@" + getNextId(); }
this.name = name;
this.onInvalidate = onInvalidate;
this.staleObservers = EMPTY_ARRAY;
this.observers = EMPTY_DERIVATION_SET || (EMPTY_DERIVATION_SET = new SimpleSet());
this.observing = [];
this.diffValue = 0;
this.runId = 0;
this.lastAccessedBy = 0;
this.unboundDepsCount = 0;
this.__mapid = "#" + getNextId();
this.dependencyChangeCount = 0;
this.dependencyStaleCount = 0;
this.isDisposed = false;
this._isScheduled = false;
this._isTrackPending = false;
this._isRunning = false;
}
Reaction.prototype.onBecomeUnobserved = function () {
};
Reaction.prototype.onDependenciesReady = function () {
this.schedule();
return false;
};
Reaction.prototype.schedule = function () {
if (!this._isScheduled) {
this._isScheduled = true;
globalState.pendingReactions.push(this);
runReactions();
}
};
Reaction.prototype.isScheduled = function () {
return this.dependencyStaleCount > 0 || this._isScheduled;
};
Reaction.prototype.runReaction = function () {
if (!this.isDisposed) {
this._isScheduled = false;
this._isTrackPending = true;
this.onInvalidate();
if (this._isTrackPending && isSpyEnabled()) {
spyReport({
object: this,
type: "scheduled-reaction"
});
}
}
};
Reaction.prototype.track = function (fn) {
var notify = isSpyEnabled();
var startTime;
if (notify) {
startTime = Date.now();
spyReportStart({
object: this,
type: "reaction",
fn: fn
});
}
this._isRunning = true;
trackDerivedFunction(this, fn);
this._isRunning = false;
this._isTrackPending = false;
if (this.isDisposed) {
clearObserving(this);
}
if (notify) {
spyReportEnd({
time: Date.now() - startTime
});
}
};
Reaction.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
if (!this._isRunning)
clearObserving(this);
}
};
Reaction.prototype.getDisposer = function () {
var r = this.dispose.bind(this);
r.$mobx = this;
return r;
};
Reaction.prototype.toString = function () {
return "Reaction[" + this.name + "]";
};
Reaction.prototype.whyRun = function () {
var observing = unique(this.observing).map(function (dep) { return dep.name; });
return ("\nWhyRun? reaction '" + this.name + "':\n * Status: [" + (this.isDisposed ? "stopped" : this._isRunning ? "running" : this.isScheduled() ? "scheduled" : "idle") + "]\n * This reaction will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this._isRunning) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n");
};
return Reaction;
}());
exports.Reaction = Reaction;
var MAX_REACTION_ITERATIONS = 100;
function runReactions() {
if (globalState.isRunningReactions === true || globalState.inTransaction > 0)
return;
globalState.isRunningReactions = true;
var allReactions = globalState.pendingReactions;
var iterations = 0;
while (allReactions.length > 0) {
if (++iterations === MAX_REACTION_ITERATIONS)
throw new Error(("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations.")
+ (" Probably there is a cycle in the reactive function: " + allReactions[0]));
var remainingReactions = allReactions.splice(0);
for (var i = 0, l = remainingReactions.length; i < l; i++)
remainingReactions[i].runReaction();
}
globalState.isRunningReactions = false;
}
var spyEnabled = false;
function isSpyEnabled() {
return spyEnabled;
}
function spyReport(event) {
if (!spyEnabled)
return false;
var listeners = globalState.spyListeners;
for (var i = 0, l = listeners.length; i < l; i++)
listeners[i](event);
}
function spyReportStart(event) {
var change = objectAssign({}, event, { spyReportStart: true });
spyReport(change);
}
var END_EVENT = { spyReportEnd: true };
function spyReportEnd(change) {
if (change)
spyReport(objectAssign({}, change, END_EVENT));
else
spyReport(END_EVENT);
}
function spy(listener) {
globalState.spyListeners.push(listener);
spyEnabled = globalState.spyListeners.length > 0;
return once(function () {
var idx = globalState.spyListeners.indexOf(listener);
if (idx !== -1)
globalState.spyListeners.splice(idx, 1);
spyEnabled = globalState.spyListeners.length > 0;
});
}
exports.spy = spy;
function trackTransitions(onReport) {
deprecated("trackTransitions is deprecated. Use mobx.spy instead");
if (typeof onReport === "boolean") {
deprecated("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first");
onReport = arguments[1];
}
if (!onReport) {
deprecated("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first");
return function () { };
}
return spy(onReport);
}
function transaction(action, thisArg, report) {
if (thisArg === void 0) { thisArg = undefined; }
if (report === void 0) { report = true; }
transactionStart((action.name) || "anonymous transaction", thisArg, report);
var res = action.call(thisArg);
transactionEnd(report);
return res;
}
exports.transaction = transaction;
function transactionStart(name, thisArg, report) {
if (thisArg === void 0) { thisArg = undefined; }
if (report === void 0) { report = true; }
globalState.inTransaction += 1;
if (report && isSpyEnabled()) {
spyReportStart({
type: "transaction",
target: thisArg,
name: name
});
}
}
function transactionEnd(report) {
if (report === void 0) { report = true; }
if (--globalState.inTransaction === 0) {
var values = globalState.changedAtoms.splice(0);
for (var i = 0, l = values.length; i < l; i++)
propagateAtomReady(values[i]);
runReactions();
}
if (report && isSpyEnabled())
spyReportEnd();
}
function hasInterceptors(interceptable) {
return (interceptable.interceptors && interceptable.interceptors.length > 0);
}
function registerInterceptor(interceptable, handler) {
var interceptors = interceptable.interceptors || (interceptable.interceptors = []);
interceptors.push(handler);
return once(function () {
var idx = interceptors.indexOf(handler);
if (idx !== -1)
interceptors.splice(idx, 1);
});
}
function interceptChange(interceptable, change) {
var prevU = untrackedStart();
var interceptors = interceptable.interceptors;
for (var i = 0, l = interceptors.length; i < l; i++) {
change = interceptors[i](change);
invariant(!change || change.type, "Intercept handlers should return nothing or a change object");
if (!change)
return null;
}
untrackedEnd(prevU);
return change;
}
function hasListeners(listenable) {
return listenable.changeListeners && listenable.changeListeners.length > 0;
}
function registerListener(listenable, handler) {
var listeners = listenable.changeListeners || (listenable.changeListeners = []);
listeners.push(handler);
return once(function () {
var idx = listeners.indexOf(handler);
if (idx !== -1)
listeners.splice(idx, 1);
});
}
function notifyListeners(listenable, change) {
var prevU = untrackedStart();
var listeners = listenable.changeListeners;
if (!listeners)
return;
listeners = listeners.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
if (Array.isArray(change)) {
listeners[i].apply(null, change);
}
else {
listeners[i](change);
}
}
untrackedEnd(prevU);
}
var ValueMode;
(function (ValueMode) {
ValueMode[ValueMode["Recursive"] = 0] = "Recursive";
ValueMode[ValueMode["Reference"] = 1] = "Reference";
ValueMode[ValueMode["Structure"] = 2] = "Structure";
ValueMode[ValueMode["Flat"] = 3] = "Flat";
})(ValueMode || (ValueMode = {}));
function asReference(value) {
return new AsReference(value);
}
exports.asReference = asReference;
function asStructure(value) {
return new AsStructure(value);
}
exports.asStructure = asStructure;
function asFlat(value) {
return new AsFlat(value);
}
exports.asFlat = asFlat;
var AsReference = (function () {
function AsReference(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsReference;
}());
var AsStructure = (function () {
function AsStructure(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsStructure;
}());
var AsFlat = (function () {
function AsFlat(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsFlat;
}());
function asMap(data, modifierFunc) {
return map(data, modifierFunc);
}
exports.asMap = asMap;
function getValueModeFromValue(value, defaultMode) {
if (value instanceof AsReference)
return [ValueMode.Reference, value.value];
if (value instanceof AsStructure)
return [ValueMode.Structure, value.value];
if (value instanceof AsFlat)
return [ValueMode.Flat, value.value];
return [defaultMode, value];
}
function getValueModeFromModifierFunc(func) {
if (func === asReference)
return ValueMode.Reference;
else if (func === asStructure)
return ValueMode.Structure;
else if (func === asFlat)
return ValueMode.Flat;
invariant(func === undefined, "Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: " + func);
return ValueMode.Recursive;
}
function makeChildObservable(value, parentMode, name) {
var childMode;
if (isObservable(value))
return value;
switch (parentMode) {
case ValueMode.Reference:
return value;
case ValueMode.Flat:
assertUnwrapped(value, "Items inside 'asFlat' cannot have modifiers");
childMode = ValueMode.Reference;
break;
case ValueMode.Structure:
assertUnwrapped(value, "Items inside 'asStructure' cannot have modifiers");
childMode = ValueMode.Structure;
break;
case ValueMode.Recursive:
_a = getValueModeFromValue(value, ValueMode.Recursive), childMode = _a[0], value = _a[1];
break;
default:
invariant(false, "Illegal State");
}
if (Array.isArray(value))
return createObservableArray(value, childMode, name);
if (isPlainObject(value) && Object.isExtensible(value))
return extendObservableHelper(value, value, childMode, name);
return value;
var _a;
}
function assertUnwrapped(value, message) {
if (value instanceof AsReference || value instanceof AsStructure || value instanceof AsFlat)
throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. " + message);
}
var safariPrototypeSetterInheritanceBug = (function () {
var v = false;
var p = {};
Object.defineProperty(p, "0", { set: function () { v = true; } });
Object.create(p)["0"] = 1;
return v === false;
})();
var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
var StubArray = (function () {
function StubArray() {
}
return StubArray;
}());
StubArray.prototype = [];
var ObservableArrayAdministration = (function () {
function ObservableArrayAdministration(name, mode, array, owned) {
this.mode = mode;
this.array = array;
this.owned = owned;
this.lastKnownLength = 0;
this.interceptors = null;
this.changeListeners = null;
this.atom = new BaseAtom(name || ("ObservableArray@" + getNextId()));
}
ObservableArrayAdministration.prototype.makeReactiveArrayItem = function (value) {
assertUnwrapped(value, "Array values cannot have modifiers");
if (this.mode === ValueMode.Flat || this.mode === ValueMode.Reference)
return value;
return makeChildObservable(value, this.mode, this.atom.name + "[..]");
};
ObservableArrayAdministration.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately === void 0) { fireImmediately = false; }
if (fireImmediately) {
listener({
object: this.array,
type: "splice",
index: 0,
added: this.values.slice(),
addedCount: this.values.length,
removed: [],
removedCount: 0
});
}
return registerListener(this, listener);
};
ObservableArrayAdministration.prototype.getArrayLength = function () {
this.atom.reportObserved();
return this.values.length;
};
ObservableArrayAdministration.prototype.setArrayLength = function (newLength) {
if (typeof newLength !== "number" || newLength < 0)
throw new Error("[mobx.array] Out of range: " + newLength);
var currentLength = this.values.length;
if (newLength === currentLength)
return;
else if (newLength > currentLength)
this.spliceWithArray(currentLength, 0, new Array(newLength - currentLength));
else
this.spliceWithArray(newLength, currentLength - newLength);
};
ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) {
if (oldLength !== this.lastKnownLength)
throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");
this.lastKnownLength += delta;
if (delta > 0 && oldLength + delta + 1 > OBSERVABLE_ARRAY_BUFFER_SIZE)
reserveArrayBuffer(oldLength + delta + 1);
};
ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) {
checkIfStateModificationsAreAllowed();
var length = this.values.length;
if (index === undefined)
index = 0;
else if (index > length)
index = length;
else if (index < 0)
index = Math.max(0, length + index);
if (arguments.length === 1)
deleteCount = length - index;
else if (deleteCount === undefined || deleteCount === null)
deleteCount = 0;
else
deleteCount = Math.max(0, Math.min(deleteCount, length - index));
if (newItems === undefined)
newItems = [];
if (hasInterceptors(this)) {
var change = interceptChange(this, {
object: this.array,
type: "splice",
index: index,
removedCount: deleteCount,
added: newItems
});
if (!change)
return EMPTY_ARRAY;
deleteCount = change.removedCount;
newItems = change.added;
}
newItems = newItems.map(this.makeReactiveArrayItem, this);
var lengthDelta = newItems.length - deleteCount;
this.updateArrayLength(length, lengthDelta);
var res = (_a = this.values).splice.apply(_a, [index, deleteCount].concat(newItems));
if (deleteCount !== 0 || newItems.length !== 0)
this.notifyArraySplice(index, newItems, res);
return res;
var _a;
};
ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) {
var notifySpy = !this.owned && isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
object: this.array,
type: "update",
index: index, newValue: newValue, oldValue: oldValue
} : null;
if (notifySpy)
spyReportStart(change);
this.atom.reportChanged();
if (notify)
notifyListeners(this, change);
if (notifySpy)
spyReportEnd();
};
ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) {
var notifySpy = !this.owned && isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
object: this.array,
type: "splice",
index: index, removed: removed, added: added,
removedCount: removed.length,
addedCount: added.length
} : null;
if (notifySpy)
spyReportStart(change);
this.atom.reportChanged();
if (notify)
notifyListeners(this, change);
if (notifySpy)
spyReportEnd();
};
return ObservableArrayAdministration;
}());
var ObservableArray = (function (_super) {
__extends(ObservableArray, _super);
function ObservableArray(initialValues, mode, name, owned) {
if (owned === void 0) { owned = false; }
_super.call(this);
var adm = new ObservableArrayAdministration(name, mode, this, owned);
addHiddenFinalProp(this, "$mobx", adm);
if (initialValues && initialValues.length) {
adm.updateArrayLength(0, initialValues.length);
adm.values = initialValues.map(adm.makeReactiveArrayItem, adm);
adm.notifyArraySplice(0, adm.values.slice(), EMPTY_ARRAY);
}
else {
adm.values = [];
}
if (safariPrototypeSetterInheritanceBug) {
Object.defineProperty(adm.array, "0", ENTRY_0);
}
}
ObservableArray.prototype.intercept = function (handler) {
return this.$mobx.intercept(handler);
};
ObservableArray.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately === void 0) { fireImmediately = false; }
return this.$mobx.observe(listener, fireImmediately);
};
ObservableArray.prototype.clear = function () {
return this.splice(0);
};
ObservableArray.prototype.concat = function () {
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i - 0] = arguments[_i];
}
this.$mobx.atom.reportObserved();
return Array.prototype.concat.apply(this.slice(), arrays.map(function (a) { return isObservableArray(a) ? a.slice() : a; }));
};
ObservableArray.prototype.replace = function (newItems) {
return this.$mobx.spliceWithArray(0, this.$mobx.values.length, newItems);
};
ObservableArray.prototype.toJS = function () {
return this.slice();
};
ObservableArray.prototype.toJSON = function () {
return this.toJS();
};
ObservableArray.prototype.peek = function () {
return this.$mobx.values;
};
ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) {
if (fromIndex === void 0) { fromIndex = 0; }
this.$mobx.atom.reportObserved();
var items = this.$mobx.values, l = items.length;
for (var i = fromIndex; i < l; i++)
if (predicate.call(thisArg, items[i], i, this))
return items[i];
return undefined;
};
ObservableArray.prototype.splice = function (index, deleteCount) {
var newItems = [];
for (var _i = 2; _i < arguments.length; _i++) {
newItems[_i - 2] = arguments[_i];
}
switch (arguments.length) {
case 0:
return [];
case 1:
return this.$mobx.spliceWithArray(index);
case 2:
return this.$mobx.spliceWithArray(index, deleteCount);
}
return this.$mobx.spliceWithArray(index, deleteCount, newItems);
};
ObservableArray.prototype.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments[_i];
}
var adm = this.$mobx;
adm.spliceWithArray(adm.values.length, 0, items);
return adm.values.length;
};
ObservableArray.prototype.pop = function () {
return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0];
};
ObservableArray.prototype.shift = function () {
return this.splice(0, 1)[0];
};
ObservableArray.prototype.unshift = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments[_i];
}
var adm = this.$mobx;
adm.spliceWithArray(0, 0, items);
return adm.values.length;
};
ObservableArray.prototype.reverse = function () {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.reverse.apply(clone, arguments);
};
ObservableArray.prototype.sort = function (compareFn) {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.sort.apply(clone, arguments);
};
ObservableArray.prototype.remove = function (value) {
var idx = this.$mobx.values.indexOf(value);
if (idx > -1) {
this.splice(idx, 1);
return true;
}
return false;
};
ObservableArray.prototype.toString = function () {
return "[mobx.array] " + Array.prototype.toString.apply(this.$mobx.values, arguments);
};
ObservableArray.prototype.toLocaleString = function () {
return "[mobx.array] " + Array.prototype.toLocaleString.apply(this.$mobx.values, arguments);
};
return ObservableArray;
}(StubArray));
declareIterator(ObservableArray.prototype, function () {
return arrayAsIterator(this.slice());
});
makeNonEnumerable(ObservableArray.prototype, [
"constructor",
"observe",
"clear",
"concat",
"replace",
"toJSON",
"peek",
"find",
"splice",
"push",
"pop",
"shift",
"unshift",
"reverse",
"sort",
"remove",
"toString",
"toLocaleString"
]);
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function () {
return this.$mobx.getArrayLength();
},
set: function (newLength) {
this.$mobx.setArrayLength(newLength);
}
});
[
"every",
"filter",
"forEach",
"indexOf",
"join",
"lastIndexOf",
"map",
"reduce",
"reduceRight",
"slice",
"some"
].forEach(function (funcName) {
var baseFunc = Array.prototype[funcName];
addHiddenProp(ObservableArray.prototype, funcName, function () {
this.$mobx.atom.reportObserved();
return baseFunc.apply(this.$mobx.values, arguments);
});
});
var ENTRY_0 = {
configurable: true,
enumerable: false,
set: createArraySetter(0),
get: createArrayGetter(0)
};
function createArrayBufferItem(index) {
var set = createArraySetter(index);
var get = createArrayGetter(index);
Object.defineProperty(ObservableArray.prototype, "" + index, {
enumerable: false,
configurable: true,
set: set, get: get
});
}
function createArraySetter(index) {
return function (newValue) {
var adm = this.$mobx;
var values = adm.values;
assertUnwrapped(newValue, "Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array)).");
if (index < values.length) {
checkIfStateModificationsAreAllowed();
var oldValue = values[index];
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
type: "update",
object: adm.array,
index: index, newValue: newValue
});
if (!change)
return;
newValue = change.newValue;
}
newValue = adm.makeReactiveArrayItem(newValue);
var changed = (adm.mode === ValueMode.Structure) ? !deepEquals(oldValue, newValue) : oldValue !== newValue;
if (changed) {
values[index] = newValue;
adm.notifyArrayChildUpdate(index, newValue, oldValue);
}
}
else if (index === values.length) {
adm.spliceWithArray(index, 0, [newValue]);
}
else
throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length);
};
}
function createArrayGetter(index) {
return function () {
var impl = this.$mobx;
if (impl && index < impl.values.length) {
impl.atom.reportObserved();
return impl.values[index];
}
console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + impl.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX");
return undefined;
};
}
function reserveArrayBuffer(max) {
for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++)
createArrayBufferItem(index);
OBSERVABLE_ARRAY_BUFFER_SIZE = max;
}
reserveArrayBuffer(1000);
function createObservableArray(initialValues, mode, name) {
return new ObservableArray(initialValues, mode, name);
}
function fastArray(initialValues) {
deprecated("fastArray is deprecated. Please use `observable(asFlat([]))`");
return createObservableArray(initialValues, ValueMode.Flat, null);
}
exports.fastArray = fastArray;
function isObservableArray(thing) {
return thing instanceof ObservableArray;
}
exports.isObservableArray = isObservableArray;
var ObservableMapMarker = {};
var ObservableMap = (function () {
function ObservableMap(initialData, valueModeFunc) {
var _this = this;
this.$mobx = ObservableMapMarker;
this._data = {};
this._hasMap = {};
this.name = "ObservableMap@" + getNextId();
this._keys = new ObservableArray(null, ValueMode.Reference, this.name + ".keys()", true);
this.interceptors = null;
this.changeListeners = null;
this._valueMode = getValueModeFromModifierFunc(valueModeFunc);
if (this._valueMode === ValueMode.Flat)
this._valueMode = ValueMode.Reference;
allowStateChanges(true, function () {
if (isPlainObject(initialData))
_this.merge(initialData);
else if (Array.isArray(initialData))
initialData.forEach(function (_a) {
var key = _a[0], value = _a[1];
return _this.set(key, value);
});
});
}
ObservableMap.prototype._has = function (key) {
return typeof this._data[key] !== "undefined";
};
ObservableMap.prototype.has = function (key) {
if (!this.isValidKey(key))
return false;
key = "" + key;
if (this._hasMap[key])
return this._hasMap[key].get();
return this._updateHasMapEntry(key, false).get();
};
ObservableMap.prototype.set = function (key, value) {
this.assertValidKey(key);
key = "" + key;
var hasKey = this._has(key);
assertUnwrapped(value, "[mobx.map.set] Expected unwrapped value to be inserted to key '" + key + "'. If you need to use modifiers pass them as second argument to the constructor");
if (hasInterceptors(this)) {
var change = interceptChange(this, {
type: hasKey ? "update" : "add",
object: this,
newValue: value,
name: key
});
if (!change)
return;
value = change.newValue;
}
if (hasKey) {
this._updateValue(key, value);
}
else {
this._addValue(key, value);
}
};
ObservableMap.prototype.delete = function (key) {
var _this = this;
this.assertValidKey(key);
key = "" + key;
if (hasInterceptors(this)) {
var change = interceptChange(this, {
type: "delete",
object: this,
name: key
});
if (!change)
return;
}
if (this._has(key)) {
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "delete",
object: this,
oldValue: this._data[key].value,
name: key
} : null;
if (notifySpy)
spyReportStart(change);
transaction(function () {
_this._keys.remove(key);
_this._updateHasMapEntry(key, false);
var observable = _this._data[key];
observable.setNewValue(undefined);
_this._data[key] = undefined;
}, undefined, false);
if (notify)
notifyListeners(this, change);
if (notifySpy)
spyReportEnd();
}
};
ObservableMap.prototype._updateHasMapEntry = function (key, value) {
var entry = this._hasMap[key];
if (entry) {
entry.setNewValue(value);
}
else {
entry = this._hasMap[key] = new ObservableValue(value, ValueMode.Reference, this.name + "." + key + "?", false);
}
return entry;
};
ObservableMap.prototype._updateValue = function (name, newValue) {
var observable = this._data[name];
newValue = observable.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "update",
object: this,
oldValue: observable.value,
name: name, newValue: newValue
} : null;
if (notifySpy)
spyReportStart(change);
observable.setNewValue(newValue);
if (notify)
notifyListeners(this, change);
if (notifySpy)
spyReportEnd();
}
};
ObservableMap.prototype._addValue = function (name, newValue) {
var _this = this;
transaction(function () {
var observable = _this._data[name] = new ObservableValue(newValue, _this._valueMode, _this.name + "." + name, false);
newValue = observable.value;
_this._updateHasMapEntry(name, true);
_this._keys.push(name);
}, undefined, false);
var notifySpy = isSpyEnabled();
var notify = hasListeners(this);
var change = notify || notifySpy ? {
type: "add",
object: this,
name: name, newValue: newValue
} : null;
if (notifySpy)
spyReportStart(change);
if (notify)
notifyListeners(this, change);
if (notifySpy)
spyReportEnd();
};
ObservableMap.prototype.get = function (key) {
key = "" + key;
if (this.has(key))
return this._data[key].get();
return undefined;
};
ObservableMap.prototype.keys = function () {
return arrayAsIterator(this._keys.slice());
};
ObservableMap.prototype.values = function () {
return arrayAsIterator(this._keys.map(this.get, this));
};
ObservableMap.prototype.entries = function () {
var _this = this;
return arrayAsIterator(this._keys.map(function (key) { return [key, _this.get(key)]; }));
};
ObservableMap.prototype.forEach = function (callback, thisArg) {
var _this = this;
this.keys().forEach(function (key) { return callback.call(thisArg, _this.get(key), key); });
};
ObservableMap.prototype.merge = function (other) {
var _this = this;
transaction(function () {
if (other instanceof ObservableMap)
other.keys().forEach(function (key) { return _this.set(key, other.get(key)); });
else
Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); });
}, undefined, false);
return this;
};
ObservableMap.prototype.clear = function () {
var _this = this;
transaction(function () {
untracked(function () {
_this.keys().forEach(_this.delete, _this);
});
}, undefined, false);
};
Object.defineProperty(ObservableMap.prototype, "size", {
get: function () {
return this._keys.length;
},
enumerable: true,
configurable: true
});
ObservableMap.prototype.toJS = function () {
var _this = this;
var res = {};
this.keys().forEach(function (key) { return res[key] = _this.get(key); });
return res;
};
ObservableMap.prototype.toJs = function () {
deprecated("toJs is deprecated, use toJS instead");
return this.toJS();
};
ObservableMap.prototype.toJSON = function () {
return this.toJS();
};
ObservableMap.prototype.isValidKey = function (key) {
if (key === null || key === undefined)
return false;
if (typeof key !== "string" && typeof key !== "number" && typeof key !== "boolean")
return false;
return true;
};
ObservableMap.prototype.assertValidKey = function (key) {
if (!this.isValidKey(key))
throw new Error("[mobx.map] Invalid key: '" + key + "'");
};
ObservableMap.prototype.toString = function () {
var _this = this;
return this.name + "[{ " + this.keys().map(function (key) { return (key + ": " + ("" + _this.get(key))); }).join(", ") + " }]";
};
ObservableMap.prototype.observe = function (listener, fireImmediately) {
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable maps.");
return registerListener(this, listener);
};
ObservableMap.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
return ObservableMap;
}());
exports.ObservableMap = ObservableMap;
declareIterator(ObservableMap.prototype, function () {
return this.entries();
});
function map(initialValues, valueModifier) {
return new ObservableMap(initialValues, valueModifier);
}
exports.map = map;
function isObservableMap(thing) {
return thing instanceof ObservableMap;
}
exports.isObservableMap = isObservableMap;
var ObservableObjectAdministration = (function () {
function ObservableObjectAdministration(target, name, mode) {
this.target = target;
this.name = name;
this.mode = mode;
this.values = {};
this.changeListeners = null;
this.interceptors = null;
}
ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) {
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects.");
return registerListener(this, callback);
};
ObservableObjectAdministration.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
return ObservableObjectAdministration;
}());
function asObservableObject(target, name, mode) {
if (mode === void 0) { mode = ValueMode.Recursive; }
if (isObservableObject(target))
return target.$mobx;
if (!isPlainObject(target))
name = target.constructor.name + "@" + getNextId();
if (!name)
name = "ObservableObject@" + getNextId();
var adm = new ObservableObjectAdministration(target, name, mode);
addHiddenFinalProp(target, "$mobx", adm);
return adm;
}
function setObservableObjectInstanceProperty(adm, propName, value) {
if (adm.values[propName])
adm.target[propName] = value;
else
defineObservableProperty(adm, propName, value, true);
}
function defineObservableProperty(adm, propName, newValue, asInstanceProperty) {
if (asInstanceProperty)
assertPropertyConfigurable(adm.target, propName);
var observable;
var name = adm.name + "." + propName;
var isComputed = true;
if (typeof newValue === "function" && newValue.length === 0 && !isAction(newValue))
observable = new ComputedValue(newValue, adm.target, false, name);
else if (newValue instanceof AsStructure && typeof newValue.value === "function" && newValue.value.length === 0)
observable = new ComputedValue(newValue.value, adm.target, true, name);
else {
isComputed = false;
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
object: adm.target,
name: propName,
type: "add",
newValue: newValue
});
if (!change)
return;
newValue = change.newValue;
}
observable = new ObservableValue(newValue, adm.mode, name, false);
newValue = observable.value;
}
adm.values[propName] = observable;
if (asInstanceProperty) {
Object.defineProperty(adm.target, propName, isComputed ? generateComputedPropConfig(propName) : generateObservablePropConfig(propName));
}
if (!isComputed)
notifyPropertyAddition(adm, adm.target, propName, newValue);
}
var observablePropertyConfigs = {};
var computedPropertyConfigs = {};
function generateObservablePropConfig(propName) {
var config = observablePropertyConfigs[propName];
if (config)
return config;
return observablePropertyConfigs[propName] = {
configurable: true,
enumerable: true,
get: function () {
return this.$mobx.values[propName].get();
},
set: function (v) {
setPropertyValue(this, propName, v);
}
};
}
function generateComputedPropConfig(propName) {
var config = computedPropertyConfigs[propName];
if (config)
return config;
return computedPropertyConfigs[propName] = {
configurable: true,
enumerable: false,
get: function () {
return this.$mobx.values[propName].get();
},
set: throwingComputedValueSetter
};
}
function setPropertyValue(instance, name, newValue) {
var adm = instance.$mobx;
var observable = adm.values[name];
if (hasInterceptors(adm)) {
var change = interceptChange(adm, {
type: "update",
object: instance,
name: name, newValue: newValue
});
if (!change)
return;
newValue = change.newValue;
}
newValue = observable.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notify = hasListeners(adm);
var notifySpy = isSpyEnabled();
var change = notifyListeners || hasListeners ? {
type: "update",
object: instance,
oldValue: observable.value,
name: name, newValue: newValue
} : null;
if (notifySpy)
spyReportStart(change);
observable.setNewValue(newValue);
if (notify)
notifyListeners(adm, change);
if (notifySpy)
spyReportEnd();
}
}
function notifyPropertyAddition(adm, object, name, newValue) {
var notify = hasListeners(adm);
var notifySpy = isSpyEnabled();
var change = notify || notifySpy ? {
type: "add",
object: object, name: name, newValue: newValue
} : null;
if (notifySpy)
spyReportStart(change);
if (notify)
notifyListeners(adm, change);
if (notifySpy)
spyReportEnd();
}
function isObservableObject(thing) {
if (typeof thing === "object" && thing !== null) {
runLazyInitializers(thing);
return thing.$mobx instanceof ObservableObjectAdministration;
}
return false;
}
exports.isObservableObject = isObservableObject;
var UNCHANGED = {};
var ObservableValue = (function (_super) {
__extends(ObservableValue, _super);
function ObservableValue(value, mode, name, notifySpy) {
if (name === void 0) { name = "ObservableValue@" + getNextId(); }
if (notifySpy === void 0) { notifySpy = true; }
_super.call(this, name);
this.mode = mode;
this.hasUnreportedChange = false;
this.value = undefined;
var _a = getValueModeFromValue(value, ValueMode.Recursive), childmode = _a[0], unwrappedValue = _a[1];
if (this.mode === ValueMode.Recursive)
this.mode = childmode;
this.value = makeChildObservable(unwrappedValue, this.mode, this.name);
if (notifySpy && isSpyEnabled()) {
spyReport({ type: "create", object: this, newValue: this.value });
}
}
ObservableValue.prototype.set = function (newValue) {
var oldValue = this.value;
newValue = this.prepareNewValue(newValue);
if (newValue !== UNCHANGED) {
var notifySpy = isSpyEnabled();
if (notifySpy) {
spyReportStart({
type: "update",
object: this,
newValue: newValue, oldValue: oldValue
});
}
this.setNewValue(newValue);
if (notifySpy)
spyReportEnd();
}
};
ObservableValue.prototype.prepareNewValue = function (newValue) {
assertUnwrapped(newValue, "Modifiers cannot be used on non-initial values.");
checkIfStateModificationsAreAllowed();
if (hasInterceptors(this)) {
var change = interceptChange(this, { object: this, type: "update", newValue: newValue });
if (!change)
return UNCHANGED;
newValue = change.newValue;
}
var changed = valueDidChange(this.mode === ValueMode.Structure, this.value, newValue);
if (changed)
return makeChildObservable(newValue, this.mode, this.name);
return UNCHANGED;
};
ObservableValue.prototype.setNewValue = function (newValue) {
var oldValue = this.value;
this.value = newValue;
this.reportChanged();
if (hasListeners(this))
notifyListeners(this, [newValue, oldValue]);
};
ObservableValue.prototype.get = function () {
this.reportObserved();
return this.value;
};
ObservableValue.prototype.intercept = function (handler) {
return registerInterceptor(this, handler);
};
ObservableValue.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately)
listener(this.value, undefined);
return registerListener(this, listener);
};
ObservableValue.prototype.toJSON = function () {
return this.get();
};
ObservableValue.prototype.toString = function () {
return this.name + "[" + this.value + "]";
};
return ObservableValue;
}(BaseAtom));
function getAtom(thing, property) {
if (typeof thing === "object" && thing !== null) {
if (isObservableArray(thing)) {
invariant(property === undefined, "It is not possible to get index atoms from arrays");
return thing.$mobx.atom;
}
if (isObservableMap(thing)) {
if (property === undefined)
return getAtom(thing._keys);
var observable_1 = thing._data[property] || thing._hasMap[property];
invariant(!!observable_1, "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'");
return observable_1;
}
runLazyInitializers(thing);
if (isObservableObject(thing)) {
invariant(!!property, "please specify a property");
var observable_2 = thing.$mobx.values[property];
invariant(!!observable_2, "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'");
return observable_2;
}
if (thing instanceof BaseAtom || thing instanceof ComputedValue || thing instanceof Reaction) {
return thing;
}
}
else if (typeof thing === "function") {
if (thing.$mobx instanceof Reaction) {
return thing.$mobx;
}
}
invariant(false, "Cannot obtain atom from " + thing);
}
function getAdministration(thing, property) {
invariant(thing, "Expection some object");
if (property !== undefined)
return getAdministration(getAtom(thing, property));
if (thing instanceof BaseAtom || thing instanceof ComputedValue || thing instanceof Reaction)
return thing;
if (isObservableMap(thing))
return thing;
runLazyInitializers(thing);
if (thing.$mobx)
return thing.$mobx;
invariant(false, "Cannot obtain administration from " + thing);
}
function getDebugName(thing, property) {
var named;
if (property !== undefined)
named = getAtom(thing, property);
else if (isObservableObject(thing) || isObservableMap(thing))
named = getAdministration(thing);
else
named = getAtom(thing);
return named.name;
}
function createClassPropertyDecorator(onInitialize, get, set, enumerable, allowCustomArguments) {
function classPropertyDecorator(target, key, descriptor, customArgs) {
invariant(allowCustomArguments || quacksLikeADecorator(arguments), "This function is a decorator, but it wasn't invoked like a decorator");
if (!descriptor) {
var newDescriptor = {
enumerable: enumerable,
configurable: true,
get: function () {
if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true)
typescriptInitializeProperty(this, key, undefined, onInitialize, customArgs, descriptor);
return get.call(this, key);
},
set: function (v) {
if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) {
typescriptInitializeProperty(this, key, v, onInitialize, customArgs, descriptor);
}
else {
set.call(this, key, v);
}
}
};
if (arguments.length < 3) {
Object.defineProperty(target, key, newDescriptor);
}
return newDescriptor;
}
else {
if (!target.hasOwnProperty("__mobxLazyInitializers")) {
addHiddenProp(target, "__mobxLazyInitializers", (target.__mobxLazyInitializers && target.__mobxLazyInitializers.slice()) || []);
}
var value_1 = descriptor.value, initializer_1 = descriptor.initializer;
target.__mobxLazyInitializers.push(function (instance) {
onInitialize(instance, key, (initializer_1 ? initializer_1.call(instance) : value_1), customArgs, descriptor);
});
return {
enumerable: enumerable, configurable: true,
get: function () {
if (this.__mobxDidRunLazyInitializers !== true)
runLazyInitializers(this);
return get.call(this, key);
},
set: function (v) {
if (this.__mobxDidRunLazyInitializers !== true)
runLazyInitializers(this);
set.call(this, key, v);
}
};
}
}
if (allowCustomArguments) {
return function () {
if (quacksLikeADecorator(arguments))
return classPropertyDecorator.apply(null, arguments);
var outerArgs = arguments;
return function (target, key, descriptor) { return classPropertyDecorator(target, key, descriptor, outerArgs); };
};
}
return classPropertyDecorator;
}
function typescriptInitializeProperty(instance, key, v, onInitialize, customArgs, baseDescriptor) {
if (!instance.hasOwnProperty("__mobxInitializedProps"))
addHiddenProp(instance, "__mobxInitializedProps", {});
instance.__mobxInitializedProps[key] = true;
onInitialize(instance, key, v, customArgs, baseDescriptor);
}
function runLazyInitializers(instance) {
if (instance.__mobxDidRunLazyInitializers === true)
return;
if (instance.__mobxLazyInitializers) {
addHiddenProp(instance, "__mobxDidRunLazyInitializers", true);
instance.__mobxDidRunLazyInitializers && instance.__mobxLazyInitializers.forEach(function (initializer) { return initializer(instance); });
}
}
function quacksLikeADecorator(args) {
return (args.length === 2 || args.length === 3) && typeof args[1] === "string";
}
function iteratorSymbol() {
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
var IS_ITERATING_MARKER = "__$$iterating";
function arrayAsIterator(array) {
invariant(array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator");
addHiddenFinalProp(array, IS_ITERATING_MARKER, true);
var idx = -1;
addHiddenFinalProp(array, "next", function next() {
idx++;
return {
done: idx >= this.length,
value: idx < this.length ? this[idx] : undefined
};
});
return array;
}
function declareIterator(prototType, iteratorFactory) {
addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory);
}
var SimpleSet = (function () {
function SimpleSet() {
this.size = 0;
this.data = {};
}
Object.defineProperty(SimpleSet.prototype, "length", {
get: function () {
return this.size;
},
enumerable: true,
configurable: true
});
SimpleSet.prototype.asArray = function () {
var res = new Array(this.size);
var i = 0;
for (var key in this.data) {
res[i] = this.data[key];
i++;
}
return res;
};
SimpleSet.prototype.add = function (value) {
var m = value.__mapid;
if (!(m in this.data)) {
this.data[m] = value;
this.size++;
}
};
SimpleSet.prototype.remove = function (value) {
if (value.__mapid in this.data) {
delete this.data[value.__mapid];
this.size--;
}
};
return SimpleSet;
}());
exports.SimpleSet = SimpleSet;
var SimpleEventEmitter = (function () {
function SimpleEventEmitter() {
this.listeners = [];
deprecated("extras.SimpleEventEmitter is deprecated and will be removed in the next major release");
}
SimpleEventEmitter.prototype.emit = function () {
var listeners = this.listeners.slice();
for (var i = 0, l = listeners.length; i < l; i++)
listeners[i].apply(null, arguments);
};
SimpleEventEmitter.prototype.on = function (listener) {
var _this = this;
this.listeners.push(listener);
return once(function () {
var idx = _this.listeners.indexOf(listener);
if (idx !== -1)
_this.listeners.splice(idx, 1);
});
};
SimpleEventEmitter.prototype.once = function (listener) {
var subscription = this.on(function () {
subscription();
listener.apply(this, arguments);
});
return subscription;
};
return SimpleEventEmitter;
}());
exports.SimpleEventEmitter = SimpleEventEmitter;
var EMPTY_ARRAY = [];
Object.freeze(EMPTY_ARRAY);
function getNextId() {
return ++globalState.mobxGuid;
}
function invariant(check, message, thing) {
if (!check)
throw new Error("[mobx] Invariant failed: " + message + (thing ? " in '" + thing + "'" : ""));
}
var deprecatedMessages = [];
function deprecated(msg) {
if (deprecatedMessages.indexOf(msg) !== -1)
return;
deprecatedMessages.push(msg);
console.error("[mobx] Deprecated: " + msg);
}
function once(func) {
var invoked = false;
return function () {
if (invoked)
return;
invoked = true;
return func.apply(this, arguments);
};
}
var noop = function () { };
function unique(list) {
var res = [];
list.forEach(function (item) {
if (res.indexOf(item) === -1)
res.push(item);
});
return res;
}
function joinStrings(things, limit, separator) {
if (limit === void 0) { limit = 100; }
if (separator === void 0) { separator = " - "; }
if (!things)
return "";
var sliced = things.slice(0, limit);
return "" + sliced.join(separator) + (things.length > limit ? " (... and " + (things.length - limit) + "more)" : "");
}
function isPlainObject(value) {
if (value === null || typeof value !== "object")
return false;
var proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function objectAssign() {
var res = arguments[0];
for (var i = 1, l = arguments.length; i < l; i++) {
var source = arguments[i];
for (var key in source)
if (source.hasOwnProperty(key)) {
res[key] = source[key];
}
}
return res;
}
function valueDidChange(compareStructural, oldValue, newValue) {
return compareStructural
? !deepEquals(oldValue, newValue)
: oldValue !== newValue;
}
function makeNonEnumerable(object, propNames) {
for (var i = 0; i < propNames.length; i++) {
addHiddenProp(object, propNames[i], object[propNames[i]]);
}
}
function addHiddenProp(object, propName, value) {
Object.defineProperty(object, propName, {
enumerable: false,
writable: true,
configurable: true,
value: value
});
}
function addHiddenFinalProp(object, propName, value) {
Object.defineProperty(object, propName, {
enumerable: false,
writable: false,
configurable: true,
value: value
});
}
function isPropertyConfigurable(object, prop) {
var descriptor = Object.getOwnPropertyDescriptor(object, prop);
return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false);
}
function assertPropertyConfigurable(object, prop) {
invariant(isPropertyConfigurable(object, prop), "Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object");
}
function getEnumerableKeys(obj) {
var res = [];
for (var key in obj)
res.push(key);
return res;
}
function deepEquals(a, b) {
if (a === null && b === null)
return true;
if (a === undefined && b === undefined)
return true;
var aIsArray = Array.isArray(a) || isObservableArray(a);
if (aIsArray !== (Array.isArray(b) || isObservableArray(b))) {
return false;
}
else if (aIsArray) {
if (a.length !== b.length)
return false;
for (var i = a.length - 1; i >= 0; i--)
if (!deepEquals(a[i], b[i]))
return false;
return true;
}
else if (typeof a === "object" && typeof b === "object") {
if (a === null || b === null)
return false;
if (getEnumerableKeys(a).length !== getEnumerableKeys(b).length)
return false;
for (var prop in a) {
if (!(prop in b))
return false;
if (!deepEquals(a[prop], b[prop]))
return false;
}
return true;
}
return a === b;
}
var _a;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
});
|
var five = require("../lib/johnny-five.js"),
board, Navigator, bot, left, right, sonar, scanner, servos,
expandWhich, reverseDirMap, scale;
reverseDirMap = {
right: "left",
left: "right"
};
scale = function(speed, low, high) {
return Math.floor(five.Fn.map(speed, 0, 5, low, high));
};
/**
* Navigator
* @param {Object} opts Optional properties object
*/
function Navigator(opts) {
// Boe Navigator continuous are calibrated to stop at 90°
this.center = opts.center || 90;
this.servos = {
right: new five.Servo({
pin: opts.right,
type: "continuous"
}),
left: new five.Servo({
pin: opts.left,
type: "continuous"
})
};
this.direction = opts.direction || {
right: this.center,
left: this.center
};
this.speed = opts.speed == null ? 0 : opts.speed;
this.history = [];
this.which = "forward";
this.isTurning = false;
setTimeout(function() {
this.fwd(1).fwd(0);
}.bind(this), 10);
}
/**
* move
* @param {Number} right Speed/Direction of right servo
* @param {Number} left Speed/Direction of left servo
* @return {Object} this
*/
Navigator.prototype.move = function(right, left) {
// Quietly ignore duplicate instructions
if (this.direction.right === right &&
this.direction.left === left) {
return this;
}
// Servos are mounted opposite of each other,
// the values for left and right will be in
// opposing directions.
this.servos.right.to(right);
this.servos.left.to(left);
// Store a recallable history of movement
this.history.push({
timestamp: Date.now(),
right: right,
left: left
});
// Update the stored direction state
this.direction.right = right;
this.direction.left = left;
return this;
};
// TODO: DRY OUT!!!!!!!
/**
* forward Move the bot forward
* fwd Move the bot forward
*
* @param {Number}0-5, 0 is stopped, 5 is fastest
* @return {Object} this
*/
Navigator.prototype.forward = Navigator.prototype.fwd = function(speed) {
speed = speed == null ? 1 : speed;
var scaled = scale(speed, this.center, 110);
this.speed = speed;
this.which = "forward";
return this.to(this.center - (scaled - this.center), scaled);
};
/**
* reverse Move the bot in reverse
* rev Move the bot in reverse
*
* @param {Number}0-5, 0 is stopped, 5 is fastest
* @return {Object} this
*/
Navigator.prototype.reverse = Navigator.prototype.rev = function(speed) {
speed = speed == null ? 1 : speed;
var scaled = scale(speed, this.center, 110);
this.speed = speed;
this.which = "reverse";
console.log(scaled, this.center - (scaled - this.center));
return this.to(scaled, this.center - (scaled - this.center));
};
/**
* stop Stops the bot, regardless of current direction
* @return {Object} this
*/
Navigator.prototype.stop = function() {
this.speed = this.center;
this.which = "stop";
return this.to(this.center, this.center);
};
/**
* right Turn the bot right
* @return {Object} this
*/
/**
* left Turn the bot lefts
* @return {Object} this
*/
["right", "left"].forEach(function(dir) {
Navigator.prototype[dir] = function() {
var actual = this.direction[reverseDirMap[dir]];
if (!this.isTurning) {
this.isTurning = true;
this.to(actual, actual);
// Restore direction after turn
setTimeout(function() {
this[this.which](this.speed);
this.isTurning = false;
}.bind(this), 750);
}
return this;
};
});
expandWhich = function(which) {
var parts, translations;
translations = [{
f: "forward",
r: "reverse",
fwd: "forward",
rev: "reverse"
}, {
r: "right",
l: "left"
}];
if (which.length === 2) {
parts = [which[0], which[1]];
}
if (!parts.length && /\-/.test(which)) {
parts = which.split("-");
}
return parts.map(function(val, i) {
return translations[i][val];
}).join("-");
};
Navigator.prototype.pivot = function(which, time) {
var actual, directions, scaled;
scaled = scale(this.speed, this.center, 110);
which = expandWhich(which);
directions = {
"forward-right": function() {
this.to(this.center, scaled);
},
"forward-left": function() {
this.to(this.center - (scaled - this.center), this.center);
},
"reverse-right": function() {
this.to(scaled, this.center);
},
"reverse-left": function() {
this.to(this.center, this.center - (scaled - this.center));
}
};
directions[which].call(this, this.speed);
setTimeout(function() {
this[this.which](this.speed);
}.bind(this), time || 1000);
return this;
};
board = new five.Board();
board.on("ready", function() {
sonar = new five.Sonar({
pin: "A2",
freq: 100
});
sonar.on("change", function() {
console.log("Object is " + this.inches + "inches away");
});
scanner = new five.Servo(12);
scanner.sweep();
this.repl.inject({
// create a bot, right servo = pin 10, left servo = pin 11
b: new Navigator({
right: 10,
left: 11
})
});
});
|
/*
* jQuery MiniColors: A tiny color picker built on jQuery
*
* Copyright: Cory LaViska for A Beautiful Site, LLC.
*
* Contributions and bug reports: https://github.com/claviska/jquery-minicolors
*
* Licensed under the MIT license: http://opensource.org/licenses/MIT
*
*/
if(jQuery) (function($) {
// Defaults
$.minicolors = {
defaults: {
animationSpeed: 50,
animationEasing: 'swing',
change: null,
changeDelay: 0,
control: 'hue',
dataUris: true,
defaultValue: '',
hide: null,
hideSpeed: 100,
inline: false,
letterCase: 'lowercase',
opacity: false,
position: 'bottom left',
show: null,
showSpeed: 100,
theme: 'default'
}
};
// Public methods
$.extend($.fn, {
minicolors: function(method, data) {
switch(method) {
// Destroy the control
case 'destroy':
$(this).each( function() {
destroy($(this));
});
return $(this);
// Hide the color picker
case 'hide':
hide();
return $(this);
// Get/set opacity
case 'opacity':
// Getter
if( data === undefined ) {
// Getter
return $(this).attr('data-opacity');
} else {
// Setter
$(this).each( function() {
updateFromInput($(this).attr('data-opacity', data));
});
}
return $(this);
// Get an RGB(A) object based on the current color/opacity
case 'rgbObject':
return rgbObject($(this), method === 'rgbaObject');
// Get an RGB(A) string based on the current color/opacity
case 'rgbString':
case 'rgbaString':
return rgbString($(this), method === 'rgbaString');
// Get/set settings on the fly
case 'settings':
if( data === undefined ) {
return $(this).data('minicolors-settings');
} else {
// Setter
$(this).each( function() {
var settings = $(this).data('minicolors-settings') || {};
destroy($(this));
$(this).minicolors($.extend(true, settings, data));
});
}
return $(this);
// Show the color picker
case 'show':
show( $(this).eq(0) );
return $(this);
// Get/set the hex color value
case 'value':
if( data === undefined ) {
// Getter
return $(this).val();
} else {
// Setter
$(this).each( function() {
updateFromInput($(this).val(data));
});
}
return $(this);
// Initializes the control
default:
if( method !== 'create' ) data = method;
$(this).each( function() {
init($(this), data);
});
return $(this);
}
}
});
// Initialize input elements
function init(input, settings) {
var minicolors = $('<div class="minicolors" />'),
defaults = $.minicolors.defaults;
// Do nothing if already initialized
if( input.data('minicolors-initialized') ) return;
// Handle settings
settings = $.extend(true, {}, defaults, settings);
// The wrapper
minicolors
.addClass('minicolors-theme-' + settings.theme)
.toggleClass('minicolors-with-opacity', settings.opacity)
.toggleClass('minicolors-no-data-uris', settings.dataUris !== true);
// Custom positioning
if( settings.position !== undefined ) {
$.each(settings.position.split(' '), function() {
minicolors.addClass('minicolors-position-' + this);
});
}
// The input
input
.addClass('minicolors-input')
.data('minicolors-initialized', false)
.data('minicolors-settings', settings)
.prop('size', 7)
.wrap(minicolors)
.after(
'<div class="minicolors-panel minicolors-slider-' + settings.control + '">' +
'<div class="minicolors-slider minicolors-sprite">' +
'<div class="minicolors-picker"></div>' +
'</div>' +
'<div class="minicolors-opacity-slider minicolors-sprite">' +
'<div class="minicolors-picker"></div>' +
'</div>' +
'<div class="minicolors-grid minicolors-sprite">' +
'<div class="minicolors-grid-inner"></div>' +
'<div class="minicolors-picker"><div></div></div>' +
'</div>' +
'</div>'
);
// The swatch
if( !settings.inline ) {
input.after('<span class="minicolors-swatch minicolors-sprite"><span class="minicolors-swatch-color"></span></span>');
input.next('.minicolors-swatch').on('click', function(event) {
event.preventDefault();
input.focus();
});
}
// Prevent text selection in IE
input.parent().find('.minicolors-panel').on('selectstart', function() { return false; }).end();
// Inline controls
if( settings.inline ) input.parent().addClass('minicolors-inline');
updateFromInput(input, false);
input.data('minicolors-initialized', true);
}
// Returns the input back to its original state
function destroy(input) {
var minicolors = input.parent();
// Revert the input element
input
.removeData('minicolors-initialized')
.removeData('minicolors-settings')
.removeProp('size')
.removeClass('minicolors-input');
// Remove the wrap and destroy whatever remains
minicolors.before(input).remove();
}
// Shows the specified dropdown panel
function show(input) {
var minicolors = input.parent(),
panel = minicolors.find('.minicolors-panel'),
settings = input.data('minicolors-settings');
// Do nothing if uninitialized, disabled, inline, or already open
if( !input.data('minicolors-initialized') ||
input.prop('disabled') ||
minicolors.hasClass('minicolors-inline') ||
minicolors.hasClass('minicolors-focus')
) return;
hide();
minicolors.addClass('minicolors-focus');
panel
.stop(true, true)
.fadeIn(settings.showSpeed, function() {
if( settings.show ) settings.show.call(input.get(0));
});
}
// Hides all dropdown panels
function hide() {
$('.minicolors-focus').each( function() {
var minicolors = $(this),
input = minicolors.find('.minicolors-input'),
panel = minicolors.find('.minicolors-panel'),
settings = input.data('minicolors-settings');
panel.fadeOut(settings.hideSpeed, function() {
if( settings.hide ) settings.hide.call(input.get(0));
minicolors.removeClass('minicolors-focus');
});
});
}
// Moves the selected picker
function move(target, event, animate) {
var input = target.parents('.minicolors').find('.minicolors-input'),
settings = input.data('minicolors-settings'),
picker = target.find('[class$=-picker]'),
offsetX = target.offset().left,
offsetY = target.offset().top,
x = Math.round(event.pageX - offsetX),
y = Math.round(event.pageY - offsetY),
duration = animate ? settings.animationSpeed : 0,
wx, wy, r, phi;
// Touch support
if( event.originalEvent.changedTouches ) {
x = event.originalEvent.changedTouches[0].pageX - offsetX;
y = event.originalEvent.changedTouches[0].pageY - offsetY;
}
// Constrain picker to its container
if( x < 0 ) x = 0;
if( y < 0 ) y = 0;
if( x > target.width() ) x = target.width();
if( y > target.height() ) y = target.height();
// Constrain color wheel values to the wheel
if( target.parent().is('.minicolors-slider-wheel') && picker.parent().is('.minicolors-grid') ) {
wx = 75 - x;
wy = 75 - y;
r = Math.sqrt(wx * wx + wy * wy);
phi = Math.atan2(wy, wx);
if( phi < 0 ) phi += Math.PI * 2;
if( r > 75 ) {
r = 75;
x = 75 - (75 * Math.cos(phi));
y = 75 - (75 * Math.sin(phi));
}
x = Math.round(x);
y = Math.round(y);
}
// Move the picker
if( target.is('.minicolors-grid') ) {
picker
.stop(true)
.animate({
top: y + 'px',
left: x + 'px'
}, duration, settings.animationEasing, function() {
updateFromControl(input, target);
});
} else {
picker
.stop(true)
.animate({
top: y + 'px'
}, duration, settings.animationEasing, function() {
updateFromControl(input, target);
});
}
}
// Sets the input based on the color picker values
function updateFromControl(input, target) {
function getCoords(picker, container) {
var left, top;
if( !picker.length || !container ) return null;
left = picker.offset().left;
top = picker.offset().top;
return {
x: left - container.offset().left + (picker.outerWidth() / 2),
y: top - container.offset().top + (picker.outerHeight() / 2)
};
}
var hue, saturation, brightness, x, y, r, phi,
hex = input.val(),
opacity = input.attr('data-opacity'),
// Helpful references
minicolors = input.parent(),
settings = input.data('minicolors-settings'),
swatch = minicolors.find('.minicolors-swatch'),
// Panel objects
grid = minicolors.find('.minicolors-grid'),
slider = minicolors.find('.minicolors-slider'),
opacitySlider = minicolors.find('.minicolors-opacity-slider'),
// Picker objects
gridPicker = grid.find('[class$=-picker]'),
sliderPicker = slider.find('[class$=-picker]'),
opacityPicker = opacitySlider.find('[class$=-picker]'),
// Picker positions
gridPos = getCoords(gridPicker, grid),
sliderPos = getCoords(sliderPicker, slider),
opacityPos = getCoords(opacityPicker, opacitySlider);
// Handle colors
if( target.is('.minicolors-grid, .minicolors-slider') ) {
// Determine HSB values
switch(settings.control) {
case 'wheel':
// Calculate hue, saturation, and brightness
x = (grid.width() / 2) - gridPos.x;
y = (grid.height() / 2) - gridPos.y;
r = Math.sqrt(x * x + y * y);
phi = Math.atan2(y, x);
if( phi < 0 ) phi += Math.PI * 2;
if( r > 75 ) {
r = 75;
gridPos.x = 69 - (75 * Math.cos(phi));
gridPos.y = 69 - (75 * Math.sin(phi));
}
saturation = keepWithin(r / 0.75, 0, 100);
hue = keepWithin(phi * 180 / Math.PI, 0, 360);
brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100);
hex = hsb2hex({
h: hue,
s: saturation,
b: brightness
});
// Update UI
slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 }));
break;
case 'saturation':
// Calculate hue, saturation, and brightness
hue = keepWithin(parseInt(gridPos.x * (360 / grid.width()), 10), 0, 360);
saturation = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100);
brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100);
hex = hsb2hex({
h: hue,
s: saturation,
b: brightness
});
// Update UI
slider.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: brightness }));
minicolors.find('.minicolors-grid-inner').css('opacity', saturation / 100);
break;
case 'brightness':
// Calculate hue, saturation, and brightness
hue = keepWithin(parseInt(gridPos.x * (360 / grid.width()), 10), 0, 360);
saturation = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100);
brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100);
hex = hsb2hex({
h: hue,
s: saturation,
b: brightness
});
// Update UI
slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 }));
minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (brightness / 100));
break;
default:
// Calculate hue, saturation, and brightness
hue = keepWithin(360 - parseInt(sliderPos.y * (360 / slider.height()), 10), 0, 360);
saturation = keepWithin(Math.floor(gridPos.x * (100 / grid.width())), 0, 100);
brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100);
hex = hsb2hex({
h: hue,
s: saturation,
b: brightness
});
// Update UI
grid.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: 100 }));
break;
}
// Adjust case
input.val( convertCase(hex, settings.letterCase) );
}
// Handle opacity
if( target.is('.minicolors-opacity-slider') ) {
if( settings.opacity ) {
opacity = parseFloat(1 - (opacityPos.y / opacitySlider.height())).toFixed(2);
} else {
opacity = 1;
}
if( settings.opacity ) input.attr('data-opacity', opacity);
}
// Set swatch color
swatch.find('SPAN').css({
backgroundColor: hex,
opacity: opacity
});
// Handle change event
doChange(input, hex, opacity);
}
// Sets the color picker values from the input
function updateFromInput(input, preserveInputValue) {
var hex,
hsb,
opacity,
x, y, r, phi,
// Helpful references
minicolors = input.parent(),
settings = input.data('minicolors-settings'),
swatch = minicolors.find('.minicolors-swatch'),
// Panel objects
grid = minicolors.find('.minicolors-grid'),
slider = minicolors.find('.minicolors-slider'),
opacitySlider = minicolors.find('.minicolors-opacity-slider'),
// Picker objects
gridPicker = grid.find('[class$=-picker]'),
sliderPicker = slider.find('[class$=-picker]'),
opacityPicker = opacitySlider.find('[class$=-picker]');
// Determine hex/HSB values
hex = convertCase(parseHex(input.val(), true), settings.letterCase);
if( !hex ){
hex = convertCase(parseHex(settings.defaultValue, true), settings.letterCase);
}
hsb = hex2hsb(hex);
// Update input value
if( !preserveInputValue ) input.val(hex);
// Determine opacity value
if( settings.opacity ) {
// Get from data-opacity attribute and keep within 0-1 range
opacity = input.attr('data-opacity') === '' ? 1 : keepWithin(parseFloat(input.attr('data-opacity')).toFixed(2), 0, 1);
if( isNaN(opacity) ) opacity = 1;
input.attr('data-opacity', opacity);
swatch.find('SPAN').css('opacity', opacity);
// Set opacity picker position
y = keepWithin(opacitySlider.height() - (opacitySlider.height() * opacity), 0, opacitySlider.height());
opacityPicker.css('top', y + 'px');
}
// Update swatch
swatch.find('SPAN').css('backgroundColor', hex);
// Determine picker locations
switch(settings.control) {
case 'wheel':
// Set grid position
r = keepWithin(Math.ceil(hsb.s * 0.75), 0, grid.height() / 2);
phi = hsb.h * Math.PI / 180;
x = keepWithin(75 - Math.cos(phi) * r, 0, grid.width());
y = keepWithin(75 - Math.sin(phi) * r, 0, grid.height());
gridPicker.css({
top: y + 'px',
left: x + 'px'
});
// Set slider position
y = 150 - (hsb.b / (100 / grid.height()));
if( hex === '' ) y = 0;
sliderPicker.css('top', y + 'px');
// Update panel color
slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 }));
break;
case 'saturation':
// Set grid position
x = keepWithin((5 * hsb.h) / 12, 0, 150);
y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height());
gridPicker.css({
top: y + 'px',
left: x + 'px'
});
// Set slider position
y = keepWithin(slider.height() - (hsb.s * (slider.height() / 100)), 0, slider.height());
sliderPicker.css('top', y + 'px');
// Update UI
slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: hsb.b }));
minicolors.find('.minicolors-grid-inner').css('opacity', hsb.s / 100);
break;
case 'brightness':
// Set grid position
x = keepWithin((5 * hsb.h) / 12, 0, 150);
y = keepWithin(grid.height() - Math.ceil(hsb.s / (100 / grid.height())), 0, grid.height());
gridPicker.css({
top: y + 'px',
left: x + 'px'
});
// Set slider position
y = keepWithin(slider.height() - (hsb.b * (slider.height() / 100)), 0, slider.height());
sliderPicker.css('top', y + 'px');
// Update UI
slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 }));
minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (hsb.b / 100));
break;
default:
// Set grid position
x = keepWithin(Math.ceil(hsb.s / (100 / grid.width())), 0, grid.width());
y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height());
gridPicker.css({
top: y + 'px',
left: x + 'px'
});
// Set slider position
y = keepWithin(slider.height() - (hsb.h / (360 / slider.height())), 0, slider.height());
sliderPicker.css('top', y + 'px');
// Update panel color
grid.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: 100 }));
break;
}
// Fire change event, but only if minicolors is fully initialized
if( input.data('minicolors-initialized') ) {
doChange(input, hex, opacity);
}
}
// Runs the change and changeDelay callbacks
function doChange(input, hex, opacity) {
var settings = input.data('minicolors-settings'),
lastChange = input.data('minicolors-lastChange');
// Only run if it actually changed
if( !lastChange || lastChange.hex !== hex || lastChange.opacity !== opacity ) {
// Remember last-changed value
input.data('minicolors-lastChange', {
hex: hex,
opacity: opacity
});
// Fire change event
if( settings.change ) {
if( settings.changeDelay ) {
// Call after a delay
clearTimeout(input.data('minicolors-changeTimeout'));
input.data('minicolors-changeTimeout', setTimeout( function() {
settings.change.call(input.get(0), hex, opacity);
}, settings.changeDelay));
} else {
// Call immediately
settings.change.call(input.get(0), hex, opacity);
}
}
input.trigger('change').trigger('input');
}
}
// Generates an RGB(A) object based on the input's value
function rgbObject(input) {
var hex = parseHex($(input).val(), true),
rgb = hex2rgb(hex),
opacity = $(input).attr('data-opacity');
if( !rgb ) return null;
if( opacity !== undefined ) $.extend(rgb, { a: parseFloat(opacity) });
return rgb;
}
// Genearates an RGB(A) string based on the input's value
function rgbString(input, alpha) {
var hex = parseHex($(input).val(), true),
rgb = hex2rgb(hex),
opacity = $(input).attr('data-opacity');
if( !rgb ) return null;
if( opacity === undefined ) opacity = 1;
if( alpha ) {
return 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + parseFloat(opacity) + ')';
} else {
return 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')';
}
}
// Converts to the letter case specified in settings
function convertCase(string, letterCase) {
return letterCase === 'uppercase' ? string.toUpperCase() : string.toLowerCase();
}
// Parses a string and returns a valid hex string when possible
function parseHex(string, expand) {
string = string.replace(/[^A-F0-9]/ig, '');
if( string.length !== 3 && string.length !== 6 ) return '';
if( string.length === 3 && expand ) {
string = string[0] + string[0] + string[1] + string[1] + string[2] + string[2];
}
return '#' + string;
}
// Keeps value within min and max
function keepWithin(value, min, max) {
if( value < min ) value = min;
if( value > max ) value = max;
return value;
}
// Converts an HSB object to an RGB object
function hsb2rgb(hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s * 255 / 100);
var v = Math.round(hsb.b * 255 / 100);
if(s === 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255 - s) * v / 255;
var t3 = (t1 - t2) * (h % 60) / 60;
if( h === 360 ) h = 0;
if( h < 60 ) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; }
else if( h < 120 ) {rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; }
else if( h < 180 ) {rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; }
else if( h < 240 ) {rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; }
else if( h < 300 ) {rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; }
else if( h < 360 ) {rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; }
else { rgb.r = 0; rgb.g = 0; rgb.b = 0; }
}
return {
r: Math.round(rgb.r),
g: Math.round(rgb.g),
b: Math.round(rgb.b)
};
}
// Converts an RGB object to a hex string
function rgb2hex(rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function(nr, val) {
if (val.length === 1) hex[nr] = '0' + val;
});
return '#' + hex.join('');
}
// Converts an HSB object to a hex string
function hsb2hex(hsb) {
return rgb2hex(hsb2rgb(hsb));
}
// Converts a hex string to an HSB object
function hex2hsb(hex) {
var hsb = rgb2hsb(hex2rgb(hex));
if( hsb.s === 0 ) hsb.h = 360;
return hsb;
}
// Converts an RGB object to an HSB object
function rgb2hsb(rgb) {
var hsb = { h: 0, s: 0, b: 0 };
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
hsb.s = max !== 0 ? 255 * delta / max : 0;
if( hsb.s !== 0 ) {
if( rgb.r === max ) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if( rgb.g === max ) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if( hsb.h < 0 ) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
}
// Converts a hex string to an RGB object
function hex2rgb(hex) {
hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {
/* jshint ignore:start */
r: hex >> 16,
g: (hex & 0x00FF00) >> 8,
b: (hex & 0x0000FF)
/* jshint ignore:end */
};
}
// Handle events
$(document)
// Hide on clicks outside of the control
.on('mousedown.minicolors touchstart.minicolors', function(event) {
if( !$(event.target).parents().add(event.target).hasClass('minicolors') ) {
hide();
}
})
// Start moving
.on('mousedown.minicolors touchstart.minicolors', '.minicolors-grid, .minicolors-slider, .minicolors-opacity-slider', function(event) {
var target = $(this);
event.preventDefault();
$(document).data('minicolors-target', target);
move(target, event, true);
})
// Move pickers
.on('mousemove.minicolors touchmove.minicolors', function(event) {
var target = $(document).data('minicolors-target');
if( target ) move(target, event);
})
// Stop moving
.on('mouseup.minicolors touchend.minicolors', function() {
$(this).removeData('minicolors-target');
})
// Show panel when swatch is clicked
.on('mousedown.minicolors touchstart.minicolors', '.minicolors-swatch', function(event) {
var input = $(this).parent().find('.minicolors-input');
event.preventDefault();
show(input);
})
// Show on focus
.on('focus.minicolors', '.minicolors-input', function() {
var input = $(this);
if( !input.data('minicolors-initialized') ) return;
show(input);
})
// Fix hex on blur
.on('blur.minicolors', '.minicolors-input', function() {
var input = $(this),
settings = input.data('minicolors-settings');
if( !input.data('minicolors-initialized') ) return;
// Parse Hex
input.val(parseHex(input.val(), true));
// Is it blank?
if( input.val() === '' ) input.val(parseHex(settings.defaultValue, true));
// Adjust case
input.val( convertCase(input.val(), settings.letterCase) );
})
// Handle keypresses
.on('keydown.minicolors', '.minicolors-input', function(event) {
var input = $(this);
if( !input.data('minicolors-initialized') ) return;
switch(event.keyCode) {
case 9: // tab
hide();
break;
case 13: // enter
case 27: // esc
hide();
input.blur();
break;
}
})
// Update on keyup
.on('keyup.minicolors', '.minicolors-input', function() {
var input = $(this);
if( !input.data('minicolors-initialized') ) return;
updateFromInput(input, true);
})
// Update on paste
.on('paste.minicolors', '.minicolors-input', function() {
var input = $(this);
if( !input.data('minicolors-initialized') ) return;
setTimeout( function() {
updateFromInput(input, true);
}, 1);
});
})(jQuery);
|
(function (global) {
var babelHelpers = global.babelHelpers = {};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
};
babelHelpers.interopRequireWildcard = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
};
})(typeof global === "undefined" ? self : global);(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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';
/**
* MUI Angular main module
* @module angular/main
*/
(function (win) {
// return if library has been loaded already
if (win._muiAngularLoaded) return;else win._muiAngularLoaded = true;
win.angular.module('mui', [require('src/angular/appbar'), require('src/angular/button'), require('src/angular/caret'), require('src/angular/container'), require('src/angular/divider'), require('src/angular/dropdown'), require('src/angular/dropdown-item'), require('src/angular/panel'), require('src/angular/input'), require('src/angular/row'), require('src/angular/col'), require('src/angular/tabs'), require('src/angular/radio'), require('src/angular/checkbox'), require('src/angular/select'), require('src/angular/form')]);
})(window);
},{"src/angular/appbar":6,"src/angular/button":7,"src/angular/caret":8,"src/angular/checkbox":9,"src/angular/col":10,"src/angular/container":11,"src/angular/divider":12,"src/angular/dropdown":14,"src/angular/dropdown-item":13,"src/angular/form":15,"src/angular/input":16,"src/angular/panel":17,"src/angular/radio":18,"src/angular/row":19,"src/angular/select":20,"src/angular/tabs":21}],2:[function(require,module,exports){
"use strict";
/**
* MUI config module
* @module config
*/
/** Define module API */
module.exports = {
/** Use debug mode */
debug: true
};
},{}],3:[function(require,module,exports){
/**
* MUI CSS/JS form helpers module
* @module lib/forms.py
*/
'use strict';
var wrapperPadding = 15,
// from CSS
inputHeight = 32,
// from CSS
optionHeight = 42,
// from CSS
menuPadding = 8; // from CSS
/**
* Menu position/size/scroll helper
* @returns {Object} Object with keys 'height', 'top', 'scrollTop'
*/
function getMenuPositionalCSSFn(wrapperEl, numOptions, currentIndex) {
var viewHeight = document.documentElement.clientHeight;
// determine 'height'
var h = numOptions * optionHeight + 2 * menuPadding,
height = Math.min(h, viewHeight);
// determine 'top'
var top, initTop, minTop, maxTop;
initTop = menuPadding + optionHeight - (wrapperPadding + inputHeight);
initTop -= currentIndex * optionHeight;
minTop = -1 * wrapperEl.getBoundingClientRect().top;
maxTop = viewHeight - height + minTop;
top = Math.min(Math.max(initTop, minTop), maxTop);
// determine 'scrollTop'
var scrollTop = 0,
scrollIdeal,
scrollMax;
if (h > viewHeight) {
scrollIdeal = menuPadding + (currentIndex + 1) * optionHeight - (-1 * top + wrapperPadding + inputHeight);
scrollMax = numOptions * optionHeight + 2 * menuPadding - height;
scrollTop = Math.min(scrollIdeal, scrollMax);
}
return {
'height': height + 'px',
'top': top + 'px',
'scrollTop': scrollTop
};
}
/** Define module API */
module.exports = {
getMenuPositionalCSS: getMenuPositionalCSSFn
};
},{}],4:[function(require,module,exports){
/**
* MUI CSS/JS jqLite module
* @module lib/jqLite
*/
'use strict';
/**
* Add a class to an element.
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteAddClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i = 0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
}
element.setAttribute('class', existingClasses.trim());
}
/**
* Get or set CSS properties.
* @param {Element} element - The DOM element.
* @param {string} [name] - The property name.
* @param {string} [value] - The property value.
*/
function jqLiteCss(element, name, value) {
// Return full style object
if (name === undefined) {
return getComputedStyle(element);
}
var nameType = jqLiteType(name);
// Set multiple values
if (nameType === 'object') {
for (var key in name) {
element.style[_camelCase(key)] = name[key];
}return;
}
// Set a single value
if (nameType === 'string' && value !== undefined) {
element.style[_camelCase(name)] = value;
}
var styleObj = getComputedStyle(element),
isArray = jqLiteType(name) === 'array';
// Read single value
if (!isArray) return _getCurrCssProp(element, name, styleObj);
// Read multiple values
var outObj = {},
key;
for (var i = 0; i < name.length; i++) {
key = name[i];
outObj[key] = _getCurrCssProp(element, key, styleObj);
}
return outObj;
}
/**
* Check if element has class.
* @param {Element} element - The DOM element.
* @param {string} cls - The class name string.
*/
function jqLiteHasClass(element, cls) {
if (!cls || !element.getAttribute) return false;
return _getExistingClasses(element).indexOf(' ' + cls + ' ') > -1;
}
/**
* Return the type of a variable.
* @param {} somevar - The JavaScript variable.
*/
function jqLiteType(somevar) {
// handle undefined
if (somevar === undefined) return 'undefined';
// handle others (of type [object <Type>])
var typeStr = Object.prototype.toString.call(somevar);
if (typeStr.indexOf('[object ') === 0) {
return typeStr.slice(8, -1).toLowerCase();
} else {
throw new Error("MUI: Could not understand type: " + typeStr);
}
}
/**
* Attach an event handler to a DOM element
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOn(element, events, callback, useCapture) {
useCapture = useCapture === undefined ? false : useCapture;
var cache = element._muiEventCache = element._muiEventCache || {};
events.split(' ').map(function (event) {
// add to DOM
element.addEventListener(event, callback, useCapture);
// add to cache
cache[event] = cache[event] || [];
cache[event].push([callback, useCapture]);
});
}
/**
* Remove an event handler from a DOM element
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOff(element, events, callback, useCapture) {
useCapture = useCapture === undefined ? false : useCapture;
// remove from cache
var cache = element._muiEventCache = element._muiEventCache || {},
argsList,
args,
i;
events.split(' ').map(function (event) {
argsList = cache[event] || [];
i = argsList.length;
while (i--) {
args = argsList[i];
// remove all events if callback is undefined
if (callback === undefined || args[0] === callback && args[1] === useCapture) {
// remove from cache
argsList.splice(i, 1);
// remove from DOM
element.removeEventListener(event, args[0], args[1]);
}
}
});
}
/**
* Attach an event hander which will only execute once per element per event
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOne(element, events, callback, useCapture) {
events.split(' ').map(function (event) {
jqLiteOn(element, event, function onFn(ev) {
// execute callback
if (callback) callback.apply(this, arguments);
// remove wrapper
jqLiteOff(element, event, onFn);
}, useCapture);
});
}
/**
* Get or set horizontal scroll position
* @param {Element} element - The DOM element
* @param {number} [value] - The scroll position
*/
function jqLiteScrollLeft(element, value) {
var win = window;
// get
if (value === undefined) {
if (element === win) {
var docEl = document.documentElement;
return (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0);
} else {
return element.scrollLeft;
}
}
// set
if (element === win) win.scrollTo(value, jqLiteScrollTop(win));else element.scrollLeft = value;
}
/**
* Get or set vertical scroll position
* @param {Element} element - The DOM element
* @param {number} value - The scroll position
*/
function jqLiteScrollTop(element, value) {
var win = window;
// get
if (value === undefined) {
if (element === win) {
var docEl = document.documentElement;
return (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0);
} else {
return element.scrollTop;
}
}
// set
if (element === win) win.scrollTo(jqLiteScrollLeft(win), value);else element.scrollTop = value;
}
/**
* Return object representing top/left offset and element height/width.
* @param {Element} element - The DOM element.
*/
function jqLiteOffset(element) {
var win = window,
rect = element.getBoundingClientRect(),
scrollTop = jqLiteScrollTop(win),
scrollLeft = jqLiteScrollLeft(win);
return {
top: rect.top + scrollTop,
left: rect.left + scrollLeft,
height: rect.height,
width: rect.width
};
}
/**
* Attach a callback to the DOM ready event listener
* @param {Function} fn - The callback function.
*/
function jqLiteReady(fn) {
var done = false,
top = true,
doc = document,
win = doc.defaultView,
root = doc.documentElement,
add = doc.addEventListener ? 'addEventListener' : 'attachEvent',
rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent',
pre = doc.addEventListener ? '' : 'on';
var init = function init(e) {
if (e.type == 'readystatechange' && doc.readyState != 'complete') {
return;
}
(e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
};
var poll = function poll() {
try {
root.doScroll('left');
} catch (e) {
setTimeout(poll, 50);return;
}
init('poll');
};
if (doc.readyState == 'complete') {
fn.call(win, 'lazy');
} else {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (e) {}
if (top) poll();
}
doc[add](pre + 'DOMContentLoaded', init, false);
doc[add](pre + 'readystatechange', init, false);
win[add](pre + 'load', init, false);
}
}
/**
* Remove classes from a DOM element
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteRemoveClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i = 0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) {
existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' ');
}
}
element.setAttribute('class', existingClasses.trim());
}
// ------------------------------
// Utilities
// ------------------------------
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g,
MOZ_HACK_REGEXP = /^moz([A-Z])/,
ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g,
BOOLEAN_ATTRS;
BOOLEAN_ATTRS = {
multiple: true,
selected: true,
checked: true,
disabled: true,
readonly: true,
required: true,
open: true
};
function _getExistingClasses(element) {
var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, '');
return ' ' + classes + ' ';
}
function _camelCase(name) {
return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).replace(MOZ_HACK_REGEXP, 'Moz$1');
}
function _escapeRegExp(string) {
return string.replace(ESCAPE_REGEXP, "\\$1");
}
function _getCurrCssProp(elem, name, computed) {
var ret;
// try computed style
ret = computed.getPropertyValue(name);
// try style attribute (if element is not attached to document)
if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)];
return ret;
}
/**
* Module API
*/
module.exports = {
/** Add classes */
addClass: jqLiteAddClass,
/** Get or set CSS properties */
css: jqLiteCss,
/** Check for class */
hasClass: jqLiteHasClass,
/** Remove event handlers */
off: jqLiteOff,
/** Return offset values */
offset: jqLiteOffset,
/** Add event handlers */
on: jqLiteOn,
/** Add an execute-once event handler */
one: jqLiteOne,
/** DOM ready event handler */
ready: jqLiteReady,
/** Remove classes */
removeClass: jqLiteRemoveClass,
/** Check JavaScript variable instance type */
type: jqLiteType,
/** Get or set horizontal scroll position */
scrollLeft: jqLiteScrollLeft,
/** Get or set vertical scroll position */
scrollTop: jqLiteScrollTop
};
},{}],5:[function(require,module,exports){
/**
* MUI CSS/JS utilities module
* @module lib/util
*/
'use strict';
var config = require('../config'),
jqLite = require('./jqLite'),
nodeInsertedCallbacks = [],
scrollLock = 0,
scrollLockCls = 'mui-body--scroll-lock',
scrollLockPos,
_supportsPointerEvents;
/**
* Logging function
*/
function logFn() {
var win = window;
if (config.debug && typeof win.console !== "undefined") {
try {
win.console.log.apply(win.console, arguments);
} catch (a) {
var e = Array.prototype.slice.call(arguments);
win.console.log(e.join("\n"));
}
}
}
/**
* Load CSS text in new stylesheet
* @param {string} cssText - The css text.
*/
function loadStyleFn(cssText) {
var doc = document,
head;
// copied from jQuery
head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement;
var e = doc.createElement('style');
e.type = 'text/css';
if (e.styleSheet) e.styleSheet.cssText = cssText;else e.appendChild(doc.createTextNode(cssText));
// add to document
head.insertBefore(e, head.firstChild);
return e;
}
/**
* Raise an error
* @param {string} msg - The error message.
*/
function raiseErrorFn(msg, useConsole) {
if (useConsole) {
if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg);
} else {
throw new Error('MUI: ' + msg);
}
}
/**
* Register callbacks on muiNodeInserted event
* @param {function} callbackFn - The callback function.
*/
function onNodeInsertedFn(callbackFn) {
nodeInsertedCallbacks.push(callbackFn);
// initalize listeners
if (nodeInsertedCallbacks._initialized === undefined) {
var doc = document,
events = 'animationstart mozAnimationStart webkitAnimationStart';
jqLite.on(doc, events, animationHandlerFn);
nodeInsertedCallbacks._initialized = true;
}
}
/**
* Execute muiNodeInserted callbacks
* @param {Event} ev - The DOM event.
*/
function animationHandlerFn(ev) {
// check animation name
if (ev.animationName !== 'mui-node-inserted') return;
var el = ev.target;
// iterate through callbacks
for (var i = nodeInsertedCallbacks.length - 1; i >= 0; i--) {
nodeInsertedCallbacks[i](el);
}
}
/**
* Convert Classname object, with class as key and true/false as value, to an
* class string.
* @param {Object} classes The classes
* @return {String} class string
*/
function classNamesFn(classes) {
var cs = '';
for (var i in classes) {
cs += classes[i] ? i + ' ' : '';
}
return cs.trim();
}
/**
* Check if client supports pointer events.
*/
function supportsPointerEventsFn() {
// check cache
if (_supportsPointerEvents !== undefined) return _supportsPointerEvents;
var element = document.createElement('x');
element.style.cssText = 'pointer-events:auto';
_supportsPointerEvents = element.style.pointerEvents === 'auto';
return _supportsPointerEvents;
}
/**
* Create callback closure.
* @param {Object} instance - The object instance.
* @param {String} funcName - The name of the callback function.
*/
function callbackFn(instance, funcName) {
return function () {
instance[funcName].apply(instance, arguments);
};
}
/**
* Dispatch event.
* @param {Element} element - The DOM element.
* @param {String} eventType - The event type.
* @param {Boolean} bubbles=true - If true, event bubbles.
* @param {Boolean} cancelable=true = If true, event is cancelable
* @param {Object} [data] - Data to add to event object
*/
function dispatchEventFn(element, eventType, bubbles, cancelable, data) {
var ev = document.createEvent('HTMLEvents'),
bubbles = bubbles !== undefined ? bubbles : true,
cancelable = cancelable !== undefined ? cancelable : true,
k;
ev.initEvent(eventType, bubbles, cancelable);
// add data to event object
if (data) for (k in data) {
ev[k] = data[k];
} // dispatch
if (element) element.dispatchEvent(ev);
return ev;
}
/**
* Turn on window scroll lock.
*/
function enableScrollLockFn() {
// increment counter
scrollLock += 1;
// add lock
if (scrollLock === 1) {
var win = window,
doc = document;
scrollLockPos = { left: jqLite.scrollLeft(win), top: jqLite.scrollTop(win) };
jqLite.addClass(doc.body, scrollLockCls);
win.scrollTo(scrollLockPos.left, scrollLockPos.top);
}
}
/**
* Turn off window scroll lock.
*/
function disableScrollLockFn() {
// ignore
if (scrollLock === 0) return;
// decrement counter
scrollLock -= 1;
// remove lock
if (scrollLock === 0) {
var win = window,
doc = document;
jqLite.removeClass(doc.body, scrollLockCls);
win.scrollTo(scrollLockPos.left, scrollLockPos.top);
}
}
/**
* requestAnimationFrame polyfilled
* @param {Function} callback - The callback function
*/
function requestAnimationFrameFn(callback) {
var fn = window.requestAnimationFrame;
if (fn) fn(callback);else setTimeout(callback, 0);
}
/**
* Define the module API
*/
module.exports = {
/** Create callback closures */
callback: callbackFn,
/** Classnames object to string */
classNames: classNamesFn,
/** Disable scroll lock */
disableScrollLock: disableScrollLockFn,
/** Dispatch event */
dispatchEvent: dispatchEventFn,
/** Enable scroll lock */
enableScrollLock: enableScrollLockFn,
/** Log messages to the console when debug is turned on */
log: logFn,
/** Load CSS text as new stylesheet */
loadStyle: loadStyleFn,
/** Register muiNodeInserted handler */
onNodeInserted: onNodeInsertedFn,
/** Raise MUI error */
raiseError: raiseErrorFn,
/** Request animation frame */
requestAnimationFrame: requestAnimationFrameFn,
/** Support Pointer Events check */
supportsPointerEvents: supportsPointerEventsFn
};
},{"../config":2,"./jqLite":4}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.appbar'; /**
* MUI Angular Appbar Component
* @module angular/appbar
*/
_angular2.default.module(moduleName, []).directive('muiAppbar', function () {
return {
restrict: 'AE',
transclude: true,
replace: true,
template: '<div class="mui-appbar"></div>',
link: function link(scope, element, attrs, controller, transcludeFn) {
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function (clone) {
element.append(clone);
});
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],7:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var _jqLite = require('../js/lib/jqLite');
var jqLite = babelHelpers.interopRequireWildcard(_jqLite);
/**
* MUI Angular Button Component
* @module angular/button
*/
var moduleName = 'mui.button',
rippleClass = 'mui-ripple-effect',
supportsTouch = 'ontouchstart' in document.documentElement,
mouseDownEvents = supportsTouch ? 'touchstart' : 'mousedown',
mouseUpEvents = supportsTouch ? 'touchend' : 'mouseup mouseleave',
animationDuration = 600;
_angular2.default.module(moduleName, []).directive('muiButton', function () {
return {
restrict: 'AE',
scope: {
type: '@?'
},
replace: true,
template: '<button class="mui-btn" type={{type}} mui-ripple ng-transclude></button>',
transclude: true,
link: function link(scope, element, attrs) {
var isUndef = _angular2.default.isUndefined,
el = element[0];
// disable MUI js
el._muiDropdown = true;
el._muiRipple = true;
// handle disabled attribute
if (!isUndef(attrs.disabled) && isUndef(attrs.ngDisabled)) {
element.prop('disabled', true);
}
// set button styles
_angular2.default.forEach(['variant', 'color', 'size'], function (attrName) {
var attrVal = attrs[attrName];
if (attrVal) element.addClass('mui-btn--' + attrVal);
});
}
};
}).directive('muiRipple', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function link(scope, element, attrs) {
// add mousedown event handler
element.on(mouseDownEvents, mouseDownHandler);
}
};
}]);
/**
* MouseDown event handler.
* @param {Event} ev - The DOM event
*/
function mouseDownHandler(ev) {
var element = _angular2.default.element(this);
// exit if disabled
if (element.prop('disabled')) return;
// add mouseup event handler once
if (!this.muiMouseUp) {
element.on(mouseUpEvents, mouseUpHandler);
this.muiMouseUp = true;
}
// get (x, y) position of click
var offset = jqLite.offset(this),
clickEv = ev.type === 'touchstart' ? ev.touches[0] : ev,
xPos = clickEv.pageX - offset.left,
yPos = clickEv.pageY - offset.top,
diameter,
radius,
rippleEl;
// choose diameter
diameter = offset.height;
if (element.hasClass('mui-btn--fab')) diameter = offset.height / 2;
// create ripple element
rippleEl = _angular2.default.element('<div class="' + rippleClass + '"></div>');
radius = diameter / 2;
rippleEl.css({
height: diameter + 'px',
width: diameter + 'px',
top: yPos - radius + 'px',
left: xPos - radius + 'px'
});
// add to DOM
element.append(rippleEl);
// start animation
util.requestAnimationFrame(function () {
rippleEl.addClass('mui--animate-in mui--active');
});
}
/**
* MouseUp event handler.
* @param {Event} ev - The DOM event
*/
function mouseUpHandler(ev) {
var children = this.children,
i = children.length,
rippleEls = [],
el;
// animate out ripples
while (i--) {
el = children[i];
if (jqLite.hasClass(el, rippleClass)) {
jqLite.addClass(el, 'mui--animate-out');
rippleEls.push(el);
}
}
// remove ripples after animation
if (rippleEls.length) {
setTimeout(function () {
var i = rippleEls.length,
el,
parentNode;
// remove elements
while (i--) {
el = rippleEls[i];
parentNode = el.parentNode;
if (parentNode) parentNode.removeChild(el);
}
}, animationDuration);
}
}
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"../js/lib/jqLite":4,"angular":"aeQg5j"}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.caret'; /**
* MUI Angular Caret Component
* @module angular/caret
*/
_angular2.default.module(moduleName, []).directive('muiCaret', function () {
return {
restrict: 'AE',
replace: true,
template: '<span class="mui-caret"></span>'
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.checkbox'; /**
* MUI Angular Checkbox Component
* @module angular/checkox
*/
_angular2.default.module(moduleName, []).directive('muiCheckbox', function () {
return {
restrict: 'AE',
replace: true,
require: ['?ngModel'],
scope: {
label: '@',
name: '@',
value: '@',
ngModel: '=',
ngDisabled: '='
},
template: '<div class="mui-checkbox">' + '<label>' + '<input type="checkbox" ' + 'name={{name}} ' + 'value={{value}} ' + 'ng-model="ngModel" ' + 'ng-disabled="ngDisabled" ' + '>{{label}}</label> ' + '</div>'
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.col'; /**
* MUI Angular Col (Grid) Component
* @module angular/col
*/
_angular2.default.module(moduleName, []).directive('muiCol', function () {
return {
restrict: 'AE',
scope: true,
replace: true,
template: '<div></div>',
transclude: true,
link: function link(scope, element, attrs, controller, transcludeFn) {
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function (clone) {
element.append(clone);
});
// iterate through breakpoints
var breakpoints = {
'xs': 'mui-col-xs-',
'sm': 'mui-col-sm-',
'md': 'mui-col-md-',
'lg': 'mui-col-lg-',
'xs-offset': 'mui-col-xs-offset-',
'sm-offset': 'mui-col-sm-offset-',
'md-offset': 'mui-col-md-offset-',
'lg-offset': 'mui-col-lg-offset-'
};
_angular2.default.forEach(breakpoints, function (value, key) {
var attrVal = attrs[attrs.$normalize(key)];
if (attrVal) element.addClass(value + attrVal);
});
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],11:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.container'; /**
* MUI Angular Container Component
* @module angular/container
*/
_angular2.default.module(moduleName, []).directive('muiContainer', function () {
return {
restrict: 'AE',
template: '<div class="mui-container"></div>',
transclude: true,
scope: true,
replace: true,
link: function link(scope, element, attrs, controller, transcludeFn) {
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function (clone) {
element.append(clone);
});
// handle fluid containers
if (!_angular2.default.isUndefined(attrs.fluid)) {
element.removeClass('mui-container').addClass('mui-container-fluid');
}
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.divider'; /**
* MUI Angular Divider Component
* @module angular/divider
*/
_angular2.default.module(moduleName, []).directive('muiDivider', function () {
return {
restrict: 'AE',
replace: true,
compile: function compile(tElement, tAttrs) {
tElement.addClass('mui-divider');
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.dropdown-item'; /**
* MUI Angular DropdownItem Component
* @module angular/dropdown-item
*/
_angular2.default.module(moduleName, []).directive('muiDropdownItem', function () {
return {
restrict: 'AE',
replace: true,
scope: {
link: '@'
},
transclude: true,
template: '<li><a href="{{link}}" ng-transclude></a></li>'
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.dropdown'; /**
* MUI Angular Dropdown Component
* @module angular/dropdown
*/
_angular2.default.module(moduleName, []).directive('muiDropdown', ['$timeout', '$compile', function ($timeout, $compile) {
return {
restrict: 'AE',
transclude: true,
replace: true,
scope: {
variant: '@',
color: '@',
size: '@',
open: '=?',
ngDisabled: '='
},
template: '<div class="mui-dropdown">' + '<mui-button ' + 'variant="{{variant}}" ' + 'color="{{color}}" ' + 'size="{{size}}" ' + 'ng-click="onClick($event);" ' + '></mui-button>' + '<ul class="mui-dropdown__menu" ng-transclude></ul>' + '</div>',
link: function link(scope, element, attrs) {
var dropdownClass = 'mui-dropdown',
menuClass = 'mui-dropdown__menu',
openClass = 'mui--is-open',
rightClass = 'mui-dropdown__menu--right',
isUndef = _angular2.default.isUndefined,
menuEl,
buttonEl;
// save references
menuEl = _angular2.default.element(element[0].querySelector('.' + menuClass));
buttonEl = _angular2.default.element(element[0].querySelector('.mui-btn'));
menuEl.css('margin-top', '-3px');
// handle is-open
if (!isUndef(attrs.open)) scope.open = true;
// handle disabled
if (!isUndef(attrs.disabled)) {
buttonEl.attr('disabled', true);
}
// handle right-align
if (!isUndef(attrs.rightAlign)) menuEl.addClass(rightClass);
// handle no-caret
if (!isUndef(attrs.noCaret)) buttonEl.html(attrs.label);else buttonEl.html(attrs.label + ' <mui-caret></mui-caret>');
function closeDropdownFn() {
scope.open = false;
scope.$apply();
}
// handle menu open
scope.$watch('open', function (newValue) {
if (newValue === true) {
menuEl.addClass(openClass);
document.addEventListener('click', closeDropdownFn);
} else if (newValue === false) {
menuEl.removeClass(openClass);
document.removeEventListener('click', closeDropdownFn);
}
});
// click handler
scope.onClick = function ($event) {
// exit if disabled
if (scope.disabled) return;
// prevent form submission
$event.preventDefault();
$event.stopPropagation();
// toggle open
if (scope.open) scope.open = false;else scope.open = true;
};
}
};
}]);
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.form'; /**
* MUI Angular Form Directive
* @module angular/form
*/
_angular2.default.module(moduleName, []).directive('muiFormInline', function () {
return {
restrict: 'A',
link: function link(scope, element, attrs) {
element.addClass('mui-form--inline');
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.input',
emptyClass = 'mui--is-empty',
notEmptyClass = 'mui--is-not-empty',
dirtyClass = 'mui--is-dirty';
/**
* Handle empty/not-empty/dirty classes.
* @param {Element} elem - The angular-wrapped DOM element.
*/
/**
* MUI Angular Input and Textarea Components
* @module angular/input
*/
function handleEmptyClasses(inputEl, value) {
if (value) inputEl.removeClass(emptyClass).addClass(notEmptyClass);else inputEl.removeClass(notEmptyClass).addClass(emptyClass);
}
/**
* Build directive function.
* @param {Boolean} isTextArea
*/
function inputFactory(isTextArea) {
var emptyClass = 'mui--is-empty',
notEmptyClass = 'mui--is-not-empty',
dirtyClass = 'mui--is-dirty',
scopeArgs,
template;
// defaults
scopeArgs = {
floatLabel: '@',
hint: '@',
label: '@',
ngDisabled: '=',
ngModel: '='
};
template = '<div class="mui-textfield">';
// element-specific
if (!isTextArea) {
scopeArgs.type = '@';
template += '<input ' + 'placeholder={{hint}} ' + 'type={{type}} ' + 'ng-change="onChange()" ' + 'ng-disabled="ngDisabled" ' + 'ng-focus="onFocus()" ' + 'ng-model="ngModel" ' + '>';
} else {
scopeArgs.rows = '@';
template += '<textarea ' + 'placeholder={{hint}} ' + 'rows={{rows}} ' + 'ng-change="onChange()" ' + 'ng-disabled="ngDisabled" ' + 'ng-focus="onFocus()" ' + 'ng-model="ngModel" ' + '></textarea>';
}
// update template
template += '<label>{{label}}</label></div>';
// directive function
return ['$timeout', function ($timeout) {
return {
restrict: 'AE',
require: ['ngModel'],
scope: scopeArgs,
replace: true,
template: template,
link: function link(scope, element, attrs, controllers) {
var inputEl = element.find('input') || element.find('textarea'),
labelEl = element.find('label'),
ngModelCtrl = controllers[0],
formCtrl = controllers[1],
isUndef = _angular2.default.isUndefined,
el = inputEl[0];
// disable MUI js
if (el) el._muiTextfield = true;
// remove attributes from wrapper
element.removeAttr('ng-change');
element.removeAttr('ng-model');
// scope defaults
if (!isTextArea) scope.type = scope.type || 'text';else scope.rows = scope.rows || 2;
// autofocus
if (!isUndef(attrs.autofocus)) inputEl[0].focus();
// required
if (!isUndef(attrs.required)) inputEl.prop('required', true);
// invalid
if (!isUndef(attrs.invalid)) inputEl.addClass('mui--is-invalid');
// set is-empty|is-no-empty
handleEmptyClasses(inputEl, scope.ngModel);
// float-label
if (!isUndef(scope.floatLabel)) {
element.addClass('mui-textfield--float-label');
$timeout(function () {
labelEl.css({
'transition': '.15s ease-out',
'-webkit-transition': '.15s ease-out',
'-moz-transition': '.15s ease-out',
'-o-transition': '.15s ease-out',
'-ms-transition': '.15s ease-out'
});
}, 150);
}
// handle changes
scope.onChange = function () {
var val = scope.ngModel;
// trigger ng-change
if (ngModelCtrl) ngModelCtrl.$setViewValue(val);
// set is-empty|is-no-empty
handleEmptyClasses(inputEl, val);
// add is-dirty
inputEl.addClass(dirtyClass);
};
// handle focus event
scope.onFocus = function () {
inputEl.addClass(dirtyClass);
};
}
};
}];
}
_angular2.default.module(moduleName, []).directive('muiInput', inputFactory(false)).directive('muiTextarea', inputFactory(true));
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.panel'; /**
* MUI Angular Panel Component
* @module angular/panel
*/
_angular2.default.module(moduleName, []).directive('muiPanel', function () {
return {
restrict: 'AE',
replace: true,
scope: true,
template: '<div class="mui-panel"></div>',
transclude: true,
link: function link(scope, element, attr, controller, transcludeFn) {
transcludeFn(scope, function (clone) {
element.append(clone);
});
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.radio'; /**
* MUI Angular Radio Component
* @module angular/radio
*/
_angular2.default.module(moduleName, []).directive('muiRadio', function () {
return {
restrict: 'AE',
replace: true,
require: ['?ngModel'],
scope: {
label: '@',
name: '@',
value: '@',
ngModel: '=',
ngDisabled: '='
},
template: '<div class="mui-radio">' + '<label>' + '<input type="radio" ' + 'name={{name}} ' + 'value={{value}} ' + 'ng-model="ngModel" ' + 'ng-disabled="ngDisabled" ' + '>{{label}}</label> ' + '</div>'
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],19:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var moduleName = 'mui.row'; /**
* MUI Angular Grid/Row Module
* @module angular/row.js
*/
_angular2.default.module('mui.row', []).directive('muiRow', function () {
return {
restrict: 'AE',
scope: true,
replace: true,
template: '<div class="mui-row"></div>',
transclude: true,
link: function link(scope, element, attr, controller, transcludeFn) {
transcludeFn(scope, function (clone) {
element.append(clone);
});
}
};
});
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"angular":"aeQg5j"}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var _forms = require('../js/lib/forms');
var formlib = babelHelpers.interopRequireWildcard(_forms);
var _util = require('../js/lib/util');
var util = babelHelpers.interopRequireWildcard(_util);
var _jqLite = require('../js/lib/jqLite');
var jqLite = babelHelpers.interopRequireWildcard(_jqLite);
/**
* MUI Angular Select Component
* @module angular/select
*/
var moduleName = 'mui.select';
_angular2.default.module(moduleName, []).directive('muiSelect', ['$timeout', function ($timeout) {
return {
restrict: 'AE',
require: ['ngModel'],
scope: {
label: '@',
name: '@',
ngDisabled: '=',
ngModel: '='
},
replace: true,
transclude: true,
template: '<div class="mui-select" ' + 'ng-blur="onWrapperBlur()" ' + 'ng-focus="onWrapperFocus($event)" ' + 'ng-keydown="onWrapperKeydown($event)">' + '<select ' + 'name="{{name}}" ' + 'ng-click="onClick()" ' + 'ng-disabled="ngDisabled" ' + 'ng-focus="onFocus()" ' + 'ng-model="ngModel" ' + 'ng-mousedown="onMousedown($event)" ' + '>' + '<option ng-repeat="option in options" value="{{option.value}}">{{option.label}}</option>' + '</select>' + '<label>{{label}}</label>' + '<div ' + 'class="mui-select__menu"' + 'ng-show="!useDefault && isOpen"> ' + '<div ' + 'ng-click="chooseOption(option)" ' + 'ng-repeat="option in options track by $index" ' + 'ng-class=\'{"mui--is-selected": $index === menuIndex}\'>{{option.label}}</div>' + '</div>' + '</div>',
link: function link(scope, element, attrs, controller, transcludeFn) {
var wrapperEl = element,
menuEl = element.find('div'),
selectEl = element.find('select'),
isUndef = _angular2.default.isUndefined,
cacheIndex;
// disable MUI js
selectEl[0]._muiSelect = true;
// init scope
scope.options = [];
scope.isOpen = false;
scope.useDefault = false;
scope.origTabIndex = selectEl[0].tabIndex;
scope.menuIndex = 0;
// handle `use-default` attribute
if (!isUndef(attrs.useDefault)) scope.useDefault = true;
// make wrapper focusable
wrapperEl.prop('tabIndex', -1);
// extract <option> elements from children
transcludeFn(function (clone) {
var el, k;
// iterate through children
for (k in clone) {
el = clone[k];
// add option to scope
if (el.tagName === 'MUI-OPTION') {
scope.options.push({
value: el.getAttribute('value'),
label: el.getAttribute('label')
});
}
}
});
/**
* Handle click event on <select> element.
*/
scope.onClick = function () {
// check flag
if (scope.useDefault === true) return;
// open menu
scope.isOpen = true;
// defer focus
wrapperEl[0].focus();
};
/**
* Handle focus event on <select> element.
*/
scope.onFocus = function () {
// check flag
if (scope.useDefault === true) return;
// disable tabfocus once
var el = selectEl[0];
scope.origTabIndex = el.tabIndex;
el.tabIndex = -1;
// defer focus to parent
wrapperEl[0].focus();
};
/**
* Handle mousedown event on <select> element
*/
scope.onMousedown = function ($event) {
// check flag
if (scope.useDefault === true) return;
// cancel default menu
$event.preventDefault();
};
/**
* Handle blur event on wrapper element.
*/
scope.onWrapperBlur = function () {
// replace select element tab index
selectEl[0].tabIndex = scope.origTabIndex;
};
/**
* Handle focus event on wrapper element.
* @param {Event} $event - Angular event instance
*/
scope.onWrapperFocus = function ($event) {
// firefox bugfix
if (selectEl[0].disabled) return wrapperEl[0].blur();
};
/**
* Handle keydown event on wrapper element.
* @param {Event} $event - Angular event instance
*/
scope.onWrapperKeydown = function ($event) {
var keyCode = $event.keyCode;
if (scope.isOpen === false) {
// spacebar, down, up
if (keyCode === 32 || keyCode === 38 || keyCode === 40) {
// prevent win scroll
$event.preventDefault();
// open menu
scope.isOpen = true;
}
} else {
// tab
if (keyCode === 9) return scope.isOpen = false;
// escape | up | down | enter
if (keyCode === 27 || keyCode === 40 || keyCode === 38 || keyCode === 13) {
$event.preventDefault();
}
if (keyCode === 27) {
// close
scope.isOpen = false;
} else if (keyCode === 40) {
// increment
if (scope.menuIndex < scope.options.length - 1) {
scope.menuIndex += 1;
}
} else if (keyCode === 38) {
// decrement
if (scope.menuIndex > 0) scope.menuIndex -= 1;
} else if (keyCode === 13) {
// choose and close
scope.ngModel = scope.options[scope.menuIndex].value;
scope.isOpen = false;
}
}
};
/**
* Choose option the user selected.
* @param {Object} option - The option selected.
*/
scope.chooseOption = function (option) {
scope.ngModel = option.value;
scope.isOpen = false;
};
// function to close menu on window resize and document click
function closeMenuFn() {
scope.isOpen = false;
scope.$digest();
}
/**
* Open/Close custom select menu
*/
scope.$watch('isOpen', function (isOpen, oldVal) {
// ignore first call
if (isOpen === oldVal) return;
// exit if use-default is true
if (scope.useDefault === true) return;
if (isOpen === true) {
// enable scroll lock
util.enableScrollLock();
// init menuIndex
var value = scope.ngModel,
options = scope.options,
m = options.length,
i;
for (i = 0; i < m; i++) {
if (options[i].value === value) {
scope.menuIndex = i;
break;
}
}
// set position of custom menu
var props = formlib.getMenuPositionalCSS(element[0], scope.options.length, scope.menuIndex);
menuEl.css(props);
jqLite.scrollTop(menuEl[0], props.scrollTop);
// attach event handlers
$timeout(function () {
jqLite.on(document, 'click', closeMenuFn);
jqLite.on(window, 'resize', closeMenuFn);
});
} else {
// focus select element
selectEl[0].focus();
// disable scroll lock
util.disableScrollLock();
// remove event handlers
jqLite.off(document, 'click', closeMenuFn);
jqLite.off(window, 'resize', closeMenuFn);
}
});
}
};
}]);
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,"angular":"aeQg5j"}],21:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _angular = window.angular;
var _angular2 = babelHelpers.interopRequireDefault(_angular);
var _jqLite = require('../js/lib/jqLite');
var jqLite = babelHelpers.interopRequireWildcard(_jqLite);
/**
* MUI Angular Tabs Component
* @module angular/tabs
*/
var moduleName = 'mui.tabs';
_angular2.default.module(moduleName, []).directive('muiTabs', function () {
return {
restrict: 'EA',
transclude: true,
scope: {
selectedId: '=?selected',
onChange: '&?'
},
template: '' + '<ul ' + 'class="mui-tabs__bar" ' + 'ng-class=\'{"mui-tabs__bar--justified": justified}\'>' + '<li ' + 'ng-repeat="tab in tabs track by $index" ' + 'ng-class=\'{"mui--is-active": $index === selectedId}\'>' + '<a ng-click="onClick($index)">{{tab.label}}</a>' + '</li>' + '</ul>',
controller: ['$scope', function ($scope) {
var counter = 0;
// init scope
$scope.tabs = [];
// add tab
this.addTab = function (args) {
// user counter for tab id
var tabId = counter;
counter += 1;
// update tabs list
$scope.tabs.push({ label: args.label });
// handle active tabs
if (args.isActive) $scope.selectedId = tabId;
// return id
return tabId;
};
}],
link: function link(scope, element, attrs, ctrl, transcludeFn) {
var isUndef = _angular2.default.isUndefined;
// init scope
if (isUndef(scope.selectedId)) scope.selectedId = 0;
scope.justified = false;
// justified
if (!isUndef(attrs.justified)) scope.justified = true;
// click handler
scope.onClick = function (tabId) {
// check current tab
if (tabId === scope.selectedId) return;
// update active tab
scope.selectedId = tabId;
// execute onChange callback
if (scope.onChange) scope.$$postDigest(scope.onChange);
};
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function (clone) {
element.append(clone);
});
}
};
}).directive('muiTab', ['$parse', function ($parse) {
return {
require: '^?muiTabs',
restrict: 'AE',
scope: {
active: '&?',
label: '@?'
},
transclude: true,
template: '<div ' + 'class="mui-tabs__pane" ' + 'ng-class=\'{"mui--is-active": tabId === $parent.selectedId}\'></div>',
link: function link(scope, element, attrs, ctrl, transcludeFn) {
var onSelectFn = $parse(attrs.onSelect),
onDeselectFn = $parse(attrs.onDeselect),
origScope = scope.$parent.$parent;
// init scope
scope.tabId = null;
// add to parent controller
if (ctrl) {
scope.tabId = ctrl.addTab({
label: scope.label,
isActive: Boolean(scope.active)
});
}
// use transcludeFn to pass ng-controller on parent element
transcludeFn(scope, function (clone) {
element.find('div').append(clone);
});
scope.$parent.$watch('selectedId', function (newVal, oldVal) {
// ignore initial load
if (newVal === oldVal) return;
// execute onSelect
if (newVal === scope.tabId) onSelectFn(origScope);
// execute onDeselect
if (oldVal === scope.tabId) onDeselectFn(origScope);
});
}
};
}]);
/** Define module API */
exports.default = moduleName;
module.exports = exports['default'];
},{"../js/lib/jqLite":4,"angular":"aeQg5j"}]},{},[1])
|
/**!
* AngularJS file upload/drop directive and service with progress and abort
* FileAPI Flash shim for old browsers not supporting FormData
* @author Danial <danial.farid@gmail.com>
* @version 3.0.3
*/
(function() {
var hasFlash = function() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch(e) {
if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) return true;
}
return false;
}
function patchXHR(fnName, newFn) {
window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
};
if ((window.XMLHttpRequest && !window.FormData) || (window.FileAPI && FileAPI.forceLoad)) {
var initializeUploadListener = function(xhr) {
if (!xhr.__listeners) {
if (!xhr.upload) xhr.upload = {};
xhr.__listeners = [];
var origAddEventListener = xhr.upload.addEventListener;
xhr.upload.addEventListener = function(t, fn, b) {
xhr.__listeners[t] = fn;
origAddEventListener && origAddEventListener.apply(this, arguments);
};
}
}
patchXHR('open', function(orig) {
return function(m, url, b) {
initializeUploadListener(this);
this.__url = url;
try {
orig.apply(this, [m, url, b]);
} catch (e) {
if (e.message.indexOf('Access is denied') > -1) {
this.__origError = e;
this.__url = '_fix_for_ie_crossdomain__';
orig.apply(this, [m, this.__url, b]);
}
}
}
});
patchXHR('getResponseHeader', function(orig) {
return function(h) {
return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h]));
};
});
patchXHR('getAllResponseHeaders', function(orig) {
return function() {
return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this));
}
});
patchXHR('abort', function(orig) {
return function() {
return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this));
}
});
patchXHR('setRequestHeader', function(orig) {
return function(header, value) {
if (header === '__setXHR_') {
initializeUploadListener(this);
var val = value(this);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(this);
}
} else {
this.__requestHeaders = this.__requestHeaders || {};
this.__requestHeaders[header] = value;
orig.apply(this, arguments);
}
}
});
function redefineProp(xhr, prop, fn) {
try {
Object.defineProperty(xhr, prop, {get: fn});
} catch (e) {/*ignore*/}
}
patchXHR('send', function(orig) {
return function() {
var xhr = this;
if (arguments[0] && arguments[0].__isFileAPIShim) {
var formData = arguments[0];
var config = {
url: xhr.__url,
jsonp: false, //removes the callback form param
cache: true, //removes the ?fileapiXXX in the url
complete: function(err, fileApiXHR) {
xhr.__completed = true;
if (!err && xhr.__listeners['load'])
xhr.__listeners['load']({type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (!err && xhr.__listeners['loadend'])
xhr.__listeners['loadend']({type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (err === 'abort' && xhr.__listeners['abort'])
xhr.__listeners['abort']({type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true});
if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function() {return (fileApiXHR.status == 0 && err && err !== 'abort') ? 500 : fileApiXHR.status});
if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function() {return fileApiXHR.statusText});
redefineProp(xhr, 'readyState', function() {return 4});
if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function() {return fileApiXHR.response});
var resp = fileApiXHR.responseText || (err && fileApiXHR.status == 0 && err !== 'abort' ? err : undefined);
redefineProp(xhr, 'responseText', function() {return resp});
redefineProp(xhr, 'response', function() {return resp});
if (err) redefineProp(xhr, 'err', function() {return err});
xhr.__fileApiXHR = fileApiXHR;
if (xhr.onreadystatechange) xhr.onreadystatechange();
if (xhr.onload) xhr.onload();
},
fileprogress: function(e) {
e.target = xhr;
xhr.__listeners['progress'] && xhr.__listeners['progress'](e);
xhr.__total = e.total;
xhr.__loaded = e.loaded;
if (e.total === e.loaded) {
// fix flash issue that doesn't call complete if there is no response text from the server
var _this = this
setTimeout(function() {
if (!xhr.__completed) {
xhr.getAllResponseHeaders = function(){};
_this.complete(null, {status: 204, statusText: 'No Content'});
}
}, FileAPI.noContentTimeout || 10000);
}
},
headers: xhr.__requestHeaders
}
config.data = {};
config.files = {}
for (var i = 0; i < formData.data.length; i++) {
var item = formData.data[i];
if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {
config.files[item.key] = item.val;
} else {
config.data[item.key] = item.val;
}
}
setTimeout(function() {
if (!hasFlash()) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
xhr.__fileApiXHR = FileAPI.upload(config);
}, 1);
} else {
if (this.__url === '_fix_for_ie_crossdomain__') {
throw this.__origError;
}
orig.apply(xhr, arguments);
}
}
});
window.XMLHttpRequest.__isFileAPIShim = true;
var addFlash = function(elem) {
if (!hasFlash()) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
var el = angular.element(elem);
if (!el.attr('disabled')) {
var hasFileSelect = false;
for (var i = 0; i < el[0].attributes.length; i++) {
var attrib = el[0].attributes[i];
if (attrib.name.indexOf('file-select') !== -1) {
hasFileSelect = true;
break;
}
}
if (!el.hasClass('js-fileapi-wrapper') && (hasFileSelect || el.attr('__afu_gen__') != null)) {
el.addClass('js-fileapi-wrapper');
if (el.attr('__afu_gen__') != null) {
var ref = (el[0].__refElem__ && angular.element(el[0].__refElem__)) || el;
while (ref && !ref.attr('__refElem__')) {
ref = angular.element(ref[0].nextSibling);
}
ref.bind('mouseover', function() {
if (el.parent().css('position') === '' || el.parent().css('position') === 'static') {
el.parent().css('position', 'relative');
}
el.css('position', 'absolute').css('top', ref[0].offsetTop + 'px').css('left', ref[0].offsetLeft + 'px')
.css('width', ref[0].offsetWidth + 'px').css('height', ref[0].offsetHeight + 'px')
.css('padding', ref.css('padding')).css('margin', ref.css('margin')).css('filter', 'alpha(opacity=0)');
ref.attr('onclick', '');
el.css('z-index', '1000');
});
}
}
}
};
var changeFnWrapper = function(fn) {
return function(evt) {
var files = FileAPI.getFiles(evt);
//just a double check for #233
for (var i = 0; i < files.length; i++) {
if (files[i].size === undefined) files[i].size = 0;
if (files[i].name === undefined) files[i].name = 'file';
if (files[i].type === undefined) files[i].type = 'undefined';
}
if (!evt.target) {
evt.target = {};
}
evt.target.files = files;
// if evt.target.files is not writable use helper field
if (evt.target.files != files) {
evt.__files_ = files;
}
(evt.__files_ || evt.target.files).item = function(i) {
return (evt.__files_ || evt.target.files)[i] || null;
}
if (fn) fn.apply(this, [evt]);
};
};
var isFileChange = function(elem, e) {
return (e.toLowerCase() === 'change' || e.toLowerCase() === 'onchange') && elem.getAttribute('type') == 'file';
}
if (HTMLInputElement.prototype.addEventListener) {
HTMLInputElement.prototype.addEventListener = (function(origAddEventListener) {
return function(e, fn, b, d) {
if (isFileChange(this, e)) {
addFlash(this);
origAddEventListener.apply(this, [e, changeFnWrapper(fn), b, d]);
} else {
origAddEventListener.apply(this, [e, fn, b, d]);
}
}
})(HTMLInputElement.prototype.addEventListener);
}
if (HTMLInputElement.prototype.attachEvent) {
HTMLInputElement.prototype.attachEvent = (function(origAttachEvent) {
return function(e, fn) {
if (isFileChange(this, e)) {
addFlash(this);
if (window.jQuery) {
// fix for #281 jQuery on IE8
angular.element(this).bind('change', changeFnWrapper(null));
} else {
origAttachEvent.apply(this, [e, changeFnWrapper(fn)]);
}
} else {
origAttachEvent.apply(this, [e, fn]);
}
}
})(HTMLInputElement.prototype.attachEvent);
}
window.FormData = FormData = function() {
return {
append: function(key, val, name) {
if (val.__isFileAPIBlobShim) {
val = val.data[0];
}
this.data.push({
key: key,
val: val,
name: name
});
},
data: [],
__isFileAPIShim: true
};
};
window.Blob = Blob = function(b) {
return {
data: b,
__isFileAPIBlobShim: true
};
};
(function () {
//load FileAPI
if (!window.FileAPI) {
window.FileAPI = {};
}
if (FileAPI.forceLoad) {
FileAPI.html5 = false;
}
if (!FileAPI.upload) {
var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src;
if (window.FileAPI.jsUrl) {
jsUrl = window.FileAPI.jsUrl;
} else if (window.FileAPI.jsPath) {
basePath = window.FileAPI.jsPath;
} else {
for (i = 0; i < allScripts.length; i++) {
src = allScripts[i].src;
index = src.search(/\/angular\-file\-upload[\-a-zA-z0-9\.]*\.js/)
if (index > -1) {
basePath = src.substring(0, index + 1);
break;
}
}
}
if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js');
document.getElementsByTagName('head')[0].appendChild(script);
FileAPI.hasFlash = hasFlash();
}
})();
FileAPI.disableFileInput = function(elem, disable) {
if (disable) {
elem.removeClass('js-fileapi-wrapper')
} else {
elem.addClass('js-fileapi-wrapper');
}
}
}
if (!window.FileReader) {
window.FileReader = function() {
var _this = this, loadStarted = false;
this.listeners = {};
this.addEventListener = function(type, fn) {
_this.listeners[type] = _this.listeners[type] || [];
_this.listeners[type].push(fn);
};
this.removeEventListener = function(type, fn) {
_this.listeners[type] && _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);
};
this.dispatchEvent = function(evt) {
var list = _this.listeners[evt.type];
if (list) {
for (var i = 0; i < list.length; i++) {
list[i].call(_this, evt);
}
}
};
this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;
var constructEvent = function(type, evt) {
var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
if (evt.result != null) e.target.result = evt.result;
return e;
};
var listener = function(evt) {
if (!loadStarted) {
loadStarted = true;
_this.onloadstart && _this.onloadstart(constructEvent('loadstart', evt));
}
if (evt.type === 'load') {
_this.onloadend && _this.onloadend(constructEvent('loadend', evt));
var e = constructEvent('load', evt);
_this.onload && _this.onload(e);
_this.dispatchEvent(e);
} else if (evt.type === 'progress') {
var e = constructEvent('progress', evt);
_this.onprogress && _this.onprogress(e);
_this.dispatchEvent(e);
} else {
var e = constructEvent('error', evt);
_this.onerror && _this.onerror(e);
_this.dispatchEvent(e);
}
};
this.readAsArrayBuffer = function(file) {
FileAPI.readAsBinaryString(file, listener);
}
this.readAsBinaryString = function(file) {
FileAPI.readAsBinaryString(file, listener);
}
this.readAsDataURL = function(file) {
FileAPI.readAsDataURL(file, listener);
}
this.readAsText = function(file) {
FileAPI.readAsText(file, listener);
}
}
}
})();
|
jQuery(function($){$(".siteorigin-panels-stretch.panel-row-style").each(function(){var $$=$(this);var onResize=function(){$$.css({"margin-left":0,"margin-right":0,"padding-left":0,"padding-right":0});var leftSpace=$$.offset().left;var rightSpace=$(window).outerWidth()-$$.offset().left-$$.parent().outerWidth();$$.css({"margin-left":-leftSpace,"margin-right":-rightSpace,"padding-left":$$.data("stretch-type")==="full"?leftSpace:0,"padding-right":$$.data("stretch-type")==="full"?rightSpace:0});var cells=$$.find("> .panel-grid-cell");if($$.data("stretch-type")==="full-stretched"&&cells.length===1){cells.css({"padding-left":0,"padding-right":0})}};$(window).resize(onResize);onResize();$$.css({"border-left":0,"border-right":0})})});
|
loadjs = (function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn, bundleId, r, q;
// define callback function
fn = function(bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting -= 1;
if (numWaiting === 0) callbackFn(depsNotFound);
};
// register callback
while (i--) {
bundleId = bundleIds[i];
// execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
}
// add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId];
// cache result
bundleResultCache[bundleId] = pathsNotFound;
// exit if queue is empty
if (!q) return;
// empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Load individual JavaScript file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadScript(path, callbackFn) {
var doc = document,
s = doc.createElement('script');
s.src = path;
s.onload = s.onerror = function(ev) {
// remove script
var p = s.parentNode;
if (p) p.removeChild(s);
// de-reference script
s = null;
// execute callback
callbackFn(path, ev.type);
};
// add to document
doc.head.appendChild(s);
}
/**
* Load multiple JavaScript files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadScripts(paths, callbackFn) {
// listify paths
paths = paths.push ? paths : [paths];
var i = paths.length, numWaiting = i, pathsNotFound = [], fn;
// define callback function
fn = function(path, result) {
if (result === 'error') pathsNotFound.push(path);
numWaiting -= 1;
if (numWaiting === 0) callbackFn(pathsNotFound);
};
// load scripts
while (i--) loadScript(paths[i], fn);
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function)} [arg1] - The bundleId or success callback
* @param {Function} [arg2] - The success or fail callback
* @param {Function} [arg3] - The fail callback
*/
function loadjs(paths, arg1, arg2, arg3) {
var bundleId, successFn, failFn;
// bundleId
if (arg1 && !arg1.call) bundleId = arg1;
// successFn, failFn
successFn = bundleId ? arg2 : arg1;
failFn = bundleId ? arg3 : arg2;
// throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw new Error("LoadJS: Bundle already defined");
} else {
bundleIdCache[bundleId] = true;
}
}
// load scripts
loadScripts(paths, function(pathsNotFound) {
if (pathsNotFound.length) (failFn || devnull)(pathsNotFound);
else (successFn || devnull)();
// publish bundle load event
publish(bundleId, pathsNotFound);
});
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Function} [successFn] - Success callback
* @param {Function} [failFn] - Fail callback
*/
loadjs.ready = function (deps, successFn, failFn) {
// subscribe to bundle load event
subscribe(deps, function(depsNotFound) {
// execute callbacks
if (depsNotFound.length) (failFn || devnull)(depsNotFound);
else (successFn || devnull)();
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
// export
return loadjs;
})();
|
(e) => "test"
|
/**
* @author alteredq / http://alteredqualia.com/
*
* - shows frustum, line of sight and up of the camera
* - suitable for fast updates
* - based on frustum visualization in lightgl.js shadowmap example
* http://evanw.github.com/lightgl.js/tests/shadowmap.html
*/
THREE.CameraHelper = function ( camera ) {
var geometry = new THREE.Geometry();
var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
var pointMap = {};
// colors
var hexFrustum = 0xffaa00;
var hexCone = 0xff0000;
var hexUp = 0x00aaff;
var hexTarget = 0xffffff;
var hexCross = 0x333333;
// near
addLine( "n1", "n2", hexFrustum );
addLine( "n2", "n4", hexFrustum );
addLine( "n4", "n3", hexFrustum );
addLine( "n3", "n1", hexFrustum );
// far
addLine( "f1", "f2", hexFrustum );
addLine( "f2", "f4", hexFrustum );
addLine( "f4", "f3", hexFrustum );
addLine( "f3", "f1", hexFrustum );
// sides
addLine( "n1", "f1", hexFrustum );
addLine( "n2", "f2", hexFrustum );
addLine( "n3", "f3", hexFrustum );
addLine( "n4", "f4", hexFrustum );
// cone
addLine( "p", "n1", hexCone );
addLine( "p", "n2", hexCone );
addLine( "p", "n3", hexCone );
addLine( "p", "n4", hexCone );
// up
addLine( "u1", "u2", hexUp );
addLine( "u2", "u3", hexUp );
addLine( "u3", "u1", hexUp );
// target
addLine( "c", "t", hexTarget );
addLine( "p", "c", hexCross );
// cross
addLine( "cn1", "cn2", hexCross );
addLine( "cn3", "cn4", hexCross );
addLine( "cf1", "cf2", hexCross );
addLine( "cf3", "cf4", hexCross );
function addLine( a, b, hex ) {
addPoint( a, hex );
addPoint( b, hex );
}
function addPoint( id, hex ) {
geometry.vertices.push( new THREE.Vector3() );
geometry.colors.push( new THREE.Color( hex ) );
if ( pointMap[ id ] === undefined ) {
pointMap[ id ] = [];
}
pointMap[ id ].push( geometry.vertices.length - 1 );
}
THREE.LineSegments.call( this, geometry, material );
this.camera = camera;
this.camera.updateProjectionMatrix();
this.matrix = camera.matrixWorld;
this.matrixAutoUpdate = false;
this.pointMap = pointMap;
this.update();
};
THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
THREE.CameraHelper.prototype.update = function () {
var geometry, pointMap;
var vector = new THREE.Vector3();
var camera = new THREE.Camera();
function setPoint( point, x, y, z ) {
vector.set( x, y, z ).unproject( camera );
var points = pointMap[ point ];
if ( points !== undefined ) {
for ( var i = 0, il = points.length; i < il; i ++ ) {
geometry.vertices[ points[ i ] ].copy( vector );
}
}
}
return function () {
geometry = this.geometry;
pointMap = this.pointMap;
var w = 1, h = 1;
// we need just camera projection matrix
// world matrix must be identity
camera.projectionMatrix.copy( this.camera.projectionMatrix );
// center / target
setPoint( "c", 0, 0, - 1 );
setPoint( "t", 0, 0, 1 );
// near
setPoint( "n1", - w, - h, - 1 );
setPoint( "n2", w, - h, - 1 );
setPoint( "n3", - w, h, - 1 );
setPoint( "n4", w, h, - 1 );
// far
setPoint( "f1", - w, - h, 1 );
setPoint( "f2", w, - h, 1 );
setPoint( "f3", - w, h, 1 );
setPoint( "f4", w, h, 1 );
// up
setPoint( "u1", w * 0.7, h * 1.1, - 1 );
setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
setPoint( "u3", 0, h * 2, - 1 );
// cross
setPoint( "cf1", - w, 0, 1 );
setPoint( "cf2", w, 0, 1 );
setPoint( "cf3", 0, - h, 1 );
setPoint( "cf4", 0, h, 1 );
setPoint( "cn1", - w, 0, - 1 );
setPoint( "cn2", w, 0, - 1 );
setPoint( "cn3", 0, - h, - 1 );
setPoint( "cn4", 0, h, - 1 );
geometry.verticesNeedUpdate = true;
};
}();
|
var identity = function(item) { return item }
var itemId = function(item) { return item.id }
/*
* Filters a list to unique items
*/
module.exports = function(list, getId) {
if (!list || !list.length) { return [] }
if (!getId) {
getId = (list[0].id ? itemId : identity)
}
var seen = {}
var result = []
for (var i=0; i<list.length; i++) {
var item = list[i]
var id = getId(item)
if (seen[id]) { continue }
seen[id] = true
result.push(item)
}
return result
}
|
module.exports = { prefix: 'fas', iconName: 'shopping-bag', icon: [448, 512, [], "f290", "M352 160v-32C352 57.42 294.579 0 224 0 153.42 0 96 57.42 96 128v32H0v272c0 44.183 35.817 80 80 80h288c44.183 0 80-35.817 80-80V160h-96zm-192-32c0-35.29 28.71-64 64-64s64 28.71 64 64v32H160v-32zm160 120c-13.255 0-24-10.745-24-24s10.745-24 24-24 24 10.745 24 24-10.745 24-24 24zm-192 0c-13.255 0-24-10.745-24-24s10.745-24 24-24 24 10.745 24 24-10.745 24-24 24z"] };
|
module.exports = { prefix: 'fas', iconName: 'headphones', icon: [512, 512, [], "f025", "M256 32C114.52 32 0 146.496 0 288v48a32 32 0 0 0 17.689 28.622l14.383 7.191C34.083 431.903 83.421 480 144 480h24c13.255 0 24-10.745 24-24V280c0-13.255-10.745-24-24-24h-24c-31.342 0-59.671 12.879-80 33.627V288c0-105.869 86.131-192 192-192s192 86.131 192 192v1.627C427.671 268.879 399.342 256 368 256h-24c-13.255 0-24 10.745-24 24v176c0 13.255 10.745 24 24 24h24c60.579 0 109.917-48.098 111.928-108.187l14.382-7.191A32 32 0 0 0 512 336v-48c0-141.479-114.496-256-256-256z"] };
|
// Contains all path information to be used throughout
// the codebase.
var moment = require('moment'),
path = require('path'),
when = require('when'),
url = require('url'),
_ = require('underscore'),
requireTree = require('../require-tree'),
appRoot = path.resolve(__dirname, '../../../'),
corePath = path.resolve(appRoot, 'core/'),
contentPath = path.resolve(appRoot, 'content/'),
themePath = path.resolve(contentPath + '/themes'),
pluginPath = path.resolve(contentPath + '/plugins'),
themeDirectories = requireTree(themePath),
pluginDirectories = requireTree(pluginPath),
localPath = '',
configUrl = '',
availableThemes,
availablePlugins;
function paths() {
var subdir = localPath === '/' ? '' : localPath;
return {
'appRoot': appRoot,
'subdir': subdir,
'config': path.join(appRoot, 'config.js'),
'configExample': path.join(appRoot, 'config.example.js'),
'contentPath': contentPath,
'corePath': corePath,
'themePath': themePath,
'pluginPath': pluginPath,
'imagesPath': path.resolve(contentPath, 'images/'),
'imagesRelPath': 'content/images',
'adminViews': path.join(corePath, '/server/views/'),
'helperTemplates': path.join(corePath, '/server/helpers/tpl/'),
'exportPath': path.join(corePath, '/server/data/export/'),
'lang': path.join(corePath, '/shared/lang/'),
'debugPath': subdir + '/ghost/debug/',
'availableThemes': availableThemes,
'availablePlugins': availablePlugins,
'builtScriptPath': path.join(corePath, 'built/scripts/')
};
}
// TODO: remove configURL and give direct access to config object?
// TODO: not called when executing tests
function update(configURL) {
configUrl = configURL;
localPath = url.parse(configURL).path;
// Remove trailing slash
if (localPath !== '/') {
localPath = localPath.replace(/\/$/, '');
}
return when.all([themeDirectories, pluginDirectories]).then(function (paths) {
availableThemes = paths[0];
availablePlugins = paths[1];
return;
});
}
// ## createUrl
// Simple url creation from a given path
// Ensures that our urls contain the subdirectory if there is one
// And are correctly formatted as either relative or absolute
// Usage:
// createUrl('/', true) -> http://my-ghost-blog.com/
// E.g. /blog/ subdir
// createUrl('/welcome-to-ghost/') -> /blog/welcome-to-ghost/
// Parameters:
// - urlPath - string which must start and end with a slash
// - absolute (optional, default:false) - boolean whether or not the url should be absolute
// Returns:
// - a URL which always ends with a slash
function createUrl(urlPath, absolute) {
urlPath = urlPath || '/';
absolute = absolute || false;
var output = '';
// create base of url, always ends without a slash
if (absolute) {
output += configUrl.replace(/\/$/, '');
} else {
output += paths().subdir;
}
// append the path, always starts and ends with a slash
output += urlPath;
return output;
}
// ## urlPathForPost
// Always sync
// Creates the url path for a post, given a post and a permalink
// Parameters:
// - post - a json object representing a post
// - permalinks - a json object containing the permalinks setting
function urlPathForPost(post, permalinks) {
var output = '',
tags = {
year: function () { return moment(post.published_at).format('YYYY'); },
month: function () { return moment(post.published_at).format('MM'); },
day: function () { return moment(post.published_at).format('DD'); },
slug: function () { return post.slug; },
id: function () { return post.id; }
};
if (post.page === 1) {
output += '/:slug/';
} else {
output += permalinks.value;
}
// replace tags like :slug or :year with actual values
output = output.replace(/(:[a-z]+)/g, function (match) {
if (_.has(tags, match.substr(1))) {
return tags[match.substr(1)]();
}
});
return output;
}
// ## urlFor
// Synchronous url creation for a given context
// Can generate a url for a named path, given path, or known object (post)
// Determines what sort of context it has been given, and delegates to the correct generation method,
// Finally passing to createUrl, to ensure any subdirectory is honoured, and the url is absolute if needed
// Usage:
// urlFor('home', true) -> http://my-ghost-blog.com/
// E.g. /blog/ subdir
// urlFor({relativeUrl: '/my-static-page/') -> /blog/my-static-page/
// E.g. if post object represents welcome post, and slugs are set to standard
// urlFor('post', {...}) -> /welcome-to-ghost/
// E.g. if post object represents welcome post, and slugs are set to date
// urlFor('post', {...}) -> /2014/01/01/welcome-to-ghost/
// Parameters:
// - context - a string, or json object describing the context for which you need a url
// - data (optional) - a json object containing data needed to generate a url
// - absolute (optional, default:false) - boolean whether or not the url should be absolute
// This is probably not the right place for this, but it's the best place for now
function urlFor(context, data, absolute) {
var urlPath = '/',
knownObjects = ['post', 'tag', 'user'],
knownPaths = {'home': '/', 'rss': '/rss/'}; // this will become really big
// Make data properly optional
if (_.isBoolean(data)) {
absolute = data;
data = null;
}
if (_.isObject(context) && context.relativeUrl) {
urlPath = context.relativeUrl;
} else if (_.isString(context) && _.indexOf(knownObjects, context) !== -1) {
// trying to create a url for an object
if (context === 'post' && data.post && data.permalinks) {
urlPath = urlPathForPost(data.post, data.permalinks);
}
// other objects are recognised but not yet supported
} else if (_.isString(context) && _.indexOf(_.keys(knownPaths), context) !== -1) {
// trying to create a url for a named path
urlPath = knownPaths[context] || '/';
}
return createUrl(urlPath, absolute);
}
// ## urlForPost
// This method is async as we have to fetch the permalinks
// Get the permalink setting and then get a URL for the given post
// Parameters
// - settings - passed reference to api.settings
// - post - a json object representing a post
// - absolute (optional, default:false) - boolean whether or not the url should be absolute
function urlForPost(settings, post, absolute) {
return settings.read('permalinks').then(function (permalinks) {
return urlFor('post', {post: post, permalinks: permalinks}, absolute);
});
}
module.exports = paths;
module.exports.update = update;
module.exports.urlFor = urlFor;
module.exports.urlForPost = urlForPost;
|
/*!
* FileInput Czech Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['cs'] = {
fileSingle: 'soubor',
filePlural: 'soubory',
browseLabel: 'Vybrat …',
removeLabel: 'Odstranit',
removeTitle: 'Vyčistit vybrané soubory',
cancelLabel: 'Storno',
cancelTitle: 'Přerušit nahrávání',
uploadLabel: 'Nahrát',
uploadTitle: 'Nahrát vybrané soubory',
msgNo: 'Ne',
msgNoFilesSelected: 'Nevybrány žádné soubory',
msgCancelled: 'Zrušeno',
msgPlaceholder: 'Vybrat {files}...',
msgZoomModalHeading: 'Detailní náhled',
msgFileRequired: 'Musíte vybrat soubor, který chcete nahrát.',
msgSizeTooSmall: 'Soubor "{name}" (<b>{size} KB</b>) je příliš malý, musí mít velikost nejméně <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Soubor "{name}" (<b>{size} KB</b>) je příliš velký, maximální povolená velikost <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Musíte vybrat nejméně <b>{n}</b> {files} souborů.',
msgFilesTooMany: 'Počet vybraných souborů <b>({n})</b> překročil maximální povolený limit <b>{m}</b>.',
msgFileNotFound: 'Soubor "{name}" nebyl nalezen!',
msgFileSecured: 'Zabezpečení souboru znemožnilo číst soubor "{name}".',
msgFileNotReadable: 'Soubor "{name}" není čitelný.',
msgFilePreviewAborted: 'Náhled souboru byl přerušen pro "{name}".',
msgFilePreviewError: 'Nastala chyba při načtení souboru "{name}".',
msgInvalidFileName: 'Neplatné nebo nepovolené znaky ve jménu souboru "{name}".',
msgInvalidFileType: 'Neplatný typ souboru "{name}". Pouze "{types}" souborů jsou podporovány.',
msgInvalidFileExtension: 'Neplatná extenze souboru "{name}". Pouze "{extensions}" souborů jsou podporovány.',
msgFileTypes: {
'image': 'obrázek',
'html': 'HTML',
'text': 'text',
'video': 'video',
'audio': 'audio',
'flash': 'flash',
'pdf': 'PDF',
'object': 'object'
},
msgUploadAborted: 'Nahrávání souboru bylo přerušeno',
msgUploadThreshold: 'Zpracovávám...',
msgUploadBegin: 'Inicializujem...',
msgUploadEnd: 'Hotovo',
msgUploadEmpty: 'Pro nahrávání nejsou k dispozici žádné platné údaje.',
msgUploadError: 'Chyba',
msgValidationError: 'Chyba ověření',
msgLoading: 'Nahrávání souboru {index} z {files} …',
msgProgress: 'Nahrávání souboru {index} z {files} - {name} - {percent}% dokončeno.',
msgSelected: '{n} {files} vybráno',
msgFoldersNotAllowed: 'Táhni a pusť pouze soubory! Vynechané {n} pustěné složk(y).',
msgImageWidthSmall: 'Šířka obrázku "{name}", musí být alespoň {size} px.',
msgImageHeightSmall: 'Výška obrázku "{name}", musí být alespoň {size} px.',
msgImageWidthLarge: 'Šířka obrázku "{name}" nesmí být větší než {size} px.',
msgImageHeightLarge: 'Výška obrázku "{name}" nesmí být větší než {size} px.',
msgImageResizeError: 'Nelze získat rozměry obrázku pro změnu velikosti.',
msgImageResizeException: 'Chyba při změně velikosti obrázku.<pre>{errors}</pre>',
msgAjaxError: 'Došlo k chybě v {operation}. Prosím zkuste to znovu později!',
msgAjaxProgressError: '{operation} - neúspěšné',
ajaxOperations: {
deleteThumb: 'odstranit soubor',
uploadThumb: 'nahrát soubor',
uploadBatch: 'nahrát várku souborů',
uploadExtra: 'odesílání dat formuláře'
},
dropZoneTitle: 'Přetáhni soubory sem …',
dropZoneClickTitle: '<br>(nebo klikni sem a vyber je)',
fileActionSettings: {
removeTitle: 'Odstranit soubor',
uploadTitle: 'Nahrát soubor',
uploadRetryTitle: 'Opakovat nahrávání',
downloadTitle: 'Stáhnout soubor',
zoomTitle: 'Zobrazit podrobnosti',
dragTitle: 'Posunout / Přeskládat',
indicatorNewTitle: 'Ještě nenahrál',
indicatorSuccessTitle: 'Nahraný',
indicatorErrorTitle: 'Chyba nahrávání',
indicatorLoadingTitle: 'Nahrávání ...'
},
previewZoomButtonTitles: {
prev: 'Zobrazit předchozí soubor',
next: 'Zobrazit následující soubor',
toggleheader: 'Přepnout záhlaví',
fullscreen: 'Přepnout celoobrazovkové zobrazení',
borderless: 'Přepnout bezrámečkové zobrazení',
close: 'Zavřít detailní náhled'
}
};
})(window.jQuery);
|
/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
* @private
*/
/* eslint-disable */
'use strict';
/* istanbul ignore else */
if (!global._babelPolyfill) {
require('babel-polyfill');
}
// helper file for code coverage
if (process.env.COVERAGE && (new RegExp(process.env.PACKAGE + '$')).test(require('../package').name)) {
if (typeof window === 'undefined') {
var covered = '../.coverage/src';
module.exports = require(covered);
}
else {
module.exports = require('../src');
}
}
else {
module.exports = require('..');
}
|
/*!
* Media Element
* HTML5 <video> libary
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 media objects
* through a Flash->JavaScript|Silverlight bridge
*
* Copyright 2010, John Dyer
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Version: 1.1.0
*/
// Namespace
var html5 = html5 || {};
// player number (for missing, same id attr)
html5.meIndex = 0;
// media types accepted by plugins
html5.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/mp4','audio/m4a','audio/mp3']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','audio/flv','audio/mp3','audio/m4a','audio/mp3']}
//,{version: [11,0], types: ['video/webm'} // for future reference
]
};
// Core detector, plugins are added below
html5.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
d,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
d = this.nav.plugins[pluginName].description;
if (d && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = d.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i], 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
html5.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
html5.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1];
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
}
*/
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (html5.PluginDetector.ua.match(/Android 2\.[12]/) !== null) {
HTMLMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'probably' : '';
};
}
// necessary detection (fixes for <IE9)
html5.MediaFeatures = {
init: function() {
var
nav = html5.PluginDetector.nav,
ua = html5.PluginDetector.ua,
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers
this.isiPad = (ua.match(/iPad/i) !== null);
this.isiPhone = (ua.match(/iPhone/i) !== null);
this.isAndroid = (ua.match(/Android/i) !== null);
this.isIE = (nav.appName.indexOf("Microsoft") != -1);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
// detect native JavaScript fullscreen (Safari only, Chrome fails)
this.hasNativeFullScreen = (typeof v.webkitEnterFullScreen !== 'undefined');
if (ua.match('Chrome')) {
this.hasNativeFullScreen = false;
}
}
};
html5.MediaFeatures.init();
/*
Utility methods
*/
html5.Utility = {
escapeHTML: function(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script');
for (; i < scripts.length; i++) {
script = scripts[i].src;
for (j = 0; j < scriptNames.length; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(seconds) {
seconds = Math.round(seconds);
var minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
return minutes + ":" + seconds;
}
};
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
html5.HtmlMediaElement = {
pluginType: 'native',
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
html5.PluginMediaElement = function (pluginid, pluginType) {
this.id = pluginid;
this.pluginType = pluginType;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
html5.PluginMediaElement.prototype = {
// special
pluginElement: null,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
this.pluginApi.playMedia();
this.paused = false;
},
load: function () {
this.pluginApi.loadMedia();
this.paused = false;
},
pause: function () {
this.pluginApi.pauseMedia();
this.paused = true;
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(html5.Utility.absolutizeUrl(url));
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(html5.Utility.absolutizeUrl(media.src));
}
}
}
},
setCurrentTime: function (time) {
this.pluginApi.setCurrentTime(time);
this.currentTime = time;
},
setVolume: function (volume) {
this.pluginApi.setVolume(volume);
this.volume = volume;
},
setMuted: function (muted) {
this.pluginApi.setMuted(muted);
this.muted = muted;
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
this.pluginApi.setVideoSize(width, height);
},
setFullscreen: function (fullscreen) {
this.pluginApi.setFullscreen(fullscreen);
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
}
// end: fake events
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
html5.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.SilverlightApp;
break;
}
if (pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = false;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
html5.MediaElementDefaults = {
// shows debug errors on screen
enablePluginDebug: false,
// remove or reorder to change plugin priority
plugins: ['silverlight', 'flash'],
// specify to force MediaElement into a mode
type: '',
// path to Flash and Silverlight plugins
pluginPath: html5.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
html5.MediaElement = function (el, o) {
html5.HtmlMediaElementShim.create(el,o);
};
html5.HtmlMediaElementShim = {
create: function(el, o) {
var
options = html5.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
isVideo = (htmlMediaElement.tagName.toLowerCase() == 'video'),
supportsMediaTag = (typeof(htmlMediaElement.canPlayType) != 'undefined'),
playback = {method:'', url:''},
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// check for real poster
poster = (poster == 'undefined' || poster === null) ? '' : poster;
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, isVideo, supportsMediaTag);
if (playback.method == 'native') {
// add methods to native HTMLMediaElement
this.updateNative( htmlMediaElement, options);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
this.createPlugin( htmlMediaElement, options, isVideo, playback.method, html5.Utility.absolutizeUrl(playback.url), poster, autoplay);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( htmlMediaElement, options, playback.url, poster );
}
},
determinePlayback: function(htmlMediaElement, options, isVideo, supportsMediaTag) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
url,
type,
result = { method: '', url: ''},
pluginName,
pluginVersions,
pluginInfo;
// STEP 1: Get Files from <video src> or <source src>
// supplied type overrides all HTML
if (typeof (options.type) != 'undefined' && options.type !== '') {
mediaFiles.push({type:options.type, url:null});
// test for src attribute first
} else if (htmlMediaElement.getAttribute('src') != 'undefined' && htmlMediaElement.getAttribute('src') !== null) {
url = htmlMediaElement.getAttribute('src');
type = this.checkType(url, htmlMediaElement.getAttribute('type'), isVideo);
mediaFiles.push({type:type, url:url});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
url = n.getAttribute('src');
type = this.checkType(url, n.getAttribute('type'), isVideo);
mediaFiles.push({type:type, url:url});
}
}
}
// STEP 2: Test for playback method
// test for native playback first
if (supportsMediaTag) {
for (i=0; i<mediaFiles.length; i++) {
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
return result;
}
}
}
// if native playback didn't work, then test plugins
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = html5.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
if (html5.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
return result;
},
checkType: function(url, type, isVideo) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
ext = url.substring(url.lastIndexOf('.') + 1);
return ((isVideo) ? 'video' : 'audio') + '/' + ext;
} else {
return type;
}
},
createErrorMessage: function(htmlMediaElement, options, downloadUrl, poster) {
var errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + downloadUrl + '"><img src="' + poster + '" /></a>' :
'<a href="' + downloadUrl + '">Download file</a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(htmlMediaElement, options, isVideo, pluginType, mediaUrl, poster, autoplay) {
var width = 1,
height = 1,
pluginid = 'me_' + pluginType + '_' + (html5.meIndex++),
pluginMediaElement = new html5.PluginMediaElement(pluginid, pluginType),
container = document.createElement('div'),
initVars;
if (isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
html5.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'poster=' + poster,
'autoplay=' + autoplay,
'width=' + width,
'height=' + height];
if (mediaUrl !== null) {
initVars.push('file=' + mediaUrl);
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
switch (pluginType) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (html5.MediaFeatures.isIE) {
container.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="sameDomain" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="sameDomain" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '?' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
},
updateNative: function(htmlMediaElement, options) {
// add methods to video object to bring it into parity with Flash Object
for (var m in html5.HtmlMediaElement) {
htmlMediaElement[m] = html5.HtmlMediaElement[m];
}
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
}
};
window.html5 = html5;
window.MediaElement = html5.MediaElement;
|
/*!
* Fuel UX v3.14.1
* Copyright 2012-2016 ExactTarget
* Licensed under the BSD-3-Clause license (https://github.com/ExactTarget/fuelux/blob/master/LICENSE)
*/
// For more information on UMD visit: https://github.com/umdjs/umd/
( function( factory ) {
if ( typeof define === 'function' && define.amd ) {
define( [ 'jquery', 'bootstrap' ], factory );
} else {
factory( jQuery );
}
}( function( jQuery ) {
if ( typeof jQuery === 'undefined' ) {
throw new Error( 'Fuel UX\'s JavaScript requires jQuery' )
}
if ( typeof jQuery.fn.dropdown === 'undefined' || typeof jQuery.fn.collapse === 'undefined' ) {
throw new Error( 'Fuel UX\'s JavaScript requires Bootstrap' )
}
( function( $ ) {
/*
* Fuel UX Checkbox
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.checkbox;
// CHECKBOX CONSTRUCTOR AND PROTOTYPE
var Checkbox = function( element, options ) {
this.options = $.extend( {}, $.fn.checkbox.defaults, options );
if ( element.tagName.toLowerCase() !== 'label' ) {
//console.log('initialize checkbox on the label that wraps the checkbox');
return;
}
// cache elements
this.$label = $( element );
this.$chk = this.$label.find( 'input[type="checkbox"]' );
this.$container = $( element ).parent( '.checkbox' ); // the container div
// determine if a toggle container is specified
var containerSelector = this.$chk.attr( 'data-toggle' );
this.$toggleContainer = $( containerSelector );
// handle internal events
this.$chk.on( 'change', $.proxy( this.itemchecked, this ) );
// set default state
this.setInitialState();
};
Checkbox.prototype = {
constructor: Checkbox,
setInitialState: function() {
var $chk = this.$chk;
var $lbl = this.$label;
// get current state of input
var checked = $chk.prop( 'checked' );
var disabled = $chk.prop( 'disabled' );
// sync label class with input state
this.setCheckedState( $chk, checked );
this.setDisabledState( $chk, disabled );
},
setCheckedState: function( element, checked ) {
var $chk = element;
var $lbl = this.$label;
var $container = this.$container;
var $containerToggle = this.$toggleContainer;
// set class on outer container too...to support highlighting
// TODO: verify inline checkboxes, also test with MCTheme
if ( checked ) {
$chk.prop( 'checked', true );
$lbl.addClass( 'checked' );
//$container.addClass('checked');
$containerToggle.removeClass( 'hide hidden' );
$lbl.trigger( 'checked.fu.checkbox' );
} else {
$chk.prop( 'checked', false );
$lbl.removeClass( 'checked' );
//$container.removeClass('checked');
$containerToggle.addClass( 'hidden' );
$lbl.trigger( 'unchecked.fu.checkbox' );
}
$lbl.trigger( 'changed.fu.checkbox', checked );
},
setDisabledState: function( element, disabled ) {
var $chk = element;
var $lbl = this.$label;
if ( disabled ) {
this.$chk.prop( 'disabled', true );
$lbl.addClass( 'disabled' );
$lbl.trigger( 'disabled.fu.checkbox' );
} else {
this.$chk.prop( 'disabled', false );
$lbl.removeClass( 'disabled' );
$lbl.trigger( 'enabled.fu.checkbox' );
}
},
itemchecked: function( evt ) {
var $chk = $( evt.target );
var checked = $chk.prop( 'checked' );
this.setCheckedState( $chk, checked );
},
toggle: function() {
var checked = this.isChecked();
if ( checked ) {
this.uncheck();
} else {
this.check();
}
},
check: function() {
this.setCheckedState( this.$chk, true );
},
uncheck: function() {
this.setCheckedState( this.$chk, false );
},
isChecked: function() {
var checked = this.$chk.prop( 'checked' );
return checked;
},
enable: function() {
this.setDisabledState( this.$chk, false );
},
disable: function() {
this.setDisabledState( this.$chk, true );
},
destroy: function() {
this.$label.remove();
// remove any external bindings
// [none]
// empty elements to return to original markup
// [none]
return this.$label[ 0 ].outerHTML;
}
};
Checkbox.prototype.getValue = Checkbox.prototype.isChecked;
// CHECKBOX PLUGIN DEFINITION
$.fn.checkbox = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.checkbox' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.checkbox', ( data = new Checkbox( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.checkbox.defaults = {};
$.fn.checkbox.Constructor = Checkbox;
$.fn.checkbox.noConflict = function() {
$.fn.checkbox = old;
return this;
};
// DATA-API
$( document ).on( 'mouseover.fu.checkbox.data-api', '[data-initialize=checkbox]', function( e ) {
var $control = $( e.target );
if ( !$control.data( 'fu.checkbox' ) ) {
$control.checkbox( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=checkbox]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.checkbox' ) ) {
$this.checkbox( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Combobox
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.combobox;
// COMBOBOX CONSTRUCTOR AND PROTOTYPE
var Combobox = function( element, options ) {
this.$element = $( element );
this.options = $.extend( {}, $.fn.combobox.defaults, options );
this.$dropMenu = this.$element.find( '.dropdown-menu' );
this.$input = this.$element.find( 'input' );
this.$button = this.$element.find( '.btn' );
this.$element.on( 'click.fu.combobox', 'a', $.proxy( this.itemclicked, this ) );
this.$element.on( 'change.fu.combobox', 'input', $.proxy( this.inputchanged, this ) );
this.$element.on( 'shown.bs.dropdown', $.proxy( this.menuShown, this ) );
// set default selection
this.setDefaultSelection();
// if dropdown is empty, disable it
var items = this.$dropMenu.children( 'li' );
if ( items.length === 0 ) {
this.$button.addClass( 'disabled' );
}
};
Combobox.prototype = {
constructor: Combobox,
destroy: function() {
this.$element.remove();
// remove any external bindings
// [none]
// set input value attrbute in markup
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup
// [none]
return this.$element[ 0 ].outerHTML;
},
doSelect: function( $item ) {
if ( typeof $item[ 0 ] !== 'undefined' ) {
this.$selectedItem = $item;
this.$input.val( this.$selectedItem.text().trim() );
} else {
this.$selectedItem = null;
}
},
menuShown: function() {
if ( this.options.autoResizeMenu ) {
this.resizeMenu();
}
},
resizeMenu: function() {
var width = this.$element.outerWidth();
this.$dropMenu.outerWidth( width );
},
selectedItem: function() {
var item = this.$selectedItem;
var data = {};
if ( item ) {
var txt = this.$selectedItem.text().trim();
data = $.extend( {
text: txt
}, this.$selectedItem.data() );
} else {
data = {
text: this.$input.val()
};
}
return data;
},
selectByText: function( text ) {
var $item = $( [] );
this.$element.find( 'li' ).each( function() {
if ( ( this.textContent || this.innerText || $( this ).text() || '' ).toLowerCase() === ( text || '' ).toLowerCase() ) {
$item = $( this );
return false;
}
} );
this.doSelect( $item );
},
selectByValue: function( value ) {
var selector = 'li[data-value="' + value + '"]';
this.selectBySelector( selector );
},
selectByIndex: function( index ) {
// zero-based index
var selector = 'li:eq(' + index + ')';
this.selectBySelector( selector );
},
selectBySelector: function( selector ) {
var $item = this.$element.find( selector );
this.doSelect( $item );
},
setDefaultSelection: function() {
var selector = 'li[data-selected=true]:first';
var item = this.$element.find( selector );
if ( item.length > 0 ) {
// select by data-attribute
this.selectBySelector( selector );
item.removeData( 'selected' );
item.removeAttr( 'data-selected' );
}
},
enable: function() {
this.$element.removeClass( 'disabled' );
this.$input.removeAttr( 'disabled' );
this.$button.removeClass( 'disabled' );
},
disable: function() {
this.$element.addClass( 'disabled' );
this.$input.attr( 'disabled', true );
this.$button.addClass( 'disabled' );
},
itemclicked: function( e ) {
this.$selectedItem = $( e.target ).parent();
// set input text and trigger input change event marked as synthetic
this.$input.val( this.$selectedItem.text().trim() ).trigger( 'change', {
synthetic: true
} );
// pass object including text and any data-attributes
// to onchange event
var data = this.selectedItem();
// trigger changed event
this.$element.trigger( 'changed.fu.combobox', data );
e.preventDefault();
// return focus to control after selecting an option
this.$element.find( '.dropdown-toggle' ).focus();
},
inputchanged: function( e, extra ) {
// skip processing for internally-generated synthetic event
// to avoid double processing
if ( extra && extra.synthetic ) return;
var val = $( e.target ).val();
this.selectByText( val );
// find match based on input
// if no match, pass the input value
var data = this.selectedItem();
if ( data.text.length === 0 ) {
data = {
text: val
};
}
// trigger changed event
this.$element.trigger( 'changed.fu.combobox', data );
}
};
Combobox.prototype.getValue = Combobox.prototype.selectedItem;
// COMBOBOX PLUGIN DEFINITION
$.fn.combobox = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.combobox' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.combobox', ( data = new Combobox( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.combobox.defaults = {
autoResizeMenu: true
};
$.fn.combobox.Constructor = Combobox;
$.fn.combobox.noConflict = function() {
$.fn.combobox = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.combobox.data-api', '[data-initialize=combobox]', function( e ) {
var $control = $( e.target ).closest( '.combobox' );
if ( !$control.data( 'fu.combobox' ) ) {
$control.combobox( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=combobox]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.combobox' ) ) {
$this.combobox( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Datepicker
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var INVALID_DATE = 'Invalid Date';
var MOMENT_NOT_AVAILABLE = 'moment.js is not available so you cannot use this function';
var datepickerStack = [];
var moment = false;
var old = $.fn.datepicker;
var requestedMoment = false;
var runStack = function() {
var i, l;
requestedMoment = true;
for ( i = 0, l = datepickerStack.length; i < l; i++ ) {
datepickerStack[ i ].init.call( datepickerStack[ i ].scope );
}
datepickerStack = [];
};
//only load moment if it's there. otherwise we'll look for it in window.moment
if ( typeof define === 'function' && define.amd ) { //check if AMD is available
require( [ 'moment' ], function( amdMoment ) {
moment = amdMoment;
runStack();
}, function( err ) {
var failedId = err.requireModules && err.requireModules[ 0 ];
if ( failedId === 'moment' ) {
runStack();
}
} );
} else {
runStack();
}
// DATEPICKER CONSTRUCTOR AND PROTOTYPE
var Datepicker = function( element, options ) {
this.$element = $( element );
this.options = $.extend( true, {}, $.fn.datepicker.defaults, options );
this.$calendar = this.$element.find( '.datepicker-calendar' );
this.$days = this.$calendar.find( '.datepicker-calendar-days' );
this.$header = this.$calendar.find( '.datepicker-calendar-header' );
this.$headerTitle = this.$header.find( '.title' );
this.$input = this.$element.find( 'input' );
this.$inputGroupBtn = this.$element.find( '.input-group-btn' );
this.$wheels = this.$element.find( '.datepicker-wheels' );
this.$wheelsMonth = this.$element.find( '.datepicker-wheels-month' );
this.$wheelsYear = this.$element.find( '.datepicker-wheels-year' );
this.artificialScrolling = false;
this.formatDate = this.options.formatDate || this.formatDate;
this.inputValue = null;
this.moment = false;
this.momentFormat = null;
this.parseDate = this.options.parseDate || this.parseDate;
this.preventBlurHide = false;
this.restricted = this.options.restricted || [];
this.restrictedParsed = [];
this.restrictedText = this.options.restrictedText;
this.sameYearOnly = this.options.sameYearOnly;
this.selectedDate = null;
this.yearRestriction = null;
this.$calendar.find( '.datepicker-today' ).on( 'click.fu.datepicker', $.proxy( this.todayClicked, this ) );
this.$days.on( 'click.fu.datepicker', 'tr td button', $.proxy( this.dateClicked, this ) );
this.$header.find( '.next' ).on( 'click.fu.datepicker', $.proxy( this.next, this ) );
this.$header.find( '.prev' ).on( 'click.fu.datepicker', $.proxy( this.prev, this ) );
this.$headerTitle.on( 'click.fu.datepicker', $.proxy( this.titleClicked, this ) );
this.$input.on( 'change.fu.datepicker', $.proxy( this.inputChanged, this ) );
this.$input.on( 'mousedown.fu.datepicker', $.proxy( this.showDropdown, this ) );
this.$inputGroupBtn.on( 'hidden.bs.dropdown', $.proxy( this.hide, this ) );
this.$inputGroupBtn.on( 'shown.bs.dropdown', $.proxy( this.show, this ) );
this.$wheels.find( '.datepicker-wheels-back' ).on( 'click.fu.datepicker', $.proxy( this.backClicked, this ) );
this.$wheels.find( '.datepicker-wheels-select' ).on( 'click.fu.datepicker', $.proxy( this.selectClicked, this ) );
this.$wheelsMonth.on( 'click.fu.datepicker', 'ul button', $.proxy( this.monthClicked, this ) );
this.$wheelsYear.on( 'click.fu.datepicker', 'ul button', $.proxy( this.yearClicked, this ) );
this.$wheelsYear.find( 'ul' ).on( 'scroll.fu.datepicker', $.proxy( this.onYearScroll, this ) );
var init = function() {
if ( this.checkForMomentJS() ) {
moment = moment || window.moment; // need to pull in the global moment if they didn't do it via require
this.moment = true;
this.momentFormat = this.options.momentConfig.format;
this.setCulture( this.options.momentConfig.culture );
// support moment with lang (< v2.8) or locale
moment.locale = moment.locale || moment.lang;
}
this.setRestrictedDates( this.restricted );
if ( !this.setDate( this.options.date ) ) {
this.$input.val( '' );
this.inputValue = this.$input.val();
}
if ( this.sameYearOnly ) {
this.yearRestriction = ( this.selectedDate ) ? this.selectedDate.getFullYear() : new Date().getFullYear();
}
};
if ( requestedMoment ) {
init.call( this );
} else {
datepickerStack.push( {
init: init,
scope: this
} );
}
};
Datepicker.prototype = {
constructor: Datepicker,
backClicked: function() {
this.changeView( 'calendar' );
},
changeView: function( view, date ) {
if ( view === 'wheels' ) {
this.$calendar.hide().attr( 'aria-hidden', 'true' );
this.$wheels.show().removeAttr( 'aria-hidden', '' );
if ( date ) {
this.renderWheel( date );
}
} else {
this.$wheels.hide().attr( 'aria-hidden', 'true' );
this.$calendar.show().removeAttr( 'aria-hidden', '' );
if ( date ) {
this.renderMonth( date );
}
}
},
checkForMomentJS: function() {
if (
( $.isFunction( window.moment ) || ( typeof moment !== 'undefined' && $.isFunction( moment ) ) ) &&
$.isPlainObject( this.options.momentConfig ) &&
( typeof this.options.momentConfig.culture === 'string' && typeof this.options.momentConfig.format === 'string' )
) {
return true;
} else {
return false;
}
},
dateClicked: function( e ) {
var $td = $( e.currentTarget ).parents( 'td:first' );
var date;
if ( $td.hasClass( 'restricted' ) ) {
return;
}
this.$days.find( 'td.selected' ).removeClass( 'selected' );
$td.addClass( 'selected' );
date = new Date( $td.attr( 'data-year' ), $td.attr( 'data-month' ), $td.attr( 'data-date' ) );
this.selectedDate = date;
this.$input.val( this.formatDate( date ) );
this.inputValue = this.$input.val();
this.hide();
this.$input.focus();
this.$element.trigger( 'dateClicked.fu.datepicker', date );
},
destroy: function() {
this.$element.remove();
// any external bindings
// [none]
// empty elements to return to original markup
this.$days.find( 'tbody' ).empty();
this.$wheelsYear.find( 'ul' ).empty();
return this.$element[ 0 ].outerHTML;
},
disable: function() {
this.$element.addClass( 'disabled' );
this.$element.find( 'input, button' ).attr( 'disabled', 'disabled' );
this.$inputGroupBtn.removeClass( 'open' );
},
enable: function() {
this.$element.removeClass( 'disabled' );
this.$element.find( 'input, button' ).removeAttr( 'disabled' );
},
formatDate: function( date ) {
var padTwo = function( value ) {
var s = '0' + value;
return s.substr( s.length - 2 );
};
if ( this.moment ) {
return moment( date ).format( this.momentFormat );
} else {
return padTwo( date.getMonth() + 1 ) + '/' + padTwo( date.getDate() ) + '/' + date.getFullYear();
}
},
getCulture: function() {
if ( this.moment ) {
return moment.locale();
} else {
throw MOMENT_NOT_AVAILABLE;
}
},
getDate: function() {
return ( !this.selectedDate ) ? new Date( NaN ) : this.selectedDate;
},
getFormat: function() {
if ( this.moment ) {
return this.momentFormat;
} else {
throw MOMENT_NOT_AVAILABLE;
}
},
getFormattedDate: function() {
return ( !this.selectedDate ) ? INVALID_DATE : this.formatDate( this.selectedDate );
},
getRestrictedDates: function() {
return this.restricted;
},
inputChanged: function() {
var inputVal = this.$input.val();
var date;
if ( inputVal !== this.inputValue ) {
date = this.setDate( inputVal );
if ( date === null ) {
this.$element.trigger( 'inputParsingFailed.fu.datepicker', inputVal );
} else if ( date === false ) {
this.$element.trigger( 'inputRestrictedDate.fu.datepicker', date );
} else {
this.$element.trigger( 'changed.fu.datepicker', date );
}
}
},
show: function() {
var date = ( this.selectedDate ) ? this.selectedDate : new Date();
this.changeView( 'calendar', date );
this.$inputGroupBtn.addClass( 'open' );
this.$element.trigger( 'shown.fu.datepicker' );
},
showDropdown: function( e ) { //input mousedown handler, name retained for legacy support of showDropdown
if ( !this.$input.is( ':focus' ) && !this.$inputGroupBtn.hasClass( 'open' ) ) {
this.show();
}
},
hide: function() {
this.$inputGroupBtn.removeClass( 'open' );
this.$element.trigger( 'hidden.fu.datepicker' );
},
hideDropdown: function() { //for legacy support of hideDropdown
this.hide();
},
isInvalidDate: function( date ) {
var dateString = date.toString();
if ( dateString === INVALID_DATE || dateString === 'NaN' ) {
return true;
}
return false;
},
isRestricted: function( date, month, year ) {
var restricted = this.restrictedParsed;
var i, from, l, to;
if ( this.sameYearOnly && this.yearRestriction !== null && year !== this.yearRestriction ) {
return true;
}
for ( i = 0, l = restricted.length; i < l; i++ ) {
from = restricted[ i ].from;
to = restricted[ i ].to;
if (
( year > from.year || ( year === from.year && month > from.month ) || ( year === from.year && month === from.month && date >= from.date ) ) &&
( year < to.year || ( year === to.year && month < to.month ) || ( year === to.year && month === to.month && date <= to.date ) )
) {
return true;
}
}
return false;
},
monthClicked: function( e ) {
this.$wheelsMonth.find( '.selected' ).removeClass( 'selected' );
$( e.currentTarget ).parent().addClass( 'selected' );
},
next: function() {
var month = this.$headerTitle.attr( 'data-month' );
var year = this.$headerTitle.attr( 'data-year' );
month++;
if ( month > 11 ) {
if ( this.sameYearOnly ) {
return;
}
month = 0;
year++;
}
this.renderMonth( new Date( year, month, 1 ) );
},
onYearScroll: function( e ) {
if ( this.artificialScrolling ) {
return;
}
var $yearUl = $( e.currentTarget );
var height = ( $yearUl.css( 'box-sizing' ) === 'border-box' ) ? $yearUl.outerHeight() : $yearUl.height();
var scrollHeight = $yearUl.get( 0 ).scrollHeight;
var scrollTop = $yearUl.scrollTop();
var bottomPercentage = ( height / ( scrollHeight - scrollTop ) ) * 100;
var topPercentage = ( scrollTop / scrollHeight ) * 100;
var i, start;
if ( topPercentage < 5 ) {
start = parseInt( $yearUl.find( 'li:first' ).attr( 'data-year' ), 10 );
for ( i = ( start - 1 ); i > ( start - 11 ); i-- ) {
$yearUl.prepend( '<li data-year="' + i + '"><button type="button">' + i + '</button></li>' );
}
this.artificialScrolling = true;
$yearUl.scrollTop( ( $yearUl.get( 0 ).scrollHeight - scrollHeight ) + scrollTop );
this.artificialScrolling = false;
} else if ( bottomPercentage > 90 ) {
start = parseInt( $yearUl.find( 'li:last' ).attr( 'data-year' ), 10 );
for ( i = ( start + 1 ); i < ( start + 11 ); i++ ) {
$yearUl.append( '<li data-year="' + i + '"><button type="button">' + i + '</button></li>' );
}
}
},
//some code ripped from http://stackoverflow.com/questions/2182246/javascript-dates-in-ie-nan-firefox-chrome-ok
parseDate: function( date ) {
var self = this;
var BAD_DATE = new Date( NaN );
var dt, isoExp, momentParse, momentParseWithFormat, tryMomentParseAll, month, parts, use;
if ( date ) {
if ( this.moment ) { //if we have moment, use that to parse the dates
momentParseWithFormat = function( d ) {
var md = moment( d, self.momentFormat );
return ( true === md.isValid() ) ? md.toDate() : BAD_DATE;
};
momentParse = function( d ) {
var md = moment( new Date( d ) );
return ( true === md.isValid() ) ? md.toDate() : BAD_DATE;
};
tryMomentParseAll = function( d, parseFunc1, parseFunc2 ) {
var pd = parseFunc1( d );
if ( !self.isInvalidDate( pd ) ) {
return pd;
}
pd = parseFunc2( pd );
if ( !self.isInvalidDate( pd ) ) {
return pd;
}
return BAD_DATE;
};
if ( 'string' === typeof( date ) ) {
// Attempts to parse date strings using this.momentFormat, falling back on newing a date
return tryMomentParseAll( date, momentParseWithFormat, momentParse );
} else {
// Attempts to parse date by newing a date object directly, falling back on parsing using this.momentFormat
return tryMomentParseAll( date, momentParse, momentParseWithFormat );
}
} else { //if moment isn't present, use previous date parsing strategy
if ( typeof( date ) === 'string' ) {
dt = new Date( Date.parse( date ) );
if ( !this.isInvalidDate( dt ) ) {
return dt;
} else {
date = date.split( 'T' )[ 0 ];
isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/;
parts = isoExp.exec( date );
if ( parts ) {
month = parseInt( parts[ 2 ], 10 );
dt = new Date( parts[ 1 ], month - 1, parts[ 3 ] );
if ( month === ( dt.getMonth() + 1 ) ) {
return dt;
}
}
}
} else {
dt = new Date( date );
if ( !this.isInvalidDate( dt ) ) {
return dt;
}
}
}
}
return new Date( NaN );
},
prev: function() {
var month = this.$headerTitle.attr( 'data-month' );
var year = this.$headerTitle.attr( 'data-year' );
month--;
if ( month < 0 ) {
if ( this.sameYearOnly ) {
return;
}
month = 11;
year--;
}
this.renderMonth( new Date( year, month, 1 ) );
},
renderMonth: function( date ) {
date = date || new Date();
var firstDay = new Date( date.getFullYear(), date.getMonth(), 1 ).getDay();
var lastDate = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate();
var lastMonthDate = new Date( date.getFullYear(), date.getMonth(), 0 ).getDate();
var $month = this.$headerTitle.find( '.month' );
var month = date.getMonth();
var now = new Date();
var nowDate = now.getDate();
var nowMonth = now.getMonth();
var nowYear = now.getFullYear();
var selected = this.selectedDate;
var $tbody = this.$days.find( 'tbody' );
var year = date.getFullYear();
var curDate, curMonth, curYear, i, j, rows, stage, previousStage, lastStage, $td, $tr;
if ( selected ) {
selected = {
date: selected.getDate(),
month: selected.getMonth(),
year: selected.getFullYear()
};
}
$month.find( '.current' ).removeClass( 'current' );
$month.find( 'span[data-month="' + month + '"]' ).addClass( 'current' );
this.$headerTitle.find( '.year' ).text( year );
this.$headerTitle.attr( {
'data-month': month,
'data-year': year
} );
$tbody.empty();
if ( firstDay !== 0 ) {
curDate = lastMonthDate - firstDay + 1;
stage = -1;
} else {
curDate = 1;
stage = 0;
}
rows = ( lastDate <= ( 35 - firstDay ) ) ? 5 : 6;
for ( i = 0; i < rows; i++ ) {
$tr = $( '<tr></tr>' );
for ( j = 0; j < 7; j++ ) {
$td = $( '<td></td>' );
if ( stage === -1 ) {
$td.addClass( 'last-month' );
if ( previousStage !== stage ) {
$td.addClass( 'first' );
}
} else if ( stage === 1 ) {
$td.addClass( 'next-month' );
if ( previousStage !== stage ) {
$td.addClass( 'first' );
}
}
curMonth = month + stage;
curYear = year;
if ( curMonth < 0 ) {
curMonth = 11;
curYear--;
} else if ( curMonth > 11 ) {
curMonth = 0;
curYear++;
}
$td.attr( {
'data-date': curDate,
'data-month': curMonth,
'data-year': curYear
} );
if ( curYear === nowYear && curMonth === nowMonth && curDate === nowDate ) {
$td.addClass( 'current-day' );
} else if ( curYear < nowYear || ( curYear === nowYear && curMonth < nowMonth ) ||
( curYear === nowYear && curMonth === nowMonth && curDate < nowDate ) ) {
$td.addClass( 'past' );
if ( !this.options.allowPastDates ) {
$td.addClass( 'restricted' ).attr( 'title', this.restrictedText );
}
}
if ( this.isRestricted( curDate, curMonth, curYear ) ) {
$td.addClass( 'restricted' ).attr( 'title', this.restrictedText );
}
if ( selected && curYear === selected.year && curMonth === selected.month && curDate === selected.date ) {
$td.addClass( 'selected' );
}
if ( $td.hasClass( 'restricted' ) ) {
$td.html( '<span><b class="datepicker-date">' + curDate + '</b></span>' );
} else {
$td.html( '<span><button type="button" class="datepicker-date">' + curDate + '</button></span>' );
}
curDate++;
lastStage = previousStage;
previousStage = stage;
if ( stage === -1 && curDate > lastMonthDate ) {
curDate = 1;
stage = 0;
if ( lastStage !== stage ) {
$td.addClass( 'last' );
}
} else if ( stage === 0 && curDate > lastDate ) {
curDate = 1;
stage = 1;
if ( lastStage !== stage ) {
$td.addClass( 'last' );
}
}
if ( i === ( rows - 1 ) && j === 6 ) {
$td.addClass( 'last' );
}
$tr.append( $td );
}
$tbody.append( $tr );
}
},
renderWheel: function( date ) {
var month = date.getMonth();
var $monthUl = this.$wheelsMonth.find( 'ul' );
var year = date.getFullYear();
var $yearUl = this.$wheelsYear.find( 'ul' );
var i, $monthSelected, $yearSelected;
if ( this.sameYearOnly ) {
this.$wheelsMonth.addClass( 'full' );
this.$wheelsYear.addClass( 'hidden' );
} else {
this.$wheelsMonth.removeClass( 'full' );
this.$wheelsYear.removeClass( 'hide hidden' ); // .hide is deprecated
}
$monthUl.find( '.selected' ).removeClass( 'selected' );
$monthSelected = $monthUl.find( 'li[data-month="' + month + '"]' );
$monthSelected.addClass( 'selected' );
$monthUl.scrollTop( $monthUl.scrollTop() + ( $monthSelected.position().top - $monthUl.outerHeight() / 2 - $monthSelected.outerHeight( true ) / 2 ) );
$yearUl.empty();
for ( i = ( year - 10 ); i < ( year + 11 ); i++ ) {
$yearUl.append( '<li data-year="' + i + '"><button type="button">' + i + '</button></li>' );
}
$yearSelected = $yearUl.find( 'li[data-year="' + year + '"]' );
$yearSelected.addClass( 'selected' );
this.artificialScrolling = true;
$yearUl.scrollTop( $yearUl.scrollTop() + ( $yearSelected.position().top - $yearUl.outerHeight() / 2 - $yearSelected.outerHeight( true ) / 2 ) );
this.artificialScrolling = false;
$monthSelected.find( 'button' ).focus();
},
selectClicked: function() {
var month = this.$wheelsMonth.find( '.selected' ).attr( 'data-month' );
var year = this.$wheelsYear.find( '.selected' ).attr( 'data-year' );
this.changeView( 'calendar', new Date( year, month, 1 ) );
},
setCulture: function( cultureCode ) {
if ( !cultureCode ) {
return false;
}
if ( this.moment ) {
moment.locale( cultureCode );
} else {
throw MOMENT_NOT_AVAILABLE;
}
},
setDate: function( date ) {
var parsed = this.parseDate( date );
if ( !this.isInvalidDate( parsed ) ) {
if ( !this.isRestricted( parsed.getDate(), parsed.getMonth(), parsed.getFullYear() ) ) {
this.selectedDate = parsed;
this.renderMonth( parsed );
this.$input.val( this.formatDate( parsed ) );
} else {
this.selectedDate = false;
this.renderMonth();
}
} else {
this.selectedDate = null;
this.renderMonth();
}
this.inputValue = this.$input.val();
return this.selectedDate;
},
setFormat: function( format ) {
if ( !format ) {
return false;
}
if ( this.moment ) {
this.momentFormat = format;
} else {
throw MOMENT_NOT_AVAILABLE;
}
},
setRestrictedDates: function( restricted ) {
var parsed = [];
var self = this;
var i, l;
var parseItem = function( val ) {
if ( val === -Infinity ) {
return {
date: -Infinity,
month: -Infinity,
year: -Infinity
};
} else if ( val === Infinity ) {
return {
date: Infinity,
month: Infinity,
year: Infinity
};
} else {
val = self.parseDate( val );
return {
date: val.getDate(),
month: val.getMonth(),
year: val.getFullYear()
};
}
};
this.restricted = restricted;
for ( i = 0, l = restricted.length; i < l; i++ ) {
parsed.push( {
from: parseItem( restricted[ i ].from ),
to: parseItem( restricted[ i ].to )
} );
}
this.restrictedParsed = parsed;
},
titleClicked: function( e ) {
this.changeView( 'wheels', new Date( this.$headerTitle.attr( 'data-year' ), this.$headerTitle.attr( 'data-month' ), 1 ) );
},
todayClicked: function( e ) {
var date = new Date();
if ( ( date.getMonth() + '' ) !== this.$headerTitle.attr( 'data-month' ) || ( date.getFullYear() + '' ) !== this.$headerTitle.attr( 'data-year' ) ) {
this.renderMonth( date );
}
},
yearClicked: function( e ) {
this.$wheelsYear.find( '.selected' ).removeClass( 'selected' );
$( e.currentTarget ).parent().addClass( 'selected' );
}
};
//for control library consistency
Datepicker.prototype.getValue = Datepicker.prototype.getDate;
// DATEPICKER PLUGIN DEFINITION
$.fn.datepicker = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.datepicker' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.datepicker', ( data = new Datepicker( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.datepicker.defaults = {
allowPastDates: false,
date: new Date(),
formatDate: null,
momentConfig: {
culture: 'en',
format: 'L' // more formats can be found here http://momentjs.com/docs/#/customization/long-date-formats/.
},
parseDate: null,
restricted: [], //accepts an array of objects formatted as so: { from: {{date}}, to: {{date}} } (ex: [ { from: new Date('12/11/2014'), to: new Date('03/31/2015') } ])
restrictedText: 'Restricted',
sameYearOnly: false
};
$.fn.datepicker.Constructor = Datepicker;
$.fn.datepicker.noConflict = function() {
$.fn.datepicker = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.datepicker.data-api', '[data-initialize=datepicker]', function( e ) {
var $control = $( e.target ).closest( '.datepicker' );
if ( !$control.data( 'datepicker' ) ) {
$control.datepicker( $control.data() );
}
} );
//used to prevent the dropdown from closing when clicking within it's bounds
$( document ).on( 'click.fu.datepicker.data-api', '.datepicker .dropdown-menu', function( e ) {
var $target = $( e.target );
if ( !$target.is( '.datepicker-date' ) || $target.closest( '.restricted' ).length ) {
e.stopPropagation();
}
} );
//used to prevent the dropdown from closing when clicking on the input
$( document ).on( 'click.fu.datepicker.data-api', '.datepicker input', function( e ) {
e.stopPropagation();
} );
$( function() {
$( '[data-initialize=datepicker]' ).each( function() {
var $this = $( this );
if ( $this.data( 'datepicker' ) ) {
return;
}
$this.datepicker( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Dropdown Auto Flip
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
$( document.body ).on( 'click.fu.dropdown-autoflip', '[data-toggle=dropdown][data-flip]', function( event ) {
if ( $( this ).data().flip === "auto" ) {
// have the drop down decide where to place itself
_autoFlip( $( this ).next( '.dropdown-menu' ) );
}
} );
// For pillbox suggestions dropdown
$( document.body ).on( 'suggested.fu.pillbox', function( event, element ) {
_autoFlip( $( element ) );
$( element ).parent().addClass( 'open' );
} );
function _autoFlip( menu ) {
// hide while the browser thinks
$( menu ).css( {
visibility: "hidden"
} );
// decide where to put menu
if ( dropUpCheck( menu ) ) {
menu.parent().addClass( "dropup" );
} else {
menu.parent().removeClass( "dropup" );
}
// show again
$( menu ).css( {
visibility: "visible"
} );
}
function dropUpCheck( element ) {
// caching container
var $container = _getContainer( element );
// building object with measurementsances for later use
var measurements = {};
measurements.parentHeight = element.parent().outerHeight();
measurements.parentOffsetTop = element.parent().offset().top;
measurements.dropdownHeight = element.outerHeight();
measurements.containerHeight = $container.overflowElement.outerHeight();
// this needs to be different if the window is the container or another element is
measurements.containerOffsetTop = ( !!$container.isWindow ) ? $container.overflowElement.scrollTop() : $container.overflowElement.offset().top;
// doing the calculations
measurements.fromTop = measurements.parentOffsetTop - measurements.containerOffsetTop;
measurements.fromBottom = measurements.containerHeight - measurements.parentHeight - ( measurements.parentOffsetTop - measurements.containerOffsetTop );
// actual determination of where to put menu
// false = drop down
// true = drop up
if ( measurements.dropdownHeight < measurements.fromBottom ) {
return false;
} else if ( measurements.dropdownHeight < measurements.fromTop ) {
return true;
} else if ( measurements.dropdownHeight >= measurements.fromTop && measurements.dropdownHeight >= measurements.fromBottom ) {
// decide which one is bigger and put it there
if ( measurements.fromTop >= measurements.fromBottom ) {
return true;
} else {
return false;
}
}
}
function _getContainer( element ) {
var targetSelector = element.attr( 'data-target' );
var isWindow = true;
var containerElement;
if ( !targetSelector ) {
// no selection so find the relevant ancestor
$.each( element.parents(), function( index, parentElement ) {
if ( $( parentElement ).css( 'overflow' ) !== 'visible' ) {
containerElement = parentElement;
isWindow = false;
return false;
}
} );
} else if ( targetSelector !== 'window' ) {
containerElement = $( targetSelector );
isWindow = false;
}
// fallback to window
if ( isWindow ) {
containerElement = window;
}
return {
overflowElement: $( containerElement ),
isWindow: isWindow
};
}
// register empty plugin
$.fn.dropdownautoflip = function() {
/* empty */
};
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Loader
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.loader;
// LOADER CONSTRUCTOR AND PROTOTYPE
var Loader = function( element, options ) {
this.$element = $( element );
this.options = $.extend( {}, $.fn.loader.defaults, options );
this.begin = ( this.$element.is( '[data-begin]' ) ) ? parseInt( this.$element.attr( 'data-begin' ), 10 ) : 1;
this.delay = ( this.$element.is( '[data-delay]' ) ) ? parseFloat( this.$element.attr( 'data-delay' ) ) : 150;
this.end = ( this.$element.is( '[data-end]' ) ) ? parseInt( this.$element.attr( 'data-end' ), 10 ) : 8;
this.frame = ( this.$element.is( '[data-frame]' ) ) ? parseInt( this.$element.attr( 'data-frame' ), 10 ) : this.begin;
this.isIElt9 = false;
this.timeout = {};
var ieVer = this.msieVersion();
if ( ieVer !== false && ieVer < 9 ) {
this.$element.addClass( 'iefix' );
this.isIElt9 = true;
}
this.$element.attr( 'data-frame', this.frame + '' );
this.play();
};
Loader.prototype = {
constructor: Loader,
destroy: function() {
this.pause();
this.$element.remove();
// any external bindings
// [none]
// empty elements to return to original markup
// [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
ieRepaint: function() {
if ( this.isIElt9 ) {
this.$element.addClass( 'iefix_repaint' ).removeClass( 'iefix_repaint' );
}
},
msieVersion: function() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf( 'MSIE ' );
if ( msie > 0 ) {
return parseInt( ua.substring( msie + 5, ua.indexOf( ".", msie ) ), 10 );
} else {
return false;
}
},
next: function() {
this.frame++;
if ( this.frame > this.end ) {
this.frame = this.begin;
}
this.$element.attr( 'data-frame', this.frame + '' );
this.ieRepaint();
},
pause: function() {
clearTimeout( this.timeout );
},
play: function() {
var self = this;
clearTimeout( this.timeout );
this.timeout = setTimeout( function() {
self.next();
self.play();
}, this.delay );
},
previous: function() {
this.frame--;
if ( this.frame < this.begin ) {
this.frame = this.end;
}
this.$element.attr( 'data-frame', this.frame + '' );
this.ieRepaint();
},
reset: function() {
this.frame = this.begin;
this.$element.attr( 'data-frame', this.frame + '' );
this.ieRepaint();
}
};
// LOADER PLUGIN DEFINITION
$.fn.loader = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.loader' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.loader', ( data = new Loader( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.loader.defaults = {};
$.fn.loader.Constructor = Loader;
$.fn.loader.noConflict = function() {
$.fn.loader = old;
return this;
};
// INIT LOADER ON DOMCONTENTLOADED
$( function() {
$( '[data-initialize=loader]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.loader' ) ) {
$this.loader( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Placard
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.placard;
var EVENT_CALLBACK_MAP = {
'accepted': 'onAccept',
'cancelled': 'onCancel'
};
// PLACARD CONSTRUCTOR AND PROTOTYPE
var Placard = function Placard( element, options ) {
var self = this;
this.$element = $( element );
this.options = $.extend( {}, $.fn.placard.defaults, options );
if ( this.$element.attr( 'data-ellipsis' ) === 'true' ) {
this.options.applyEllipsis = true;
}
this.$accept = this.$element.find( '.placard-accept' );
this.$cancel = this.$element.find( '.placard-cancel' );
this.$field = this.$element.find( '.placard-field' );
this.$footer = this.$element.find( '.placard-footer' );
this.$header = this.$element.find( '.placard-header' );
this.$popup = this.$element.find( '.placard-popup' );
this.actualValue = null;
this.clickStamp = '_';
this.previousValue = '';
if ( this.options.revertOnCancel === -1 ) {
this.options.revertOnCancel = ( this.$accept.length > 0 );
}
// Placard supports inputs, textareas, or contenteditable divs. These checks determine which is being used
this.isContentEditableDiv = this.$field.is( 'div' );
this.isInput = this.$field.is( 'input' );
this.divInTextareaMode = ( this.isContentEditableDiv && this.$field.attr( 'data-textarea' ) === 'true' );
this.$field.on( 'focus.fu.placard', $.proxy( this.show, this ) );
this.$field.on( 'keydown.fu.placard', $.proxy( this.keyComplete, this ) );
this.$element.on( 'close.fu.placard', $.proxy( this.hide, this ) );
this.$accept.on( 'click.fu.placard', $.proxy( this.complete, this, 'accepted' ) );
this.$cancel.on( 'click.fu.placard', function( e ) {
e.preventDefault();
self.complete( 'cancelled' );
} );
this.applyEllipsis();
};
var _isShown = function _isShown( placard ) {
return placard.$element.hasClass( 'showing' );
};
var _closeOtherPlacards = function _closeOtherPlacards() {
var otherPlacards;
otherPlacards = $( document ).find( '.placard.showing' );
if ( otherPlacards.length > 0 ) {
if ( otherPlacards.data( 'fu.placard' ) && otherPlacards.data( 'fu.placard' ).options.explicit ) {
return false; //failed
}
otherPlacards.placard( 'externalClickListener', {}, true );
}
return true; //succeeded
};
Placard.prototype = {
constructor: Placard,
complete: function complete( action ) {
var func = this.options[ EVENT_CALLBACK_MAP[ action ] ];
var obj = {
previousValue: this.previousValue,
value: this.getValue()
};
if ( func ) {
func( obj );
this.$element.trigger( action + '.fu.placard', obj );
} else {
if ( action === 'cancelled' && this.options.revertOnCancel ) {
this.setValue( this.previousValue, true );
}
this.$element.trigger( action + '.fu.placard', obj );
this.hide();
}
},
keyComplete: function keyComplete( e ) {
if ( ( ( this.isContentEditableDiv && !this.divInTextareaMode ) || this.isInput ) && e.keyCode === 13 ) {
this.complete( 'accepted' );
this.$field.blur();
} else if ( e.keyCode === 27 ) {
this.complete( 'cancelled' );
this.$field.blur();
}
},
destroy: function destroy() {
this.$element.remove();
// remove any external bindings
$( document ).off( 'click.fu.placard.externalClick.' + this.clickStamp );
// set input value attribute
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup
// [none]
// return string of markup
return this.$element[ 0 ].outerHTML;
},
disable: function disable() {
this.$element.addClass( 'disabled' );
this.$field.attr( 'disabled', 'disabled' );
if ( this.isContentEditableDiv ) {
this.$field.removeAttr( 'contenteditable' );
}
this.hide();
},
applyEllipsis: function applyEllipsis() {
var field, i, str;
if ( this.options.applyEllipsis ) {
field = this.$field.get( 0 );
if ( ( this.isContentEditableDiv && !this.divInTextareaMode ) || this.isInput ) {
field.scrollLeft = 0;
} else {
field.scrollTop = 0;
if ( field.clientHeight < field.scrollHeight ) {
this.actualValue = this.getValue();
this.setValue( '', true );
str = '';
i = 0;
while ( field.clientHeight >= field.scrollHeight ) {
str += this.actualValue[ i ];
this.setValue( str + '...', true );
i++;
}
str = ( str.length > 0 ) ? str.substring( 0, str.length - 1 ) : '';
this.setValue( str + '...', true );
}
}
}
},
enable: function enable() {
this.$element.removeClass( 'disabled' );
this.$field.removeAttr( 'disabled' );
if ( this.isContentEditableDiv ) {
this.$field.attr( 'contenteditable', 'true' );
}
},
externalClickListener: function externalClickListener( e, force ) {
if ( force === true || this.isExternalClick( e ) ) {
this.complete( this.options.externalClickAction );
}
},
getValue: function getValue() {
if ( this.actualValue !== null ) {
return this.actualValue;
} else if ( this.isContentEditableDiv ) {
return this.$field.html();
} else {
return this.$field.val();
}
},
hide: function hide() {
if ( !this.$element.hasClass( 'showing' ) ) {
return;
}
this.$element.removeClass( 'showing' );
this.applyEllipsis();
$( document ).off( 'click.fu.placard.externalClick.' + this.clickStamp );
this.$element.trigger( 'hidden.fu.placard' );
},
isExternalClick: function isExternalClick( e ) {
var el = this.$element.get( 0 );
var exceptions = this.options.externalClickExceptions || [];
var $originEl = $( e.target );
var i, l;
if ( e.target === el || $originEl.parents( '.placard:first' ).get( 0 ) === el ) {
return false;
} else {
for ( i = 0, l = exceptions.length; i < l; i++ ) {
if ( $originEl.is( exceptions[ i ] ) || $originEl.parents( exceptions[ i ] ).length > 0 ) {
return false;
}
}
}
return true;
},
/**
* setValue() sets the Placard triggering DOM element's display value
*
* @param {String} the value to be displayed
* @param {Boolean} If you want to explicitly suppress the application
* of ellipsis, pass `true`. This would typically only be
* done from internal functions (like `applyEllipsis`)
* that want to avoid circular logic. Otherwise, the
* value of the option applyEllipsis will be used.
* @return {Object} jQuery object representing the DOM element whose
* value was set
*/
setValue: function setValue( val, suppressEllipsis ) {
//if suppressEllipsis is undefined, check placards init settings
if ( typeof suppressEllipsis === 'undefined' ) {
suppressEllipsis = !this.options.applyEllipsis;
}
if ( this.isContentEditableDiv ) {
this.$field.empty().append( val );
} else {
this.$field.val( val );
}
if ( !suppressEllipsis && !_isShown( this ) ) {
this.applyEllipsis();
}
return this.$field;
},
show: function show() {
if ( _isShown( this ) ) {
return;
}
if ( !_closeOtherPlacards() ) {
return;
}
this.previousValue = ( this.isContentEditableDiv ) ? this.$field.html() : this.$field.val();
if ( this.actualValue !== null ) {
this.setValue( this.actualValue, true );
this.actualValue = null;
}
this.showPlacard();
},
showPlacard: function showPlacard() {
this.$element.addClass( 'showing' );
if ( this.$header.length > 0 ) {
this.$popup.css( 'top', '-' + this.$header.outerHeight( true ) + 'px' );
}
if ( this.$footer.length > 0 ) {
this.$popup.css( 'bottom', '-' + this.$footer.outerHeight( true ) + 'px' );
}
this.$element.trigger( 'shown.fu.placard' );
this.clickStamp = new Date().getTime() + ( Math.floor( Math.random() * 100 ) + 1 );
if ( !this.options.explicit ) {
$( document ).on( 'click.fu.placard.externalClick.' + this.clickStamp, $.proxy( this.externalClickListener, this ) );
}
}
};
// PLACARD PLUGIN DEFINITION
$.fn.placard = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.placard' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.placard', ( data = new Placard( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.placard.defaults = {
onAccept: undefined,
onCancel: undefined,
externalClickAction: 'cancelled',
externalClickExceptions: [],
explicit: false,
revertOnCancel: -1, //negative 1 will check for an '.placard-accept' button. Also can be set to true or false
applyEllipsis: false
};
$.fn.placard.Constructor = Placard;
$.fn.placard.noConflict = function() {
$.fn.placard = old;
return this;
};
// DATA-API
$( document ).on( 'focus.fu.placard.data-api', '[data-initialize=placard]', function( e ) {
var $control = $( e.target ).closest( '.placard' );
if ( !$control.data( 'fu.placard' ) ) {
$control.placard( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=placard]' ).each( function() {
var $this = $( this );
if ( $this.data( 'fu.placard' ) ) return;
$this.placard( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Radio
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.radio;
// RADIO CONSTRUCTOR AND PROTOTYPE
var Radio = function( element, options ) {
this.options = $.extend( {}, $.fn.radio.defaults, options );
if ( element.tagName.toLowerCase() !== 'label' ) {
//console.log('initialize radio on the label that wraps the radio');
return;
}
// cache elements
this.$label = $( element );
this.$radio = this.$label.find( 'input[type="radio"]' );
this.groupName = this.$radio.attr( 'name' ); // don't cache group itself since items can be added programmatically
// determine if a toggle container is specified
var containerSelector = this.$radio.attr( 'data-toggle' );
this.$toggleContainer = $( containerSelector );
// handle internal events
this.$radio.on( 'change', $.proxy( this.itemchecked, this ) );
// set default state
this.setInitialState();
};
Radio.prototype = {
constructor: Radio,
setInitialState: function() {
var $radio = this.$radio;
var $lbl = this.$label;
// get current state of input
var checked = $radio.prop( 'checked' );
var disabled = $radio.prop( 'disabled' );
// sync label class with input state
this.setCheckedState( $radio, checked );
this.setDisabledState( $radio, disabled );
},
resetGroup: function() {
var $radios = $( 'input[name="' + this.groupName + '"]' );
$radios.each( function( index, item ) {
var $radio = $( item );
var $lbl = $radio.parent();
var containerSelector = $radio.attr( 'data-toggle' );
var $containerToggle = $( containerSelector );
$lbl.removeClass( 'checked' );
$containerToggle.addClass( 'hidden' );
} );
},
setCheckedState: function( element, checked ) {
var $radio = element;
var $lbl = $radio.parent();
var containerSelector = $radio.attr( 'data-toggle' );
var $containerToggle = $( containerSelector );
if ( checked ) {
// reset all items in group
this.resetGroup();
$radio.prop( 'checked', true );
$lbl.addClass( 'checked' );
$containerToggle.removeClass( 'hide hidden' );
$lbl.trigger( 'checked.fu.radio' );
} else {
$radio.prop( 'checked', false );
$lbl.removeClass( 'checked' );
$containerToggle.addClass( 'hidden' );
$lbl.trigger( 'unchecked.fu.radio' );
}
$lbl.trigger( 'changed.fu.radio', checked );
},
setDisabledState: function( element, disabled ) {
var $radio = element;
var $lbl = this.$label;
if ( disabled ) {
this.$radio.prop( 'disabled', true );
$lbl.addClass( 'disabled' );
$lbl.trigger( 'disabled.fu.radio' );
} else {
this.$radio.prop( 'disabled', false );
$lbl.removeClass( 'disabled' );
$lbl.trigger( 'enabled.fu.radio' );
}
},
itemchecked: function( evt ) {
var $radio = $( evt.target );
this.setCheckedState( $radio, true );
},
check: function() {
this.setCheckedState( this.$radio, true );
},
uncheck: function() {
this.setCheckedState( this.$radio, false );
},
isChecked: function() {
var checked = this.$radio.prop( 'checked' );
return checked;
},
enable: function() {
this.setDisabledState( this.$radio, false );
},
disable: function() {
this.setDisabledState( this.$radio, true );
},
destroy: function() {
this.$label.remove();
// remove any external bindings
// [none]
// empty elements to return to original markup
// [none]
return this.$label[ 0 ].outerHTML;
}
};
Radio.prototype.getValue = Radio.prototype.isChecked;
// RADIO PLUGIN DEFINITION
$.fn.radio = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.radio' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.radio', ( data = new Radio( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.radio.defaults = {};
$.fn.radio.Constructor = Radio;
$.fn.radio.noConflict = function() {
$.fn.radio = old;
return this;
};
// DATA-API
$( document ).on( 'mouseover.fu.radio.data-api', '[data-initialize=radio]', function( e ) {
var $control = $( e.target );
if ( !$control.data( 'fu.radio' ) ) {
$control.radio( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=radio]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.radio' ) ) {
$this.radio( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Search
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.search;
// SEARCH CONSTRUCTOR AND PROTOTYPE
var Search = function( element, options ) {
this.$element = $( element );
this.options = $.extend( {}, $.fn.search.defaults, options );
if ( this.$element.attr( 'data-searchOnKeyPress' ) === 'true' ) {
this.options.searchOnKeyPress = true;
}
this.$button = this.$element.find( 'button' );
this.$input = this.$element.find( 'input' );
this.$icon = this.$element.find( '.glyphicon' );
this.$button.on( 'click.fu.search', $.proxy( this.buttonclicked, this ) );
this.$input.on( 'keyup.fu.search', $.proxy( this.keypress, this ) );
this.activeSearch = '';
};
Search.prototype = {
constructor: Search,
destroy: function() {
this.$element.remove();
// any external bindings
// [none]
// set input value attrbute
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup
// [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
search: function( searchText ) {
if ( this.$icon.hasClass( 'glyphicon' ) ) {
this.$icon.removeClass( 'glyphicon-search' ).addClass( 'glyphicon-remove' );
}
this.activeSearch = searchText;
this.$element.addClass( 'searched' );
this.$element.trigger( 'searched.fu.search', searchText );
},
clear: function() {
if ( this.$icon.hasClass( 'glyphicon' ) ) {
this.$icon.removeClass( 'glyphicon-remove' ).addClass( 'glyphicon-search' );
}
this.activeSearch = '';
this.$input.val( '' );
this.$element.removeClass( 'searched' );
this.$element.trigger( 'cleared.fu.search' );
},
action: function() {
var val = this.$input.val();
if ( val && val.length > 0 ) {
this.search( val );
} else {
this.clear();
}
},
buttonclicked: function( e ) {
e.preventDefault();
if ( $( e.currentTarget ).is( '.disabled, :disabled' ) ) return;
if ( this.$element.hasClass( 'searched' ) ) {
this.clear();
} else {
this.action();
}
},
keypress: function( e ) {
var ENTER_KEY_CODE = 13;
var TAB_KEY_CODE = 9;
var ESC_KEY_CODE = 27;
if ( e.which === ENTER_KEY_CODE ) {
e.preventDefault();
this.action();
} else if ( e.which === TAB_KEY_CODE ) {
e.preventDefault();
} else if ( e.which === ESC_KEY_CODE ) {
e.preventDefault();
this.clear();
} else if ( this.options.searchOnKeyPress ) {
// search on other keypress
this.action();
}
},
disable: function() {
this.$element.addClass( 'disabled' );
this.$input.attr( 'disabled', 'disabled' );
this.$button.addClass( 'disabled' );
},
enable: function() {
this.$element.removeClass( 'disabled' );
this.$input.removeAttr( 'disabled' );
this.$button.removeClass( 'disabled' );
}
};
// SEARCH PLUGIN DEFINITION
$.fn.search = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.search' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.search', ( data = new Search( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.search.defaults = {
clearOnEmpty: false,
searchOnKeyPress: false
};
$.fn.search.Constructor = Search;
$.fn.search.noConflict = function() {
$.fn.search = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.search.data-api', '[data-initialize=search]', function( e ) {
var $control = $( e.target ).closest( '.search' );
if ( !$control.data( 'fu.search' ) ) {
$control.search( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=search]' ).each( function() {
var $this = $( this );
if ( $this.data( 'fu.search' ) ) return;
$this.search( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Selectlist
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.selectlist;
// SELECT CONSTRUCTOR AND PROTOTYPE
var Selectlist = function( element, options ) {
this.$element = $( element );
this.options = $.extend( {}, $.fn.selectlist.defaults, options );
this.$button = this.$element.find( '.btn.dropdown-toggle' );
this.$hiddenField = this.$element.find( '.hidden-field' );
this.$label = this.$element.find( '.selected-label' );
this.$dropdownMenu = this.$element.find( '.dropdown-menu' );
this.$element.on( 'click.fu.selectlist', '.dropdown-menu a', $.proxy( this.itemClicked, this ) );
this.setDefaultSelection();
if ( options.resize === 'auto' || this.$element.attr( 'data-resize' ) === 'auto' ) {
this.resize();
}
// if selectlist is empty or is one item, disable it
var items = this.$dropdownMenu.children( 'li' );
if ( items.length === 0 ) {
this.disable();
this.doSelect( $( this.options.emptyLabelHTML ) );
}
// support jumping focus to first letter in dropdown when key is pressed
this.$element.on( 'shown.bs.dropdown', function() {
var $this = $( this );
// attach key listener when dropdown is shown
$( document ).on( 'keypress.fu.selectlist', function( e ) {
// get the key that was pressed
var key = String.fromCharCode( e.which );
// look the items to find the first item with the first character match and set focus
$this.find( "li" ).each( function( idx, item ) {
if ( $( item ).text().charAt( 0 ).toLowerCase() === key ) {
$( item ).children( 'a' ).focus();
return false;
}
} );
} );
} );
// unbind key event when dropdown is hidden
this.$element.on( 'hide.bs.dropdown', function() {
$( document ).off( 'keypress.fu.selectlist' );
} );
};
Selectlist.prototype = {
constructor: Selectlist,
destroy: function() {
this.$element.remove();
// any external bindings
// [none]
// empty elements to return to original markup
// [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
doSelect: function( $item ) {
var $selectedItem;
this.$selectedItem = $selectedItem = $item;
this.$hiddenField.val( this.$selectedItem.attr( 'data-value' ) );
this.$label.html( $( this.$selectedItem.children()[ 0 ] ).html() );
// clear and set selected item to allow declarative init state
// unlike other controls, selectlist's value is stored internal, not in an input
this.$element.find( 'li' ).each( function() {
if ( $selectedItem.is( $( this ) ) ) {
$( this ).attr( 'data-selected', true );
} else {
$( this ).removeData( 'selected' ).removeAttr( 'data-selected' );
}
} );
},
itemClicked: function( e ) {
this.$element.trigger( 'clicked.fu.selectlist', this.$selectedItem );
e.preventDefault();
// ignore if a disabled item is clicked
if ( $( e.currentTarget ).parent( 'li' ).is( '.disabled, :disabled' ) ) {
return;
}
// is clicked element different from currently selected element?
if ( !( $( e.target ).parent().is( this.$selectedItem ) ) ) {
this.itemChanged( e );
}
// return focus to control after selecting an option
this.$element.find( '.dropdown-toggle' ).focus();
},
itemChanged: function( e ) {
//selectedItem needs to be <li> since the data is stored there, not in <a>
this.doSelect( $( e.target ).closest( 'li' ) );
// pass object including text and any data-attributes
// to onchange event
var data = this.selectedItem();
// trigger changed event
this.$element.trigger( 'changed.fu.selectlist', data );
},
resize: function() {
var width = 0;
var newWidth = 0;
var sizer = $( '<div/>' ).addClass( 'selectlist-sizer' );
if ( Boolean( $( document ).find( 'html' ).hasClass( 'fuelux' ) ) ) {
// default behavior for fuel ux setup. means fuelux was a class on the html tag
$( document.body ).append( sizer );
} else {
// fuelux is not a class on the html tag. So we'll look for the first one we find so the correct styles get applied to the sizer
$( '.fuelux:first' ).append( sizer );
}
sizer.append( this.$element.clone() );
this.$element.find( 'a' ).each( function() {
sizer.find( '.selected-label' ).text( $( this ).text() );
newWidth = sizer.find( '.selectlist' ).outerWidth();
newWidth = newWidth + sizer.find( '.sr-only' ).outerWidth();
if ( newWidth > width ) {
width = newWidth;
}
} );
if ( width <= 1 ) {
return;
}
this.$button.css( 'width', width );
this.$dropdownMenu.css( 'width', width );
sizer.remove();
},
selectedItem: function() {
var txt = this.$selectedItem.text();
return $.extend( {
text: txt
}, this.$selectedItem.data() );
},
selectByText: function( text ) {
var $item = $( [] );
this.$element.find( 'li' ).each( function() {
if ( ( this.textContent || this.innerText || $( this ).text() || '' ).toLowerCase() === ( text || '' ).toLowerCase() ) {
$item = $( this );
return false;
}
} );
this.doSelect( $item );
},
selectByValue: function( value ) {
var selector = 'li[data-value="' + value + '"]';
this.selectBySelector( selector );
},
selectByIndex: function( index ) {
// zero-based index
var selector = 'li:eq(' + index + ')';
this.selectBySelector( selector );
},
selectBySelector: function( selector ) {
var $item = this.$element.find( selector );
this.doSelect( $item );
},
setDefaultSelection: function() {
var $item = this.$element.find( 'li[data-selected=true]' ).eq( 0 );
if ( $item.length === 0 ) {
$item = this.$element.find( 'li' ).has( 'a' ).eq( 0 );
}
this.doSelect( $item );
},
enable: function() {
this.$element.removeClass( 'disabled' );
this.$button.removeClass( 'disabled' );
},
disable: function() {
this.$element.addClass( 'disabled' );
this.$button.addClass( 'disabled' );
}
};
Selectlist.prototype.getValue = Selectlist.prototype.selectedItem;
// SELECT PLUGIN DEFINITION
$.fn.selectlist = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.selectlist' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.selectlist', ( data = new Selectlist( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.selectlist.defaults = {
emptyLabelHTML: '<li data-value=""><a href="#">No items</a></li>'
};
$.fn.selectlist.Constructor = Selectlist;
$.fn.selectlist.noConflict = function() {
$.fn.selectlist = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.selectlist.data-api', '[data-initialize=selectlist]', function( e ) {
var $control = $( e.target ).closest( '.selectlist' );
if ( !$control.data( 'fu.selectlist' ) ) {
$control.selectlist( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=selectlist]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.selectlist' ) ) {
$this.selectlist( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Spinbox
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.spinbox;
// SPINBOX CONSTRUCTOR AND PROTOTYPE
var Spinbox = function Spinbox( element, options ) {
this.$element = $( element );
this.$element.find( '.btn' ).on( 'click', function( e ) {
//keep spinbox from submitting if they forgot to say type="button" on their spinner buttons
e.preventDefault();
} );
this.options = $.extend( {}, $.fn.spinbox.defaults, options );
this.options.step = this.$element.data( 'step' ) || this.options.step;
if ( this.options.value < this.options.min ) {
this.options.value = this.options.min;
} else if ( this.options.max < this.options.value ) {
this.options.value = this.options.max;
}
this.$input = this.$element.find( '.spinbox-input' );
this.$input.on( 'focusout.fu.spinbox', this.$input, $.proxy( this.change, this ) );
this.$element.on( 'keydown.fu.spinbox', this.$input, $.proxy( this.keydown, this ) );
this.$element.on( 'keyup.fu.spinbox', this.$input, $.proxy( this.keyup, this ) );
this.bindMousewheelListeners();
this.mousewheelTimeout = {};
if ( this.options.hold ) {
this.$element.on( 'mousedown.fu.spinbox', '.spinbox-up', $.proxy( function() {
this.startSpin( true );
}, this ) );
this.$element.on( 'mouseup.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy( this.stopSpin, this ) );
this.$element.on( 'mouseout.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy( this.stopSpin, this ) );
this.$element.on( 'mousedown.fu.spinbox', '.spinbox-down', $.proxy( function() {
this.startSpin( false );
}, this ) );
} else {
this.$element.on( 'click.fu.spinbox', '.spinbox-up', $.proxy( function() {
this.step( true );
}, this ) );
this.$element.on( 'click.fu.spinbox', '.spinbox-down', $.proxy( function() {
this.step( false );
}, this ) );
}
this.switches = {
count: 1,
enabled: true
};
if ( this.options.speed === 'medium' ) {
this.switches.speed = 300;
} else if ( this.options.speed === 'fast' ) {
this.switches.speed = 100;
} else {
this.switches.speed = 500;
}
this.options.defaultUnit = _isUnitLegal( this.options.defaultUnit, this.options.units ) ? this.options.defaultUnit : '';
this.unit = this.options.defaultUnit;
this.lastValue = this.options.value;
this.render();
if ( this.options.disabled ) {
this.disable();
}
};
// Truly private methods
var _limitToStep = function _limitToStep( number, step ) {
return Math.round( number / step ) * step;
};
var _isUnitLegal = function _isUnitLegal( unit, validUnits ) {
var legalUnit = false;
var suspectUnit = unit.toLowerCase();
$.each( validUnits, function( i, validUnit ) {
validUnit = validUnit.toLowerCase();
if ( suspectUnit === validUnit ) {
legalUnit = true;
return false; //break out of the loop
}
} );
return legalUnit;
};
var _applyLimits = function _applyLimits( value ) {
// if unreadable
if ( isNaN( parseFloat( value ) ) ) {
return value;
}
// if not within range return the limit
if ( value > this.options.max ) {
if ( this.options.cycle ) {
value = this.options.min;
} else {
value = this.options.max;
}
} else if ( value < this.options.min ) {
if ( this.options.cycle ) {
value = this.options.max;
} else {
value = this.options.min;
}
}
if ( this.options.limitToStep && this.options.step ) {
value = _limitToStep( value, this.options.step );
//force round direction so that it stays within bounds
if ( value > this.options.max ) {
value = value - this.options.step;
} else if ( value < this.options.min ) {
value = value + this.options.step;
}
}
return value;
};
Spinbox.prototype = {
constructor: Spinbox,
destroy: function destroy() {
this.$element.remove();
// any external bindings
// [none]
// set input value attrbute
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup
// [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
render: function render() {
this.setValue( this.getDisplayValue() );
},
change: function change() {
this.setValue( this.getDisplayValue() );
this.triggerChangedEvent();
},
stopSpin: function stopSpin() {
if ( this.switches.timeout !== undefined ) {
clearTimeout( this.switches.timeout );
this.switches.count = 1;
this.triggerChangedEvent();
}
},
triggerChangedEvent: function triggerChangedEvent() {
var currentValue = this.getValue();
if ( currentValue === this.lastValue ) return;
this.lastValue = currentValue;
// Primary changed event
this.$element.trigger( 'changed.fu.spinbox', currentValue );
},
startSpin: function startSpin( type ) {
if ( !this.options.disabled ) {
var divisor = this.switches.count;
if ( divisor === 1 ) {
this.step( type );
divisor = 1;
} else if ( divisor < 3 ) {
divisor = 1.5;
} else if ( divisor < 8 ) {
divisor = 2.5;
} else {
divisor = 4;
}
this.switches.timeout = setTimeout( $.proxy( function() {
this.iterate( type );
}, this ), this.switches.speed / divisor );
this.switches.count++;
}
},
iterate: function iterate( type ) {
this.step( type );
this.startSpin( type );
},
step: function step( isIncrease ) {
//refresh value from display before trying to increment in case they have just been typing before clicking the nubbins
this.setValue( this.getDisplayValue() );
var newVal;
if ( isIncrease ) {
newVal = this.options.value + this.options.step;
} else {
newVal = this.options.value - this.options.step;
}
newVal = newVal.toFixed( 5 );
this.setValue( newVal + this.unit );
},
getDisplayValue: function getDisplayValue() {
var inputValue = this.parseInput( this.$input.val() );
var value = ( !!inputValue ) ? inputValue : this.options.value;
return value;
},
setDisplayValue: function setDisplayValue( value ) {
this.$input.val( value );
},
getValue: function getValue() {
var val = this.options.value;
if ( this.options.decimalMark !== '.' ) {
val = ( val + '' ).split( '.' ).join( this.options.decimalMark );
}
return val + this.unit;
},
setValue: function setValue( val ) {
//remove any i18n on the number
if ( this.options.decimalMark !== '.' ) {
val = this.parseInput( val );
}
//are we dealing with united numbers?
if ( typeof val !== "number" ) {
var potentialUnit = val.replace( /[0-9.-]/g, '' );
//make sure unit is valid, or else drop it in favor of current unit, or default unit (potentially nothing)
this.unit = _isUnitLegal( potentialUnit, this.options.units ) ? potentialUnit : this.options.defaultUnit;
}
var intVal = this.getIntValue( val );
//make sure we are dealing with a number
if ( isNaN( intVal ) && !isFinite( intVal ) ) {
return this.setValue( this.options.value );
}
//conform
intVal = _applyLimits.call( this, intVal );
//cache the pure int value
this.options.value = intVal;
//prepare number for display
val = intVal + this.unit;
if ( this.options.decimalMark !== '.' ) {
val = ( val + '' ).split( '.' ).join( this.options.decimalMark );
}
//display number
this.setDisplayValue( val );
return this;
},
value: function value( val ) {
if ( val || val === 0 ) {
return this.setValue( val );
} else {
return this.getValue();
}
},
parseInput: function parseInput( value ) {
value = ( value + '' ).split( this.options.decimalMark ).join( '.' );
return value;
},
getIntValue: function getIntValue( value ) {
//if they didn't pass in a number, try and get the number
value = ( typeof value === "undefined" ) ? this.getValue() : value;
// if there still isn't a number, abort
if ( typeof value === "undefined" ) {
return;
}
if ( typeof value === 'string' ) {
value = this.parseInput( value );
}
value = parseFloat( value, 10 );
return value;
},
disable: function disable() {
this.options.disabled = true;
this.$element.addClass( 'disabled' );
this.$input.attr( 'disabled', '' );
this.$element.find( 'button' ).addClass( 'disabled' );
},
enable: function enable() {
this.options.disabled = false;
this.$element.removeClass( 'disabled' );
this.$input.removeAttr( 'disabled' );
this.$element.find( 'button' ).removeClass( 'disabled' );
},
keydown: function keydown( event ) {
var keyCode = event.keyCode;
if ( keyCode === 38 ) {
this.step( true );
} else if ( keyCode === 40 ) {
this.step( false );
} else if ( keyCode === 13 ) {
this.change();
}
},
keyup: function keyup( event ) {
var keyCode = event.keyCode;
if ( keyCode === 38 || keyCode === 40 ) {
this.triggerChangedEvent();
}
},
bindMousewheelListeners: function bindMousewheelListeners() {
var inputEl = this.$input.get( 0 );
if ( inputEl.addEventListener ) {
//IE 9, Chrome, Safari, Opera
inputEl.addEventListener( 'mousewheel', $.proxy( this.mousewheelHandler, this ), false );
// Firefox
inputEl.addEventListener( 'DOMMouseScroll', $.proxy( this.mousewheelHandler, this ), false );
} else {
// IE <9
inputEl.attachEvent( 'onmousewheel', $.proxy( this.mousewheelHandler, this ) );
}
},
mousewheelHandler: function mousewheelHandler( event ) {
if ( !this.options.disabled ) {
var e = window.event || event; // old IE support
var delta = Math.max( -1, Math.min( 1, ( e.wheelDelta || -e.detail ) ) );
var self = this;
clearTimeout( this.mousewheelTimeout );
this.mousewheelTimeout = setTimeout( function() {
self.triggerChangedEvent();
}, 300 );
if ( delta < 0 ) {
this.step( true );
} else {
this.step( false );
}
if ( e.preventDefault ) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
};
// SPINBOX PLUGIN DEFINITION
$.fn.spinbox = function spinbox( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.spinbox' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.spinbox', ( data = new Spinbox( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
// value needs to be 0 for this.render();
$.fn.spinbox.defaults = {
value: 0,
min: 0,
max: 999,
step: 1,
hold: true,
speed: 'medium',
disabled: false,
cycle: false,
units: [],
decimalMark: '.',
defaultUnit: '',
limitToStep: false
};
$.fn.spinbox.Constructor = Spinbox;
$.fn.spinbox.noConflict = function noConflict() {
$.fn.spinbox = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.spinbox.data-api', '[data-initialize=spinbox]', function( e ) {
var $control = $( e.target ).closest( '.spinbox' );
if ( !$control.data( 'fu.spinbox' ) ) {
$control.spinbox( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=spinbox]' ).each( function() {
var $this = $( this );
if ( !$this.data( 'fu.spinbox' ) ) {
$this.spinbox( $this.data() );
}
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Tree
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.tree;
// TREE CONSTRUCTOR AND PROTOTYPE
var Tree = function Tree( element, options ) {
this.$element = $( element );
this.options = $.extend( {}, $.fn.tree.defaults, options );
if ( this.options.itemSelect ) {
this.$element.on( 'click.fu.tree', '.tree-item', $.proxy( function( ev ) {
this.selectItem( ev.currentTarget );
}, this ) );
}
this.$element.on( 'click.fu.tree', '.tree-branch-name', $.proxy( function( ev ) {
this.toggleFolder( ev.currentTarget );
}, this ) );
// folderSelect default is true
if ( this.options.folderSelect ) {
this.$element.addClass( 'tree-folder-select' );
this.$element.off( 'click.fu.tree', '.tree-branch-name' );
this.$element.on( 'click.fu.tree', '.icon-caret', $.proxy( function( ev ) {
this.toggleFolder( $( ev.currentTarget ).parent() );
}, this ) );
this.$element.on( 'click.fu.tree', '.tree-branch-name', $.proxy( function( ev ) {
this.selectFolder( $( ev.currentTarget ) );
}, this ) );
}
this.render();
};
Tree.prototype = {
constructor: Tree,
deselectAll: function deselectAll( nodes ) {
// clear all child tree nodes and style as deselected
nodes = nodes || this.$element;
var $selectedElements = $( nodes ).find( '.tree-selected' );
$selectedElements.each( function( index, element ) {
styleNodeDeselected( $( element ), $( element ).find( '.glyphicon' ) );
} );
return $selectedElements;
},
destroy: function destroy() {
// any external bindings [none]
// empty elements to return to original markup
this.$element.find( "li:not([data-template])" ).remove();
this.$element.remove();
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
render: function render() {
this.populate( this.$element );
},
populate: function populate( $el, isBackgroundProcess ) {
var self = this;
var $parent = ( $el.hasClass( 'tree' ) ) ? $el : $el.parent();
var loader = $parent.find( '.tree-loader:eq(0)' );
var treeData = $parent.data();
isBackgroundProcess = isBackgroundProcess || false; // no user affordance needed (ex.- "loading")
if ( isBackgroundProcess === false ) {
loader.removeClass( 'hide hidden' ); // hide is deprecated
}
this.options.dataSource( treeData ? treeData : {}, function( items ) {
loader.addClass( 'hidden' );
$.each( items.data, function( index, value ) {
var $entity;
if ( value.type === 'folder' ) {
$entity = self.$element.find( '[data-template=treebranch]:eq(0)' ).clone().removeClass( 'hide hidden' ).removeData( 'template' ); // hide is deprecated
$entity.data( value );
$entity.find( '.tree-branch-name > .tree-label' ).html( value.text || value.name );
} else if ( value.type === 'item' ) {
$entity = self.$element.find( '[data-template=treeitem]:eq(0)' ).clone().removeClass( 'hide hidden' ).removeData( 'template' ); // hide is deprecated
$entity.find( '.tree-item-name > .tree-label' ).html( value.text || value.name );
$entity.data( value );
}
// Decorate $entity with data or other attributes making the
// element easily accessable with libraries like jQuery.
//
// Values are contained within the object returned
// for folders and items as attr:
//
// {
// text: "An Item",
// type: 'item',
// attr = {
// 'classes': 'required-item red-text',
// 'data-parent': parentId,
// 'guid': guid,
// 'id': guid
// }
// };
//
// the "name" attribute is also supported but is deprecated for "text".
// add attributes to tree-branch or tree-item
var attr = value.attr || value.dataAttributes || [];
$.each( attr, function( key, value ) {
switch ( key ) {
case 'cssClass':
case 'class':
case 'className':
$entity.addClass( value );
break;
// allow custom icons
case 'data-icon':
$entity.find( '.icon-item' ).removeClass().addClass( 'icon-item ' + value );
$entity.attr( key, value );
break;
// ARIA support
case 'id':
$entity.attr( key, value );
$entity.attr( 'aria-labelledby', value + '-label' );
$entity.find( '.tree-branch-name > .tree-label' ).attr( 'id', value + '-label' );
break;
// style, data-*
default:
$entity.attr( key, value );
break;
}
} );
// add child nodes
if ( $el.hasClass( 'tree-branch-header' ) ) {
$parent.find( '.tree-branch-children:eq(0)' ).append( $entity );
} else {
$el.append( $entity );
}
} );
// return newly populated folder
self.$element.trigger( 'loaded.fu.tree', $parent );
} );
},
selectTreeNode: function selectItem( clickedElement, nodeType ) {
var clicked = {}; // object for clicked element
clicked.$element = $( clickedElement );
var selected = {}; // object for selected elements
selected.$elements = this.$element.find( '.tree-selected' );
selected.dataForEvent = [];
// determine clicked element and it's icon
if ( nodeType === 'folder' ) {
// make the clicked.$element the container branch
clicked.$element = clicked.$element.closest( '.tree-branch' );
clicked.$icon = clicked.$element.find( '.icon-folder' );
} else {
clicked.$icon = clicked.$element.find( '.icon-item' );
}
clicked.elementData = clicked.$element.data();
// the below functions pass objects by copy/reference and use modified object in this function
if ( this.options.multiSelect ) {
multiSelectSyncNodes( this, clicked, selected );
} else {
singleSelectSyncNodes( this, clicked, selected );
}
// all done with the DOM, now fire events
this.$element.trigger( selected.eventType + '.fu.tree', {
target: clicked.elementData,
selected: selected.dataForEvent
} );
clicked.$element.trigger( 'updated.fu.tree', {
selected: selected.dataForEvent,
item: clicked.$element,
eventType: selected.eventType
} );
},
discloseFolder: function discloseFolder( el ) {
var $el = $( el );
var $branch = $el.closest( '.tree-branch' );
var $treeFolderContent = $branch.find( '.tree-branch-children' );
var $treeFolderContentFirstChild = $treeFolderContent.eq( 0 );
//take care of the styles
$branch.addClass( 'tree-open' );
$branch.attr( 'aria-expanded', 'true' );
$treeFolderContentFirstChild.removeClass( 'hide hidden' ); // hide is deprecated
$branch.find( '> .tree-branch-header .icon-folder' ).eq( 0 )
.removeClass( 'glyphicon-folder-close' )
.addClass( 'glyphicon-folder-open' );
//add the children to the folder
if ( !$treeFolderContent.children().length ) {
this.populate( $treeFolderContent );
}
this.$element.trigger( 'disclosedFolder.fu.tree', $branch.data() );
},
closeFolder: function closeFolder( el ) {
var $el = $( el );
var $branch = $el.closest( '.tree-branch' );
var $treeFolderContent = $branch.find( '.tree-branch-children' );
var $treeFolderContentFirstChild = $treeFolderContent.eq( 0 );
//take care of the styles
$branch.removeClass( 'tree-open' );
$branch.attr( 'aria-expanded', 'false' );
$treeFolderContentFirstChild.addClass( 'hidden' );
$branch.find( '> .tree-branch-header .icon-folder' ).eq( 0 )
.removeClass( 'glyphicon-folder-open' )
.addClass( 'glyphicon-folder-close' );
// remove chidren if no cache
if ( !this.options.cacheItems ) {
$treeFolderContentFirstChild.empty();
}
this.$element.trigger( 'closed.fu.tree', $branch.data() );
},
toggleFolder: function toggleFolder( el ) {
var $el = $( el );
if ( $el.find( '.glyphicon-folder-close' ).length ) {
this.discloseFolder( el );
} else if ( $el.find( '.glyphicon-folder-open' ).length ) {
this.closeFolder( el );
}
},
selectFolder: function selectFolder( el ) {
if ( this.options.folderSelect ) {
this.selectTreeNode( el, 'folder' );
}
},
selectItem: function selectItem( el ) {
if ( this.options.itemSelect ) {
this.selectTreeNode( el, 'item' );
}
},
selectedItems: function selectedItems() {
var $sel = this.$element.find( '.tree-selected' );
var data = [];
$.each( $sel, function( index, value ) {
data.push( $( value ).data() );
} );
return data;
},
// collapses open folders
collapse: function collapse() {
var self = this;
var reportedClosed = [];
var closedReported = function closedReported( event, closed ) {
reportedClosed.push( closed );
// hide is deprecated
if ( self.$element.find( ".tree-branch.tree-open:not('.hidden, .hide')" ).length === 0 ) {
self.$element.trigger( 'closedAll.fu.tree', {
tree: self.$element,
reportedClosed: reportedClosed
} );
self.$element.off( 'loaded.fu.tree', self.$element, closedReported );
}
};
//trigger callback when all folders have reported closed
self.$element.on( 'closed.fu.tree', closedReported );
self.$element.find( ".tree-branch.tree-open:not('.hidden, .hide')" ).each( function() {
self.closeFolder( this );
} );
},
//disclose visible will only disclose visible tree folders
discloseVisible: function discloseVisible() {
var self = this;
var $openableFolders = self.$element.find( ".tree-branch:not('.tree-open, .hidden, .hide')" );
var reportedOpened = [];
var openReported = function openReported( event, opened ) {
reportedOpened.push( opened );
if ( reportedOpened.length === $openableFolders.length ) {
self.$element.trigger( 'disclosedVisible.fu.tree', {
tree: self.$element,
reportedOpened: reportedOpened
} );
/*
* Unbind the `openReported` event. `discloseAll` may be running and we want to reset this
* method for the next iteration.
*/
self.$element.off( 'loaded.fu.tree', self.$element, openReported );
}
};
//trigger callback when all folders have reported opened
self.$element.on( 'loaded.fu.tree', openReported );
// open all visible folders
self.$element.find( ".tree-branch:not('.tree-open, .hidden, .hide')" ).each( function triggerOpen() {
self.discloseFolder( $( this ).find( '.tree-branch-header' ) );
} );
},
/**
* Disclose all will keep listening for `loaded.fu.tree` and if `$(tree-el).data('ignore-disclosures-limit')`
* is `true` (defaults to `true`) it will attempt to disclose any new closed folders than were
* loaded in during the last disclosure.
*/
discloseAll: function discloseAll() {
var self = this;
//first time
if ( typeof self.$element.data( 'disclosures' ) === 'undefined' ) {
self.$element.data( 'disclosures', 0 );
}
var isExceededLimit = ( self.options.disclosuresUpperLimit >= 1 && self.$element.data( 'disclosures' ) >= self.options.disclosuresUpperLimit );
var isAllDisclosed = self.$element.find( ".tree-branch:not('.tree-open, .hidden, .hide')" ).length === 0;
if ( !isAllDisclosed ) {
if ( isExceededLimit ) {
self.$element.trigger( 'exceededDisclosuresLimit.fu.tree', {
tree: self.$element,
disclosures: self.$element.data( 'disclosures' )
} );
/*
* If you've exceeded the limit, the loop will be killed unless you
* explicitly ignore the limit and start the loop again:
*
* $tree.one('exceededDisclosuresLimit.fu.tree', function () {
* $tree.data('ignore-disclosures-limit', true);
* $tree.tree('discloseAll');
* });
*/
if ( !self.$element.data( 'ignore-disclosures-limit' ) ) {
return;
}
}
self.$element.data( 'disclosures', self.$element.data( 'disclosures' ) + 1 );
/*
* A new branch that is closed might be loaded in, make sure those get handled too.
* This attachment needs to occur before calling `discloseVisible` to make sure that
* if the execution of `discloseVisible` happens _super fast_ (as it does in our QUnit tests
* this will still be called. However, make sure this only gets called _once_, because
* otherwise, every single time we go through this loop, _another_ event will be bound
* and then when the trigger happens, this will fire N times, where N equals the number
* of recursive `discloseAll` executions (instead of just one)
*/
self.$element.one( 'disclosedVisible.fu.tree', function() {
self.discloseAll();
} );
/*
* If the page is very fast, calling this first will cause `disclosedVisible.fu.tree` to not
* be bound in time to be called, so, we need to call this last so that the things bound
* and triggered above can have time to take place before the next execution of the
* `discloseAll` method.
*/
self.discloseVisible();
} else {
self.$element.trigger( 'disclosedAll.fu.tree', {
tree: self.$element,
disclosures: self.$element.data( 'disclosures' )
} );
//if `cacheItems` is false, and they call closeAll, the data is trashed and therefore
//disclosures needs to accurately reflect that
if ( !self.options.cacheItems ) {
self.$element.one( 'closeAll.fu.tree', function() {
self.$element.data( 'disclosures', 0 );
} );
}
}
},
// This refreshes the children of a folder. Please destroy and re-initilize for "root level" refresh.
// The data of the refreshed folder is not updated. This control's architecture only allows updating of children.
// Folder renames should probably be handled directly on the node.
refreshFolder: function refreshFolder( $el ) {
var $treeFolder = $el.closest( '.tree-branch' );
var $treeFolderChildren = $treeFolder.find( '.tree-branch-children' );
$treeFolderChildren.eq( 0 ).empty();
if ( $treeFolder.hasClass( 'tree-open' ) ) {
this.populate( $treeFolderChildren, false );
} else {
this.populate( $treeFolderChildren, true );
}
this.$element.trigger( 'refreshedFolder.fu.tree', $treeFolder.data() );
}
};
// ALIASES
//alias for collapse for consistency. "Collapse" is an ambiguous term (collapse what? All? One specific branch?)
Tree.prototype.closeAll = Tree.prototype.collapse;
//alias for backwards compatibility because there's no reason not to.
Tree.prototype.openFolder = Tree.prototype.discloseFolder;
//For library consistency
Tree.prototype.getValue = Tree.prototype.selectedItems;
// PRIVATE FUNCTIONS
function styleNodeSelected( $element, $icon ) {
$element.addClass( 'tree-selected' );
if ( $element.data( 'type' ) === 'item' && $icon.hasClass( 'fueluxicon-bullet' ) ) {
$icon.removeClass( 'fueluxicon-bullet' ).addClass( 'glyphicon-ok' ); // make checkmark
}
}
function styleNodeDeselected( $element, $icon ) {
$element.removeClass( 'tree-selected' );
if ( $element.data( 'type' ) === 'item' && $icon.hasClass( 'glyphicon-ok' ) ) {
$icon.removeClass( 'glyphicon-ok' ).addClass( 'fueluxicon-bullet' ); // make bullet
}
}
function multiSelectSyncNodes( self, clicked, selected ) {
// search for currently selected and add to selected data list if needed
$.each( selected.$elements, function( index, element ) {
var $element = $( element );
if ( $element[ 0 ] !== clicked.$element[ 0 ] ) {
selected.dataForEvent.push( $( $element ).data() );
}
} );
if ( clicked.$element.hasClass( 'tree-selected' ) ) {
styleNodeDeselected( clicked.$element, clicked.$icon );
// set event data
selected.eventType = 'deselected';
} else {
styleNodeSelected( clicked.$element, clicked.$icon );
// set event data
selected.eventType = 'selected';
selected.dataForEvent.push( clicked.elementData );
}
}
function singleSelectSyncNodes( self, clicked, selected ) {
// element is not currently selected
if ( selected.$elements[ 0 ] !== clicked.$element[ 0 ] ) {
var clearedElements = self.deselectAll( self.$element );
styleNodeSelected( clicked.$element, clicked.$icon );
// set event data
selected.eventType = 'selected';
selected.dataForEvent = [ clicked.elementData ];
} else {
styleNodeDeselected( clicked.$element, clicked.$icon );
// set event data
selected.eventType = 'deselected';
selected.dataForEvent = [];
}
}
// TREE PLUGIN DEFINITION
$.fn.tree = function tree( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.tree' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.tree', ( data = new Tree( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.tree.defaults = {
dataSource: function dataSource( options, callback ) {},
multiSelect: false,
cacheItems: true,
folderSelect: true,
itemSelect: true,
/*
* How many times `discloseAll` should be called before a stopping and firing
* an `exceededDisclosuresLimit` event. You can force it to continue by
* listening for this event, setting `ignore-disclosures-limit` to `true` and
* starting `discloseAll` back up again. This lets you make more decisions
* about if/when/how/why/how many times `discloseAll` will be started back
* up after it exceeds the limit.
*
* $tree.one('exceededDisclosuresLimit.fu.tree', function () {
* $tree.data('ignore-disclosures-limit', true);
* $tree.tree('discloseAll');
* });
*
* `disclusuresUpperLimit` defaults to `0`, so by default this trigger
* will never fire. The true hard the upper limit is the browser's
* ability to load new items (i.e. it will keep loading until the browser
* falls over and dies). On the Fuel UX `index.html` page, the point at
* which the page became super slow (enough to seem almost unresponsive)
* was `4`, meaning 256 folders had been opened, and 1024 were attempting to open.
*/
disclosuresUpperLimit: 0
};
$.fn.tree.Constructor = Tree;
$.fn.tree.noConflict = function() {
$.fn.tree = old;
return this;
};
// NO DATA-API DUE TO NEED OF DATA-SOURCE
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Wizard
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.wizard;
// WIZARD CONSTRUCTOR AND PROTOTYPE
var Wizard = function( element, options ) {
var kids;
this.$element = $( element );
this.options = $.extend( {}, $.fn.wizard.defaults, options );
this.options.disablePreviousStep = ( this.$element.attr( 'data-restrict' ) === 'previous' ) ? true : this.options.disablePreviousStep;
this.currentStep = this.options.selectedItem.step;
this.numSteps = this.$element.find( '.steps li' ).length;
this.$prevBtn = this.$element.find( 'button.btn-prev' );
this.$nextBtn = this.$element.find( 'button.btn-next' );
// maintains backwards compatibility with < 3.8, will be removed in the future
if ( this.$element.children( '.steps-container' ).length === 0 ) {
this.$element.addClass( 'no-steps-container' );
if ( window && window.console && window.console.warn ) {
window.console.warn( 'please update your wizard markup to include ".steps-container" as seen in http://getfuelux.com/javascript.html#wizard-usage-markup' );
}
}
kids = this.$nextBtn.children().detach();
this.nextText = $.trim( this.$nextBtn.text() );
this.$nextBtn.append( kids );
// handle events
this.$prevBtn.on( 'click.fu.wizard', $.proxy( this.previous, this ) );
this.$nextBtn.on( 'click.fu.wizard', $.proxy( this.next, this ) );
this.$element.on( 'click.fu.wizard', 'li.complete', $.proxy( this.stepclicked, this ) );
this.selectedItem( this.options.selectedItem );
if ( this.options.disablePreviousStep ) {
this.$prevBtn.attr( 'disabled', true );
this.$element.find( '.steps' ).addClass( 'previous-disabled' );
}
};
Wizard.prototype = {
constructor: Wizard,
destroy: function() {
this.$element.remove();
// any external bindings [none]
// empty elements to return to original markup [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
//index is 1 based
//second parameter can be array of objects [{ ... }, { ... }] or you can pass n additional objects as args
//object structure is as follows (all params are optional): { badge: '', label: '', pane: '' }
addSteps: function( index ) {
var items = [].slice.call( arguments ).slice( 1 );
var $steps = this.$element.find( '.steps' );
var $stepContent = this.$element.find( '.step-content' );
var i, l, $pane, $startPane, $startStep, $step;
index = ( index === -1 || ( index > ( this.numSteps + 1 ) ) ) ? this.numSteps + 1 : index;
if ( items[ 0 ] instanceof Array ) {
items = items[ 0 ];
}
$startStep = $steps.find( 'li:nth-child(' + index + ')' );
$startPane = $stepContent.find( '.step-pane:nth-child(' + index + ')' );
if ( $startStep.length < 1 ) {
$startStep = null;
}
for ( i = 0, l = items.length; i < l; i++ ) {
$step = $( '<li data-step="' + index + '"><span class="badge badge-info"></span></li>' );
$step.append( items[ i ].label || '' ).append( '<span class="chevron"></span>' );
$step.find( '.badge' ).append( items[ i ].badge || index );
$pane = $( '<div class="step-pane" data-step="' + index + '"></div>' );
$pane.append( items[ i ].pane || '' );
if ( !$startStep ) {
$steps.append( $step );
$stepContent.append( $pane );
} else {
$startStep.before( $step );
$startPane.before( $pane );
}
index++;
}
this.syncSteps();
this.numSteps = $steps.find( 'li' ).length;
this.setState();
},
//index is 1 based, howMany is number to remove
removeSteps: function( index, howMany ) {
var action = 'nextAll';
var i = 0;
var $steps = this.$element.find( '.steps' );
var $stepContent = this.$element.find( '.step-content' );
var $start;
howMany = ( howMany !== undefined ) ? howMany : 1;
if ( index > $steps.find( 'li' ).length ) {
$start = $steps.find( 'li:last' );
} else {
$start = $steps.find( 'li:nth-child(' + index + ')' ).prev();
if ( $start.length < 1 ) {
action = 'children';
$start = $steps;
}
}
$start[ action ]().each( function() {
var item = $( this );
var step = item.attr( 'data-step' );
if ( i < howMany ) {
item.remove();
$stepContent.find( '.step-pane[data-step="' + step + '"]:first' ).remove();
} else {
return false;
}
i++;
} );
this.syncSteps();
this.numSteps = $steps.find( 'li' ).length;
this.setState();
},
setState: function() {
var canMovePrev = ( this.currentStep > 1 ); //remember, steps index is 1 based...
var isFirstStep = ( this.currentStep === 1 );
var isLastStep = ( this.currentStep === this.numSteps );
// disable buttons based on current step
if ( !this.options.disablePreviousStep ) {
this.$prevBtn.attr( 'disabled', ( isFirstStep === true || canMovePrev === false ) );
}
// change button text of last step, if specified
var last = this.$nextBtn.attr( 'data-last' );
if ( last ) {
this.lastText = last;
// replace text
var text = this.nextText;
if ( isLastStep === true ) {
text = this.lastText;
// add status class to wizard
this.$element.addClass( 'complete' );
} else {
this.$element.removeClass( 'complete' );
}
var kids = this.$nextBtn.children().detach();
this.$nextBtn.text( text ).append( kids );
}
// reset classes for all steps
var $steps = this.$element.find( '.steps li' );
$steps.removeClass( 'active' ).removeClass( 'complete' );
$steps.find( 'span.badge' ).removeClass( 'badge-info' ).removeClass( 'badge-success' );
// set class for all previous steps
var prevSelector = '.steps li:lt(' + ( this.currentStep - 1 ) + ')';
var $prevSteps = this.$element.find( prevSelector );
$prevSteps.addClass( 'complete' );
$prevSteps.find( 'span.badge' ).addClass( 'badge-success' );
// set class for current step
var currentSelector = '.steps li:eq(' + ( this.currentStep - 1 ) + ')';
var $currentStep = this.$element.find( currentSelector );
$currentStep.addClass( 'active' );
$currentStep.find( 'span.badge' ).addClass( 'badge-info' );
// set display of target element
var $stepContent = this.$element.find( '.step-content' );
var target = $currentStep.attr( 'data-step' );
$stepContent.find( '.step-pane' ).removeClass( 'active' );
$stepContent.find( '.step-pane[data-step="' + target + '"]:first' ).addClass( 'active' );
// reset the wizard position to the left
this.$element.find( '.steps' ).first().attr( 'style', 'margin-left: 0' );
// check if the steps are wider than the container div
var totalWidth = 0;
this.$element.find( '.steps > li' ).each( function() {
totalWidth += $( this ).outerWidth();
} );
var containerWidth = 0;
if ( this.$element.find( '.actions' ).length ) {
containerWidth = this.$element.width() - this.$element.find( '.actions' ).first().outerWidth();
} else {
containerWidth = this.$element.width();
}
if ( totalWidth > containerWidth ) {
// set the position so that the last step is on the right
var newMargin = totalWidth - containerWidth;
this.$element.find( '.steps' ).first().attr( 'style', 'margin-left: -' + newMargin + 'px' );
// set the position so that the active step is in a good
// position if it has been moved out of view
if ( this.$element.find( 'li.active' ).first().position().left < 200 ) {
newMargin += this.$element.find( 'li.active' ).first().position().left - 200;
if ( newMargin < 1 ) {
this.$element.find( '.steps' ).first().attr( 'style', 'margin-left: 0' );
} else {
this.$element.find( '.steps' ).first().attr( 'style', 'margin-left: -' + newMargin + 'px' );
}
}
}
// only fire changed event after initializing
if ( typeof( this.initialized ) !== 'undefined' ) {
var e = $.Event( 'changed.fu.wizard' );
this.$element.trigger( e, {
step: this.currentStep
} );
}
this.initialized = true;
},
stepclicked: function( e ) {
var li = $( e.currentTarget );
var index = this.$element.find( '.steps li' ).index( li );
if ( index < this.currentStep && this.options.disablePreviousStep ) { //enforce restrictions
return;
} else {
var evt = $.Event( 'stepclicked.fu.wizard' );
this.$element.trigger( evt, {
step: index + 1
} );
if ( evt.isDefaultPrevented() ) {
return;
}
this.currentStep = ( index + 1 );
this.setState();
}
},
syncSteps: function() {
var i = 1;
var $steps = this.$element.find( '.steps' );
var $stepContent = this.$element.find( '.step-content' );
$steps.children().each( function() {
var item = $( this );
var badge = item.find( '.badge' );
var step = item.attr( 'data-step' );
if ( !isNaN( parseInt( badge.html(), 10 ) ) ) {
badge.html( i );
}
item.attr( 'data-step', i );
$stepContent.find( '.step-pane[data-step="' + step + '"]:last' ).attr( 'data-step', i );
i++;
} );
},
previous: function() {
if ( this.options.disablePreviousStep || this.currentStep === 1 ) {
return;
}
var e = $.Event( 'actionclicked.fu.wizard' );
this.$element.trigger( e, {
step: this.currentStep,
direction: 'previous'
} );
if ( e.isDefaultPrevented() ) {
return;
} // don't increment ...what? Why?
this.currentStep -= 1;
this.setState();
// only set focus if focus is still on the $nextBtn (avoid stomping on a focus set programmatically in actionclicked callback)
if ( this.$prevBtn.is( ':focus' ) ) {
var firstFormField = this.$element.find( '.active' ).find( 'input, select, textarea' )[ 0 ];
if ( typeof firstFormField !== 'undefined' ) {
// allow user to start typing immediately instead of having to click on the form field.
$( firstFormField ).focus();
} else if ( this.$element.find( '.active input:first' ).length === 0 && this.$prevBtn.is( ':disabled' ) ) {
//only set focus on a button as the last resort if no form fields exist and the just clicked button is now disabled
this.$nextBtn.focus();
}
}
},
next: function() {
var e = $.Event( 'actionclicked.fu.wizard' );
this.$element.trigger( e, {
step: this.currentStep,
direction: 'next'
} );
if ( e.isDefaultPrevented() ) {
return;
} // respect preventDefault in case dev has attached validation to step and wants to stop propagation based on it.
if ( this.currentStep < this.numSteps ) {
this.currentStep += 1;
this.setState();
} else { //is last step
this.$element.trigger( 'finished.fu.wizard' );
}
// only set focus if focus is still on the $nextBtn (avoid stomping on a focus set programmatically in actionclicked callback)
if ( this.$nextBtn.is( ':focus' ) ) {
var firstFormField = this.$element.find( '.active' ).find( 'input, select, textarea' )[ 0 ];
if ( typeof firstFormField !== 'undefined' ) {
// allow user to start typing immediately instead of having to click on the form field.
$( firstFormField ).focus();
} else if ( this.$element.find( '.active input:first' ).length === 0 && this.$nextBtn.is( ':disabled' ) ) {
//only set focus on a button as the last resort if no form fields exist and the just clicked button is now disabled
this.$prevBtn.focus();
}
}
},
selectedItem: function( selectedItem ) {
var retVal, step;
if ( selectedItem ) {
step = selectedItem.step || -1;
//allow selection of step by data-name
step = Number( this.$element.find( '.steps li[data-name="' + step + '"]' ).first().attr( 'data-step' ) ) || Number( step );
if ( 1 <= step && step <= this.numSteps ) {
this.currentStep = step;
this.setState();
} else {
step = this.$element.find( '.steps li.active:first' ).attr( 'data-step' );
if ( !isNaN( step ) ) {
this.currentStep = parseInt( step, 10 );
this.setState();
}
}
retVal = this;
} else {
retVal = {
step: this.currentStep
};
if ( this.$element.find( '.steps li.active:first[data-name]' ).length ) {
retVal.stepname = this.$element.find( '.steps li.active:first' ).attr( 'data-name' );
}
}
return retVal;
}
};
// WIZARD PLUGIN DEFINITION
$.fn.wizard = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.wizard' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.wizard', ( data = new Wizard( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.wizard.defaults = {
disablePreviousStep: false,
selectedItem: {
step: -1
} //-1 means it will attempt to look for "active" class in order to set the step
};
$.fn.wizard.Constructor = Wizard;
$.fn.wizard.noConflict = function() {
$.fn.wizard = old;
return this;
};
// DATA-API
$( document ).on( 'mouseover.fu.wizard.data-api', '[data-initialize=wizard]', function( e ) {
var $control = $( e.target ).closest( '.wizard' );
if ( !$control.data( 'fu.wizard' ) ) {
$control.wizard( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=wizard]' ).each( function() {
var $this = $( this );
if ( $this.data( 'fu.wizard' ) ) return;
$this.wizard( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Infinite Scroll
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.infinitescroll;
// INFINITE SCROLL CONSTRUCTOR AND PROTOTYPE
var InfiniteScroll = function( element, options ) {
this.$element = $( element );
this.$element.addClass( 'infinitescroll' );
this.options = $.extend( {}, $.fn.infinitescroll.defaults, options );
this.curScrollTop = this.$element.scrollTop();
this.curPercentage = this.getPercentage();
this.fetchingData = false;
this.$element.on( 'scroll.fu.infinitescroll', $.proxy( this.onScroll, this ) );
this.onScroll();
};
InfiniteScroll.prototype = {
constructor: InfiniteScroll,
destroy: function() {
this.$element.remove();
// any external bindings
// [none]
// empty elements to return to original markup
this.$element.empty();
return this.$element[ 0 ].outerHTML;
},
disable: function() {
this.$element.off( 'scroll.fu.infinitescroll' );
},
enable: function() {
this.$element.on( 'scroll.fu.infinitescroll', $.proxy( this.onScroll, this ) );
},
end: function( content ) {
var end = $( '<div class="infinitescroll-end"></div>' );
if ( content ) {
end.append( content );
} else {
end.append( '---------' );
}
this.$element.append( end );
this.disable();
},
getPercentage: function() {
var height = ( this.$element.css( 'box-sizing' ) === 'border-box' ) ? this.$element.outerHeight() : this.$element.height();
var scrollHeight = this.$element.get( 0 ).scrollHeight;
return ( scrollHeight > height ) ? ( ( height / ( scrollHeight - this.curScrollTop ) ) * 100 ) : 0;
},
fetchData: function( force ) {
var load = $( '<div class="infinitescroll-load"></div>' );
var self = this;
var moreBtn;
var fetch = function() {
var helpers = {
percentage: self.curPercentage,
scrollTop: self.curScrollTop
};
var $loader = $( '<div class="loader"></div>' );
load.append( $loader );
$loader.loader();
if ( self.options.dataSource ) {
self.options.dataSource( helpers, function( resp ) {
var end;
load.remove();
if ( resp.content ) {
self.$element.append( resp.content );
}
if ( resp.end ) {
end = ( resp.end !== true ) ? resp.end : undefined;
self.end( end );
}
self.fetchingData = false;
} );
}
};
this.fetchingData = true;
this.$element.append( load );
if ( this.options.hybrid && force !== true ) {
moreBtn = $( '<button type="button" class="btn btn-primary"></button>' );
if ( typeof this.options.hybrid === 'object' ) {
moreBtn.append( this.options.hybrid.label );
} else {
moreBtn.append( '<span class="glyphicon glyphicon-repeat"></span>' );
}
moreBtn.on( 'click.fu.infinitescroll', function() {
moreBtn.remove();
fetch();
} );
load.append( moreBtn );
} else {
fetch();
}
},
onScroll: function( e ) {
this.curScrollTop = this.$element.scrollTop();
this.curPercentage = this.getPercentage();
if ( !this.fetchingData && this.curPercentage >= this.options.percentage ) {
this.fetchData();
}
}
};
// INFINITE SCROLL PLUGIN DEFINITION
$.fn.infinitescroll = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.infinitescroll' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.infinitescroll', ( data = new InfiniteScroll( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.infinitescroll.defaults = {
dataSource: null,
hybrid: false, //can be true or an object with structure: { 'label': (markup or jQuery obj) }
percentage: 95 //percentage scrolled to the bottom before more is loaded
};
$.fn.infinitescroll.Constructor = InfiniteScroll;
$.fn.infinitescroll.noConflict = function() {
$.fn.infinitescroll = old;
return this;
};
// NO DATA-API DUE TO NEED OF DATA-SOURCE
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Pillbox
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.pillbox;
// PILLBOX CONSTRUCTOR AND PROTOTYPE
var Pillbox = function( element, options ) {
this.$element = $( element );
this.$moreCount = this.$element.find( '.pillbox-more-count' );
this.$pillGroup = this.$element.find( '.pill-group' );
this.$addItem = this.$element.find( '.pillbox-add-item' );
this.$addItemWrap = this.$addItem.parent();
this.$suggest = this.$element.find( '.suggest' );
this.$pillHTML = '<li class="btn btn-default pill">' +
' <span></span>' +
' <span class="glyphicon glyphicon-close">' +
' <span class="sr-only">Remove</span>' +
' </span>' +
'</li>';
this.options = $.extend( {}, $.fn.pillbox.defaults, options );
if ( this.options.readonly === -1 ) {
if ( this.$element.attr( 'data-readonly' ) !== undefined ) {
this.readonly( true );
}
} else if ( this.options.readonly ) {
this.readonly( true );
}
// EVENTS
this.acceptKeyCodes = this._generateObject( this.options.acceptKeyCodes );
// Creatie an object out of the key code array, so we dont have to loop through it on every key stroke
this.$element.on( 'click.fu.pillbox', '.pill-group > .pill', $.proxy( this.itemClicked, this ) );
this.$element.on( 'click.fu.pillbox', $.proxy( this.inputFocus, this ) );
this.$element.on( 'keydown.fu.pillbox', '.pillbox-add-item', $.proxy( this.inputEvent, this ) );
if ( this.options.onKeyDown ) {
this.$element.on( 'mousedown.fu.pillbox', '.suggest > li', $.proxy( this.suggestionClick, this ) );
}
if ( this.options.edit ) {
this.$element.addClass( 'pills-editable' );
this.$element.on( 'blur.fu.pillbox', '.pillbox-add-item', $.proxy( this.cancelEdit, this ) );
}
};
Pillbox.prototype = {
constructor: Pillbox,
destroy: function() {
this.$element.remove();
// any external bindings
// [none]
// empty elements to return to original markup
// [none]
// returns string of markup
return this.$element[ 0 ].outerHTML;
},
items: function() {
var self = this;
return this.$pillGroup.children( '.pill' ).map( function() {
return self.getItemData( $( this ) );
} ).get();
},
itemClicked: function( e ) {
var self = this;
var $target = $( e.target );
var $item;
e.preventDefault();
e.stopPropagation();
this._closeSuggestions();
if ( !$target.hasClass( 'pill' ) ) {
$item = $target.parent();
if ( this.$element.attr( 'data-readonly' ) === undefined ) {
if ( $target.hasClass( 'glyphicon-close' ) ) {
if ( this.options.onRemove ) {
this.options.onRemove( this.getItemData( $item, {
el: $item
} ), $.proxy( this._removeElement, this ) );
} else {
this._removeElement( this.getItemData( $item, {
el: $item
} ) );
}
return false;
} else if ( this.options.edit ) {
if ( $item.find( '.pillbox-list-edit' ).length ) {
return false;
}
this.openEdit( $item );
}
}
} else {
$item = $target;
}
this.$element.trigger( 'clicked.fu.pillbox', this.getItemData( $item ) );
},
readonly: function( enable ) {
if ( enable ) {
this.$element.attr( 'data-readonly', 'readonly' );
} else {
this.$element.removeAttr( 'data-readonly' );
}
if ( this.options.truncate ) {
this.truncate( enable );
}
},
suggestionClick: function( e ) {
var $item = $( e.currentTarget );
var item = {
text: $item.html(),
value: $item.data( 'value' )
};
e.preventDefault();
this.$addItem.val( '' );
if ( $item.data( 'attr' ) ) {
item.attr = JSON.parse( $item.data( 'attr' ) );
}
item.data = $item.data( 'data' );
this.addItems( item, true );
// needs to be after addItems for IE
this._closeSuggestions();
},
itemCount: function() {
return this.$pillGroup.children( '.pill' ).length;
},
// First parameter is 1 based index (optional, if index is not passed all new items will be appended)
// Second parameter can be array of objects [{ ... }, { ... }] or you can pass n additional objects as args
// object structure is as follows (attr and value are optional): { text: '', value: '', attr: {}, data: {} }
addItems: function() {
var self = this;
var items, index, isInternal;
if ( isFinite( String( arguments[ 0 ] ) ) && !( arguments[ 0 ] instanceof Array ) ) {
items = [].slice.call( arguments ).slice( 1 );
index = arguments[ 0 ];
} else {
items = [].slice.call( arguments ).slice( 0 );
isInternal = items[ 1 ] && !items[ 1 ].text;
}
//If first argument is an array, use that, otherwise they probably passed each thing through as a separate arg, so use items as-is
if ( items[ 0 ] instanceof Array ) {
items = items[ 0 ];
}
if ( items.length ) {
$.each( items, function( i, value ) {
var data = {
text: value.text,
value: ( value.value ? value.value : value.text ),
el: self.$pillHTML
};
if ( value.attr ) {
data.attr = value.attr;
}
if ( value.data ) {
data.data = value.data;
}
items[ i ] = data;
} );
if ( this.options.edit && this.currentEdit ) {
items[ 0 ].el = this.currentEdit.wrap( '<div></div>' ).parent().html();
}
if ( isInternal ) {
items.pop( 1 );
}
if ( self.options.onAdd && isInternal ) {
if ( this.options.edit && this.currentEdit ) {
self.options.onAdd( items[ 0 ], $.proxy( self.saveEdit, this ) );
} else {
self.options.onAdd( items[ 0 ], $.proxy( self.placeItems, this ) );
}
} else {
if ( this.options.edit && this.currentEdit ) {
self.saveEdit( items );
} else {
if ( index ) {
self.placeItems( index, items );
} else {
self.placeItems( items, isInternal );
}
}
}
}
},
//First parameter is the index (1 based) to start removing items
//Second parameter is the number of items to be removed
removeItems: function( index, howMany ) {
var self = this;
var count;
var $currentItem;
if ( !index ) {
this.$pillGroup.find( '.pill' ).remove();
this._removePillTrigger( {
method: 'removeAll'
} );
} else {
howMany = howMany ? howMany : 1;
for ( count = 0; count < howMany; count++ ) {
$currentItem = self.$pillGroup.find( '> .pill:nth-child(' + index + ')' );
if ( $currentItem ) {
$currentItem.remove();
} else {
break;
}
}
}
},
//First parameter is index (optional)
//Second parameter is new arguments
placeItems: function() {
var $newHtml = [];
var items;
var index;
var $neighbor;
var isInternal;
if ( isFinite( String( arguments[ 0 ] ) ) && !( arguments[ 0 ] instanceof Array ) ) {
items = [].slice.call( arguments ).slice( 1 );
index = arguments[ 0 ];
} else {
items = [].slice.call( arguments ).slice( 0 );
isInternal = items[ 1 ] && !items[ 1 ].text;
}
if ( items[ 0 ] instanceof Array ) {
items = items[ 0 ];
}
if ( items.length ) {
$.each( items, function( i, item ) {
var $item = $( item.el );
var $neighbor;
$item.attr( 'data-value', item.value );
$item.find( 'span:first' ).html( item.text );
// DOM attributes
if ( item.attr ) {
$.each( item.attr, function( key, value ) {
if ( key === 'cssClass' || key === 'class' ) {
$item.addClass( value );
} else {
$item.attr( key, value );
}
} );
}
if ( item.data ) {
$item.data( 'data', item.data );
}
$newHtml.push( $item );
} );
if ( this.$pillGroup.children( '.pill' ).length > 0 ) {
if ( index ) {
$neighbor = this.$pillGroup.find( '.pill:nth-child(' + index + ')' );
if ( $neighbor.length ) {
$neighbor.before( $newHtml );
} else {
this.$pillGroup.children( '.pill:last' ).after( $newHtml );
}
} else {
this.$pillGroup.children( '.pill:last' ).after( $newHtml );
}
} else {
this.$pillGroup.prepend( $newHtml );
}
if ( isInternal ) {
this.$element.trigger( 'added.fu.pillbox', {
text: items[ 0 ].text,
value: items[ 0 ].value
} );
}
}
},
inputEvent: function( e ) {
var self = this;
var text = this.$addItem.val();
var value;
var attr;
var $lastItem;
var $selection;
if ( this.acceptKeyCodes[ e.keyCode ] ) {
if ( this.options.onKeyDown && this._isSuggestionsOpen() ) {
$selection = this.$suggest.find( '.pillbox-suggest-sel' );
if ( $selection.length ) {
text = $selection.html();
value = $selection.data( 'value' );
attr = $selection.data( 'attr' );
}
}
//ignore comma and make sure text that has been entered (protects against " ,". https://github.com/ExactTarget/fuelux/issues/593), unless allowEmptyPills is true.
if ( text.replace( /[ ]*\,[ ]*/, '' ).match( /\S/ ) || ( this.options.allowEmptyPills && text.length ) ) {
this._closeSuggestions();
this.$addItem.hide();
if ( attr ) {
this.addItems( {
text: text,
value: value,
attr: JSON.parse( attr )
}, true );
} else {
this.addItems( {
text: text,
value: value
}, true );
}
setTimeout( function() {
self.$addItem.show().val( '' ).attr( {
size: 10
} );
}, 0 );
}
e.preventDefault();
return true;
} else if ( e.keyCode === 8 || e.keyCode === 46 ) {
// backspace: 8
// delete: 46
if ( !text.length ) {
e.preventDefault();
if ( this.options.edit && this.currentEdit ) {
this.cancelEdit();
return true;
}
this._closeSuggestions();
$lastItem = this.$pillGroup.children( '.pill:last' );
if ( $lastItem.hasClass( 'pillbox-highlight' ) ) {
this._removeElement( this.getItemData( $lastItem, {
el: $lastItem
} ) );
} else {
$lastItem.addClass( 'pillbox-highlight' );
}
return true;
}
} else if ( text.length > 10 ) {
if ( this.$addItem.width() < ( this.$pillGroup.width() - 6 ) ) {
this.$addItem.attr( {
size: text.length + 3
} );
}
}
this.$pillGroup.find( '.pill' ).removeClass( 'pillbox-highlight' );
if ( this.options.onKeyDown ) {
if ( e.keyCode === 9 || e.keyCode === 38 || e.keyCode === 40 ) {
// tab: 9
// up arrow: 38
// down arrow: 40
if ( this._isSuggestionsOpen() ) {
this._keySuggestions( e );
}
return true;
}
//only allowing most recent event callback to register
this.callbackId = e.timeStamp;
this.options.onKeyDown( {
event: e,
value: text
}, function( data ) {
self._openSuggestions( e, data );
} );
}
},
openEdit: function( el ) {
var index = el.index() + 1;
var $addItemWrap = this.$addItemWrap.detach().hide();
this.$pillGroup.find( '.pill:nth-child(' + index + ')' ).before( $addItemWrap );
this.currentEdit = el.detach();
$addItemWrap.addClass( 'editing' );
this.$addItem.val( el.find( 'span:first' ).html() );
$addItemWrap.show();
this.$addItem.focus().select();
},
cancelEdit: function( e ) {
var $addItemWrap;
if ( !this.currentEdit ) {
return false;
}
this._closeSuggestions();
if ( e ) {
this.$addItemWrap.before( this.currentEdit );
}
this.currentEdit = false;
$addItemWrap = this.$addItemWrap.detach();
$addItemWrap.removeClass( 'editing' );
this.$addItem.val( '' );
this.$pillGroup.append( $addItemWrap );
},
//Must match syntax of placeItem so addItem callback is called when an item is edited
//expecting to receive an array back from the callback containing edited items
saveEdit: function() {
var item = arguments[ 0 ][ 0 ] ? arguments[ 0 ][ 0 ] : arguments[ 0 ];
this.currentEdit = $( item.el );
this.currentEdit.data( 'value', item.value );
this.currentEdit.find( 'span:first' ).html( item.text );
this.$addItemWrap.hide();
this.$addItemWrap.before( this.currentEdit );
this.currentEdit = false;
this.$addItem.val( '' );
this.$addItemWrap.removeClass( 'editing' );
this.$pillGroup.append( this.$addItemWrap.detach().show() );
this.$element.trigger( 'edited.fu.pillbox', {
value: item.value,
text: item.text
} );
},
removeBySelector: function() {
var selectors = [].slice.call( arguments ).slice( 0 );
var self = this;
$.each( selectors, function( i, sel ) {
self.$pillGroup.find( sel ).remove();
} );
this._removePillTrigger( {
method: 'removeBySelector',
removedSelectors: selectors
} );
},
removeByValue: function() {
var values = [].slice.call( arguments ).slice( 0 );
var self = this;
$.each( values, function( i, val ) {
self.$pillGroup.find( '> .pill[data-value="' + val + '"]' ).remove();
} );
this._removePillTrigger( {
method: 'removeByValue',
removedValues: values
} );
},
removeByText: function() {
var text = [].slice.call( arguments ).slice( 0 );
var self = this;
$.each( text, function( i, text ) {
self.$pillGroup.find( '> .pill:contains("' + text + '")' ).remove();
} );
this._removePillTrigger( {
method: 'removeByText',
removedText: text
} );
},
truncate: function( enable ) {
var self = this;
var available, full, i, pills, used;
this.$element.removeClass( 'truncate' );
this.$addItemWrap.removeClass( 'truncated' );
this.$pillGroup.find( '.pill' ).removeClass( 'truncated' );
if ( enable ) {
this.$element.addClass( 'truncate' );
available = this.$element.width();
full = false;
i = 0;
pills = this.$pillGroup.find( '.pill' ).length;
used = 0;
this.$pillGroup.find( '.pill' ).each( function() {
var pill = $( this );
if ( !full ) {
i++;
self.$moreCount.text( pills - i );
if ( ( used + pill.outerWidth( true ) + self.$addItemWrap.outerWidth( true ) ) <= available ) {
used += pill.outerWidth( true );
} else {
self.$moreCount.text( ( pills - i ) + 1 );
pill.addClass( 'truncated' );
full = true;
}
} else {
pill.addClass( 'truncated' );
}
} );
if ( i === pills ) {
this.$addItemWrap.addClass( 'truncated' );
}
}
},
inputFocus: function( e ) {
this.$element.find( '.pillbox-add-item' ).focus();
},
getItemData: function( el, data ) {
return $.extend( {
text: el.find( 'span:first' ).html()
}, el.data(), data );
},
_removeElement: function( data ) {
data.el.remove();
delete data.el;
this.$element.trigger( 'removed.fu.pillbox', data );
},
_removePillTrigger: function( removedBy ) {
this.$element.trigger( 'removed.fu.pillbox', removedBy );
},
_generateObject: function( data ) {
var obj = {};
$.each( data, function( index, value ) {
obj[ value ] = true;
} );
return obj;
},
_openSuggestions: function( e, data ) {
var markup = '';
var $suggestionList = $( '<ul>' );
if ( this.callbackId !== e.timeStamp ) {
return false;
}
if ( data.data && data.data.length ) {
$.each( data.data, function( index, value ) {
var val = value.value ? value.value : value.text;
// markup concatentation is 10x faster, but does not allow data store
var $suggestion = $( '<li data-value="' + val + '">' + value.text + '</li>' );
if ( value.attr ) {
$suggestion.data( 'attr', JSON.stringify( value.attr ) );
}
if ( value.data ) {
$suggestion.data( 'data', value.data );
}
$suggestionList.append( $suggestion );
} );
// suggestion dropdown
this.$suggest.html( '' ).append( $suggestionList.children() );
$( document.body ).trigger( 'suggested.fu.pillbox', this.$suggest );
}
},
_closeSuggestions: function() {
this.$suggest.html( '' ).parent().removeClass( 'open' );
},
_isSuggestionsOpen: function() {
return this.$suggest.parent().hasClass( 'open' );
},
_keySuggestions: function( e ) {
var $first = this.$suggest.find( 'li.pillbox-suggest-sel' );
var dir = e.keyCode === 38; // up arrow
var $next, val;
e.preventDefault();
if ( !$first.length ) {
$first = this.$suggest.find( 'li:first' );
$first.addClass( 'pillbox-suggest-sel' );
} else {
$next = dir ? $first.prev() : $first.next();
if ( !$next.length ) {
$next = dir ? this.$suggest.find( 'li:last' ) : this.$suggest.find( 'li:first' );
}
if ( $next ) {
$next.addClass( 'pillbox-suggest-sel' );
$first.removeClass( 'pillbox-suggest-sel' );
}
}
}
};
Pillbox.prototype.getValue = Pillbox.prototype.items;
// PILLBOX PLUGIN DEFINITION
$.fn.pillbox = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.pillbox' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.pillbox', ( data = new Pillbox( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.pillbox.defaults = {
onAdd: undefined,
onRemove: undefined,
onKeyDown: undefined,
edit: false,
readonly: -1, //can be true or false. -1 means it will check for data-readonly="readonly"
truncate: false,
acceptKeyCodes: [
13, //Enter
188 //Comma
],
allowEmptyPills: false
//example on remove
/*onRemove: function(data,callback){
console.log('onRemove');
callback(data);
}*/
//example on key down
/*onKeyDown: function(event, data, callback ){
callback({data:[
{text: Math.random(),value:'sdfsdfsdf'},
{text: Math.random(),value:'sdfsdfsdf'}
]});
}
*/
//example onAdd
/*onAdd: function( data, callback ){
console.log(data, callback);
callback(data);
}*/
};
$.fn.pillbox.Constructor = Pillbox;
$.fn.pillbox.noConflict = function() {
$.fn.pillbox = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.pillbox.data-api', '[data-initialize=pillbox]', function( e ) {
var $control = $( e.target ).closest( '.pillbox' );
if ( !$control.data( 'fu.pillbox' ) ) {
$control.pillbox( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=pillbox]' ).each( function() {
var $this = $( this );
if ( $this.data( 'fu.pillbox' ) ) return;
$this.pillbox( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Repeater
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.repeater;
// REPEATER CONSTRUCTOR AND PROTOTYPE
var Repeater = function( element, options ) {
var self = this;
var $btn, currentView;
this.$element = $( element );
this.$canvas = this.$element.find( '.repeater-canvas' );
this.$count = this.$element.find( '.repeater-count' );
this.$end = this.$element.find( '.repeater-end' );
this.$filters = this.$element.find( '.repeater-filters' );
this.$loader = this.$element.find( '.repeater-loader' );
this.$pageSize = this.$element.find( '.repeater-itemization .selectlist' );
this.$nextBtn = this.$element.find( '.repeater-next' );
this.$pages = this.$element.find( '.repeater-pages' );
this.$prevBtn = this.$element.find( '.repeater-prev' );
this.$primaryPaging = this.$element.find( '.repeater-primaryPaging' );
this.$search = this.$element.find( '.repeater-search' ).find( '.search' );
this.$secondaryPaging = this.$element.find( '.repeater-secondaryPaging' );
this.$start = this.$element.find( '.repeater-start' );
this.$viewport = this.$element.find( '.repeater-viewport' );
this.$views = this.$element.find( '.repeater-views' );
this.currentPage = 0;
this.currentView = null;
this.isDisabled = false;
this.infiniteScrollingCallback = function() {};
this.infiniteScrollingCont = null;
this.infiniteScrollingEnabled = false;
this.infiniteScrollingEnd = null;
this.infiniteScrollingOptions = {};
this.lastPageInput = 0;
this.options = $.extend( {}, $.fn.repeater.defaults, options );
this.pageIncrement = 0; // store direction navigated
this.resizeTimeout = {};
this.stamp = new Date().getTime() + ( Math.floor( Math.random() * 100 ) + 1 );
this.storedDataSourceOpts = null;
this.syncingViewButtonState = false;
this.viewOptions = {};
this.viewType = null;
this.$filters.selectlist();
this.$pageSize.selectlist();
this.$primaryPaging.find( '.combobox' ).combobox();
this.$search.search( {
searchOnKeyPress: this.options.searchOnKeyPress
} );
this.$filters.on( 'changed.fu.selectlist', function( e, value ) {
self.$element.trigger( 'filtered.fu.repeater', value );
self.render( {
clearInfinite: true,
pageIncrement: null
} );
} );
this.$nextBtn.on( 'click.fu.repeater', $.proxy( this.next, this ) );
this.$pageSize.on( 'changed.fu.selectlist', function( e, value ) {
self.$element.trigger( 'pageSizeChanged.fu.repeater', value );
self.render( {
pageIncrement: null
} );
} );
this.$prevBtn.on( 'click.fu.repeater', $.proxy( this.previous, this ) );
this.$primaryPaging.find( '.combobox' ).on( 'changed.fu.combobox', function( evt, data ) {
self.$element.trigger( 'pageChanged.fu.repeater', [ data.text, data ] );
self.pageInputChange( data.text );
} );
this.$search.on( 'searched.fu.search cleared.fu.search', function( e, value ) {
self.$element.trigger( 'searchChanged.fu.repeater', value );
self.render( {
clearInfinite: true,
pageIncrement: null
} );
} );
this.$secondaryPaging.on( 'blur.fu.repeater', function( e ) {
self.pageInputChange( self.$secondaryPaging.val() );
} );
this.$secondaryPaging.on( 'keyup', function( e ) {
if ( e.keyCode === 13 ) {
self.pageInputChange( self.$secondaryPaging.val() );
}
} );
this.$views.find( 'input' ).on( 'change.fu.repeater', $.proxy( this.viewChanged, this ) );
// ID needed since event is bound to instance
$( window ).on( 'resize.fu.repeater.' + this.stamp, function( event ) {
clearTimeout( self.resizeTimeout );
self.resizeTimeout = setTimeout( function() {
self.resize();
self.$element.trigger( 'resized.fu.repeater' );
}, 75 );
} );
this.$loader.loader();
this.$loader.loader( 'pause' );
if ( this.options.defaultView !== -1 ) {
currentView = this.options.defaultView;
} else {
$btn = this.$views.find( 'label.active input' );
currentView = ( $btn.length > 0 ) ? $btn.val() : 'list';
}
this.setViewOptions( currentView );
this.initViewTypes( function() {
self.resize();
self.$element.trigger( 'resized.fu.repeater' );
self.render( {
changeView: currentView
} );
} );
};
Repeater.prototype = {
constructor: Repeater,
clear: function( options ) {
var viewChanged, viewTypeObj;
function scan( cont ) {
var keep = [];
cont.children().each( function() {
var item = $( this );
var pres = item.attr( 'data-preserve' );
if ( pres === 'deep' ) {
item.detach();
keep.push( item );
} else if ( pres === 'shallow' ) {
scan( item );
item.detach();
keep.push( item );
}
} );
cont.empty();
cont.append( keep );
}
options = options || {};
if ( !options.preserve ) {
//Just trash everything because preserve is false
this.$canvas.empty();
} else if ( !this.infiniteScrollingEnabled || options.clearInfinite ) {
//Preserve clear only if infiniteScrolling is disabled or if specifically told to do so
scan( this.$canvas );
} //Otherwise don't clear because infiniteScrolling is enabled
//If viewChanged and current viewTypeObj has a cleared function, call it
viewChanged = ( options.viewChanged !== undefined ) ? options.viewChanged : false;
viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
if ( !viewChanged && viewTypeObj.cleared ) {
viewTypeObj.cleared.call( this, {
options: options
} );
}
},
clearPreservedDataSourceOptions: function() {
this.storedDataSourceOpts = null;
},
destroy: function() {
var markup;
// set input value attrbute in markup
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup
this.$canvas.empty();
markup = this.$element[ 0 ].outerHTML;
// destroy components and remove leftover
this.$element.find( '.combobox' ).combobox( 'destroy' );
this.$element.find( '.selectlist' ).selectlist( 'destroy' );
this.$element.find( '.search' ).search( 'destroy' );
if ( this.infiniteScrollingEnabled ) {
$( this.infiniteScrollingCont ).infinitescroll( 'destroy' );
}
this.$element.remove();
// any external events
$( window ).off( 'resize.fu.repeater.' + this.stamp );
return markup;
},
disable: function() {
var disable = 'disable';
var disabled = 'disabled';
var viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
this.$search.search( disable );
this.$filters.selectlist( disable );
this.$views.find( 'label, input' ).addClass( disabled ).attr( disabled, disabled );
this.$pageSize.selectlist( disable );
this.$primaryPaging.find( '.combobox' ).combobox( disable );
this.$secondaryPaging.attr( disabled, disabled );
this.$prevBtn.attr( disabled, disabled );
this.$nextBtn.attr( disabled, disabled );
if ( viewTypeObj.enabled ) {
viewTypeObj.enabled.call( this, {
status: false
} );
}
this.isDisabled = true;
this.$element.addClass( 'disabled' );
this.$element.trigger( 'disabled.fu.repeater' );
},
enable: function() {
var disabled = 'disabled';
var enable = 'enable';
var pageEnd = 'page-end';
var viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
this.$search.search( enable );
this.$filters.selectlist( enable );
this.$views.find( 'label, input' ).removeClass( disabled ).removeAttr( disabled );
this.$pageSize.selectlist( 'enable' );
this.$primaryPaging.find( '.combobox' ).combobox( enable );
this.$secondaryPaging.removeAttr( disabled );
if ( !this.$prevBtn.hasClass( pageEnd ) ) {
this.$prevBtn.removeAttr( disabled );
}
if ( !this.$nextBtn.hasClass( pageEnd ) ) {
this.$nextBtn.removeAttr( disabled );
}
// is 0 or 1 pages, if using $primaryPaging (combobox)
// if using selectlist allow user to use selectlist to select 0 or 1
if ( this.$prevBtn.hasClass( pageEnd ) && this.$nextBtn.hasClass( pageEnd ) ) {
this.$primaryPaging.combobox( 'disable' );
}
//if there are no items
if ( parseInt( this.$count.html() ) !== 0 ) {
this.$pageSize.selectlist( 'enable' );
} else {
this.$pageSize.selectlist( 'disable' );
}
if ( viewTypeObj.enabled ) {
viewTypeObj.enabled.call( this, {
status: true
} );
}
this.isDisabled = false;
this.$element.removeClass( 'disabled' );
this.$element.trigger( 'enabled.fu.repeater' );
},
getDataOptions: function( options ) {
var dataSourceOptions = {};
var opts = {};
var val, viewDataOpts;
options = options || {};
opts.filter = ( this.$filters.length > 0 ) ? this.$filters.selectlist( 'selectedItem' ) : {
text: 'All',
value: 'all'
};
opts.view = this.currentView;
if ( !this.infiniteScrollingEnabled ) {
opts.pageSize = ( this.$pageSize.length > 0 ) ? parseInt( this.$pageSize.selectlist( 'selectedItem' ).value, 10 ) : 25;
}
if ( options.pageIncrement !== undefined ) {
if ( options.pageIncrement === null ) {
this.currentPage = 0;
} else {
this.currentPage += options.pageIncrement;
}
}
opts.pageIndex = this.currentPage;
val = ( this.$search.length > 0 ) ? this.$search.find( 'input' ).val() : '';
if ( val !== '' ) {
opts.search = val;
}
if ( options.dataSourceOptions ) {
dataSourceOptions = options.dataSourceOptions;
if ( options.preserveDataSourceOptions ) {
this.storedDataSourceOpts = ( this.storedDataSourceOpts ) ? $.extend( this.storedDataSourceOpts, dataSourceOptions ) : dataSourceOptions;
}
}
if ( this.storedDataSourceOpts ) {
dataSourceOptions = $.extend( this.storedDataSourceOpts, dataSourceOptions );
}
viewDataOpts = $.fn.repeater.viewTypes[ this.viewType ] || {};
viewDataOpts = viewDataOpts.dataOptions;
if ( viewDataOpts ) {
viewDataOpts = viewDataOpts.call( this, opts );
opts = $.extend( viewDataOpts, dataSourceOptions );
} else {
opts = $.extend( opts, dataSourceOptions );
}
return opts;
},
infiniteScrolling: function( enable, options ) {
var footer = this.$element.find( '.repeater-footer' );
var viewport = this.$element.find( '.repeater-viewport' );
var cont, data;
options = options || {};
if ( enable ) {
this.infiniteScrollingEnabled = true;
this.infiniteScrollingEnd = options.end;
delete options.dataSource;
delete options.end;
this.infiniteScrollingOptions = options;
viewport.css( {
height: viewport.height() + footer.outerHeight()
} );
footer.hide();
} else {
cont = this.infiniteScrollingCont;
data = cont.data();
delete data.infinitescroll;
cont.off( 'scroll' );
cont.removeClass( 'infinitescroll' );
this.infiniteScrollingCont = null;
this.infiniteScrollingEnabled = false;
this.infiniteScrollingEnd = null;
this.infiniteScrollingOptions = {};
viewport.css( {
height: viewport.height() - footer.outerHeight()
} );
footer.show();
}
},
infiniteScrollPaging: function( data, options ) {
var end = ( this.infiniteScrollingEnd !== true ) ? this.infiniteScrollingEnd : undefined;
var page = data.page;
var pages = data.pages;
this.currentPage = ( page !== undefined ) ? page : NaN;
if ( data.end === true || ( this.currentPage + 1 ) >= pages ) {
this.infiniteScrollingCont.infinitescroll( 'end', end );
}
},
initInfiniteScrolling: function() {
var cont = this.$canvas.find( '[data-infinite="true"]:first' );
var opts, self;
cont = ( cont.length < 1 ) ? this.$canvas : cont;
if ( cont.data( 'fu.infinitescroll' ) ) {
cont.infinitescroll( 'enable' );
} else {
self = this;
opts = $.extend( {}, this.infiniteScrollingOptions );
opts.dataSource = function( helpers, callback ) {
self.infiniteScrollingCallback = callback;
self.render( {
pageIncrement: 1
} );
};
cont.infinitescroll( opts );
this.infiniteScrollingCont = cont;
}
},
initViewTypes: function( callback ) {
var self = this;
var viewTypes = [];
var i, viewTypesLength;
function init( index ) {
function next() {
index++;
if ( index < viewTypesLength ) {
init( index );
} else {
callback();
}
}
if ( viewTypes[ index ].initialize ) {
viewTypes[ index ].initialize.call( self, {}, function() {
next();
} );
} else {
next();
}
}
for ( i in $.fn.repeater.viewTypes ) {
viewTypes.push( $.fn.repeater.viewTypes[ i ] );
}
viewTypesLength = viewTypes.length;
if ( viewTypesLength > 0 ) {
init( 0 );
} else {
callback();
}
},
itemization: function( data ) {
this.$count.html( ( data.count !== undefined ) ? data.count : '?' );
this.$end.html( ( data.end !== undefined ) ? data.end : '?' );
this.$start.html( ( data.start !== undefined ) ? data.start : '?' );
},
next: function( e ) {
var d = 'disabled';
this.$nextBtn.attr( d, d );
this.$prevBtn.attr( d, d );
this.pageIncrement = 1;
this.$element.trigger( 'nextClicked.fu.repeater' );
this.render( {
pageIncrement: this.pageIncrement
} );
},
pageInputChange: function( val ) {
var pageInc;
if ( val !== this.lastPageInput ) {
this.lastPageInput = val;
val = parseInt( val, 10 ) - 1;
pageInc = val - this.currentPage;
this.$element.trigger( 'pageChanged.fu.repeater', val );
this.render( {
pageIncrement: pageInc
} );
}
},
pagination: function( data ) {
var act = 'active';
var dsbl = 'disabled';
var page = data.page;
var pageEnd = 'page-end';
var pages = data.pages;
var dropMenu, i, l;
var currenPageOutput;
this.currentPage = ( page !== undefined ) ? page : NaN;
this.$primaryPaging.removeClass( act );
this.$secondaryPaging.removeClass( act );
// set paging to 0 if total pages is 0, otherwise use one-based index
currenPageOutput = pages === 0 ? 0 : this.currentPage + 1;
if ( pages <= this.viewOptions.dropPagingCap ) {
this.$primaryPaging.addClass( act );
dropMenu = this.$primaryPaging.find( '.dropdown-menu' );
dropMenu.empty();
for ( i = 0; i < pages; i++ ) {
l = i + 1;
dropMenu.append( '<li data-value="' + l + '"><a href="#">' + l + '</a></li>' );
}
this.$primaryPaging.find( 'input.form-control' ).val( currenPageOutput );
} else {
this.$secondaryPaging.addClass( act );
this.$secondaryPaging.val( currenPageOutput );
}
this.lastPageInput = this.currentPage + 1 + '';
this.$pages.html( '' + pages );
// this is not the last page
if ( ( this.currentPage + 1 ) < pages ) {
this.$nextBtn.removeAttr( dsbl );
this.$nextBtn.removeClass( pageEnd );
} else {
this.$nextBtn.attr( dsbl, dsbl );
this.$nextBtn.addClass( pageEnd );
}
// this is not the first page
if ( ( this.currentPage - 1 ) >= 0 ) {
this.$prevBtn.removeAttr( dsbl );
this.$prevBtn.removeClass( pageEnd );
} else {
this.$prevBtn.attr( dsbl, dsbl );
this.$prevBtn.addClass( pageEnd );
}
// return focus to next/previous buttons after navigating
if ( this.pageIncrement !== 0 ) {
if ( this.pageIncrement > 0 ) {
if ( this.$nextBtn.is( ':disabled' ) ) {
// if you can't focus, go the other way
this.$prevBtn.focus();
} else {
this.$nextBtn.focus();
}
} else {
if ( this.$prevBtn.is( ':disabled' ) ) {
// if you can't focus, go the other way
this.$nextBtn.focus();
} else {
this.$prevBtn.focus();
}
}
}
},
previous: function() {
var d = 'disabled';
this.$nextBtn.attr( d, d );
this.$prevBtn.attr( d, d );
this.pageIncrement = -1;
this.$element.trigger( 'previousClicked.fu.repeater' );
this.render( {
pageIncrement: this.pageIncrement
} );
},
render: function( options ) {
var self = this;
var viewChanged = false;
var viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
var dataOptions, prevView;
options = options || {};
this.disable();
if ( options.changeView && ( this.currentView !== options.changeView ) ) {
prevView = this.currentView;
this.currentView = options.changeView;
this.viewType = this.currentView.split( '.' )[ 0 ];
this.setViewOptions( this.currentView );
this.$element.attr( 'data-currentview', this.currentView );
this.$element.attr( 'data-viewtype', this.viewType );
viewChanged = true;
options.viewChanged = viewChanged;
this.$element.trigger( 'viewChanged.fu.repeater', this.currentView );
if ( this.infiniteScrollingEnabled ) {
self.infiniteScrolling( false );
}
viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
if ( viewTypeObj.selected ) {
viewTypeObj.selected.call( this, {
prevView: prevView
} );
}
}
this.syncViewButtonState();
options.preserve = ( options.preserve !== undefined ) ? options.preserve : !viewChanged;
this.clear( options );
if ( !this.infiniteScrollingEnabled || ( this.infiniteScrollingEnabled && viewChanged ) ) {
this.$loader.show().loader( 'play' );
}
dataOptions = this.getDataOptions( options );
this.viewOptions.dataSource( dataOptions, function( data ) {
data = data || {};
if ( self.infiniteScrollingEnabled ) {
// pass empty object because data handled in infiniteScrollPaging method
self.infiniteScrollingCallback( {} );
} else {
self.itemization( data );
self.pagination( data );
}
self.runRenderer( viewTypeObj, data, function() {
if ( self.infiniteScrollingEnabled ) {
if ( viewChanged || options.clearInfinite ) {
self.initInfiniteScrolling();
}
self.infiniteScrollPaging( data, options );
}
self.$loader.hide().loader( 'pause' );
self.enable();
self.$element.trigger( 'rendered.fu.repeater', {
data: data,
options: dataOptions,
renderOptions: options
} );
//for maintaining support of 'loaded' event
self.$element.trigger( 'loaded.fu.repeater', dataOptions );
} );
} );
},
resize: function() {
var staticHeight = ( this.viewOptions.staticHeight === -1 ) ? this.$element.attr( 'data-staticheight' ) : this.viewOptions.staticHeight;
var viewTypeObj = {};
var height, viewportMargins;
if ( this.viewType ) {
viewTypeObj = $.fn.repeater.viewTypes[ this.viewType ] || {};
}
if ( staticHeight !== undefined && staticHeight !== false && staticHeight !== 'false' ) {
this.$canvas.addClass( 'scrolling' );
viewportMargins = {
bottom: this.$viewport.css( 'margin-bottom' ),
top: this.$viewport.css( 'margin-top' )
};
var staticHeightValue = ( staticHeight === 'true' || staticHeight === true ) ? this.$element.height() : parseInt( staticHeight, 10 );
var headerHeight = this.$element.find( '.repeater-header' ).outerHeight();
var footerHeight = this.$element.find( '.repeater-footer' ).outerHeight();
var bottomMargin = ( viewportMargins.bottom === 'auto' ) ? 0 : parseInt( viewportMargins.bottom, 10 );
var topMargin = ( viewportMargins.top === 'auto' ) ? 0 : parseInt( viewportMargins.top, 10 );
height = staticHeightValue - headerHeight - footerHeight - bottomMargin - topMargin;
this.$viewport.outerHeight( height );
} else {
this.$canvas.removeClass( 'scrolling' );
}
if ( viewTypeObj.resize ) {
viewTypeObj.resize.call( this, {
height: this.$element.outerHeight(),
width: this.$element.outerWidth()
} );
}
},
runRenderer: function( viewTypeObj, data, callback ) {
var $container, i, l, response, repeat, subset;
function addItem( $parent, resp ) {
var action;
if ( resp ) {
action = ( resp.action ) ? resp.action : 'append';
if ( action !== 'none' && resp.item !== undefined ) {
$parent = ( resp.container !== undefined ) ? $( resp.container ) : $parent;
$parent[ action ]( resp.item );
}
}
}
if ( !viewTypeObj.render ) {
if ( viewTypeObj.before ) {
response = viewTypeObj.before.call( this, {
container: this.$canvas,
data: data
} );
addItem( this.$canvas, response );
}
$container = this.$canvas.find( '[data-container="true"]:last' );
$container = ( $container.length > 0 ) ? $container : this.$canvas;
if ( viewTypeObj.renderItem ) {
repeat = viewTypeObj.repeat || 'data.items';
repeat = repeat.split( '.' );
if ( repeat[ 0 ] === 'data' || repeat[ 0 ] === 'this' ) {
subset = ( repeat[ 0 ] === 'this' ) ? this : data;
repeat.shift();
} else {
repeat = [];
subset = [];
if ( window.console && window.console.warn ) {
window.console.warn( 'WARNING: Repeater plugin "repeat" value must start with either "data" or "this"' );
}
}
for ( i = 0, l = repeat.length; i < l; i++ ) {
if ( subset[ repeat[ i ] ] !== undefined ) {
subset = subset[ repeat[ i ] ];
} else {
subset = [];
if ( window.console && window.console.warn ) {
window.console.warn( 'WARNING: Repeater unable to find property to iterate renderItem on.' );
}
break;
}
}
for ( i = 0, l = subset.length; i < l; i++ ) {
response = viewTypeObj.renderItem.call( this, {
container: $container,
data: data,
index: i,
subset: subset
} );
addItem( $container, response );
}
}
if ( viewTypeObj.after ) {
response = viewTypeObj.after.call( this, {
container: this.$canvas,
data: data
} );
addItem( this.$canvas, response );
}
callback();
} else {
viewTypeObj.render.call( this, {
container: this.$canvas,
data: data
}, function() {
callback();
} );
}
},
setViewOptions: function( curView ) {
var opts = {};
var viewName = curView.split( '.' )[ 1 ];
if ( this.options.views ) {
opts = this.options.views[ viewName ] || this.options.views[ curView ] || {};
} else {
opts = {};
}
this.viewOptions = $.extend( {}, this.options, opts );
},
viewChanged: function( e ) {
var $selected = $( e.target );
var val = $selected.val();
if ( !this.syncingViewButtonState ) {
if ( this.isDisabled || $selected.parents( 'label:first' ).hasClass( 'disabled' ) ) {
this.syncViewButtonState();
} else {
this.render( {
changeView: val,
pageIncrement: null
} );
}
}
},
syncViewButtonState: function() {
var $itemToCheck = this.$views.find( 'input[value="' + this.currentView + '"]' );
this.syncingViewButtonState = true;
this.$views.find( 'input' ).prop( 'checked', false );
this.$views.find( 'label.active' ).removeClass( 'active' );
if ( $itemToCheck.length > 0 ) {
$itemToCheck.prop( 'checked', true );
$itemToCheck.parents( 'label:first' ).addClass( 'active' );
}
this.syncingViewButtonState = false;
}
};
// REPEATER PLUGIN DEFINITION
$.fn.repeater = function( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.repeater' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.repeater', ( data = new Repeater( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.repeater.defaults = {
dataSource: function( options, callback ) {
callback( {
count: 0,
end: 0,
items: [],
page: 0,
pages: 1,
start: 0
} );
},
defaultView: -1, //should be a string value. -1 means it will grab the active view from the view controls
dropPagingCap: 10,
staticHeight: -1, //normally true or false. -1 means it will look for data-staticheight on the element
views: null, //can be set to an object to configure multiple views of the same type,
searchOnKeyPress: false
};
$.fn.repeater.viewTypes = {};
$.fn.repeater.Constructor = Repeater;
$.fn.repeater.noConflict = function() {
$.fn.repeater = old;
return this;
};
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Repeater - List View Plugin
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
if ( $.fn.repeater ) {
//ADDITIONAL METHODS
$.fn.repeater.Constructor.prototype.list_clearSelectedItems = function() {
this.$canvas.find( '.repeater-list-check' ).remove();
this.$canvas.find( '.repeater-list table tbody tr.selected' ).removeClass( 'selected' );
};
$.fn.repeater.Constructor.prototype.list_highlightColumn = function( index, force ) {
var tbody = this.$canvas.find( '.repeater-list-wrapper > table tbody' );
if ( this.viewOptions.list_highlightSortedColumn || force ) {
tbody.find( 'td.sorted' ).removeClass( 'sorted' );
tbody.find( 'tr' ).each( function() {
var col = $( this ).find( 'td:nth-child(' + ( index + 1 ) + ')' ).filter( function() {
return !$( this ).parent().hasClass( 'empty' );
} );
col.addClass( 'sorted' );
} );
}
};
$.fn.repeater.Constructor.prototype.list_getSelectedItems = function() {
var selected = [];
this.$canvas.find( '.repeater-list .repeater-list-wrapper > table tbody tr.selected' ).each( function() {
var $item = $( this );
selected.push( {
data: $item.data( 'item_data' ),
element: $item
} );
} );
return selected;
};
$.fn.repeater.Constructor.prototype.getValue = $.fn.repeater.Constructor.prototype.list_getSelectedItems;
$.fn.repeater.Constructor.prototype.list_positionHeadings = function() {
var $wrapper = this.$element.find( '.repeater-list-wrapper' );
var offsetLeft = $wrapper.offset().left;
var scrollLeft = $wrapper.scrollLeft();
if ( scrollLeft > 0 ) {
$wrapper.find( '.repeater-list-heading' ).each( function() {
var $heading = $( this );
var left = ( $heading.parents( 'th:first' ).offset().left - offsetLeft ) + 'px';
$heading.addClass( 'shifted' ).css( 'left', left );
} );
} else {
$wrapper.find( '.repeater-list-heading' ).each( function() {
$( this ).removeClass( 'shifted' ).css( 'left', '' );
} );
}
};
$.fn.repeater.Constructor.prototype.list_setSelectedItems = function( items, force ) {
var selectable = this.viewOptions.list_selectable;
var self = this;
var data, i, $item, length;
//this function is necessary because lint yells when a function is in a loop
function checkIfItemMatchesValue( rowIndex ) {
$item = $( this );
data = $item.data( 'item_data' ) || {};
if ( data[ items[ i ].property ] === items[ i ].value ) {
selectItem( $item, items[ i ].selected, rowIndex );
}
}
function selectItem( $itm, select, index ) {
var $frozenCols;
select = ( select !== undefined ) ? select : true;
if ( select ) {
if ( !force && selectable !== 'multi' ) {
self.list_clearSelectedItems();
}
if ( !$itm.hasClass( 'selected' ) ) {
$itm.addClass( 'selected' );
if ( self.viewOptions.list_frozenColumns || self.viewOptions.list_selectable === 'multi' ) {
$frozenCols = self.$element.find( '.frozen-column-wrapper tr:nth-child(' + ( index + 1 ) + ')' );
$frozenCols.addClass( 'selected' );
$frozenCols.find( '.repeater-select-checkbox' ).addClass( 'checked' );
}
if ( self.viewOptions.list_actions ) {
self.$element.find( '.actions-column-wrapper tr:nth-child(' + ( index + 1 ) + ')' ).addClass( 'selected' );
}
$itm.find( 'td:first' ).prepend( '<div class="repeater-list-check"><span class="glyphicon glyphicon-ok"></span></div>' );
}
} else {
if ( self.viewOptions.list_frozenColumns ) {
$frozenCols = self.$element.find( '.frozen-column-wrapper tr:nth-child(' + ( index + 1 ) + ')' );
$frozenCols.addClass( 'selected' );
$frozenCols.find( '.repeater-select-checkbox' ).removeClass( 'checked' );
}
if ( self.viewOptions.list_actions ) {
self.$element.find( '.actions-column-wrapper tr:nth-child(' + ( index + 1 ) + ')' ).removeClass( 'selected' );
}
$itm.find( '.repeater-list-check' ).remove();
$itm.removeClass( 'selected' );
}
}
if ( !$.isArray( items ) ) {
items = [ items ];
}
if ( force === true || selectable === 'multi' ) {
length = items.length;
} else if ( selectable ) {
length = ( items.length > 0 ) ? 1 : 0;
} else {
length = 0;
}
for ( i = 0; i < length; i++ ) {
if ( items[ i ].index !== undefined ) {
$item = this.$canvas.find( '.repeater-list .repeater-list-wrapper > table tbody tr:nth-child(' + ( items[ i ].index + 1 ) + ')' );
if ( $item.length > 0 ) {
selectItem( $item, items[ i ].selected, items[ i ].index );
}
} else if ( items[ i ].property !== undefined && items[ i ].value !== undefined ) {
this.$canvas.find( '.repeater-list .repeater-list-wrapper > table tbody tr' ).each( checkIfItemMatchesValue );
}
}
};
$.fn.repeater.Constructor.prototype.list_sizeHeadings = function() {
var $table = this.$element.find( '.repeater-list table' );
$table.find( 'thead th' ).each( function() {
var $th = $( this );
var $heading = $th.find( '.repeater-list-heading' );
$heading.css( {
height: $th.outerHeight()
} );
$heading.outerWidth( $heading.data( 'forced-width' ) || $th.outerWidth() );
} );
};
$.fn.repeater.Constructor.prototype.list_setFrozenColumns = function() {
var frozenTable = this.$canvas.find( '.table-frozen' );
var $wrapper = this.$element.find( '.repeater-canvas' );
var $table = this.$element.find( '.repeater-list .repeater-list-wrapper > table' );
var repeaterWrapper = this.$element.find( '.repeater-list' );
var numFrozenColumns = this.viewOptions.list_frozenColumns;
var self = this;
if ( this.viewOptions.list_selectable === 'multi' ) {
numFrozenColumns = numFrozenColumns + 1;
$wrapper.addClass( 'multi-select-enabled' );
}
if ( frozenTable.length < 1 ) {
//setup frozen column markup
//main wrapper and remove unneeded columns
var $frozenColumnWrapper = $( '<div class="frozen-column-wrapper"></div>' ).insertBefore( $table );
var $frozenColumn = $table.clone().addClass( 'table-frozen' );
$frozenColumn.find( 'th:not(:lt(' + numFrozenColumns + '))' ).remove();
$frozenColumn.find( 'td:not(:nth-child(n+0):nth-child(-n+' + numFrozenColumns + '))' ).remove();
//need to set absolute heading for vertical scrolling
var $frozenThead = $frozenColumn.clone().removeClass( 'table-frozen' );
$frozenThead.find( 'tbody' ).remove();
var $frozenTheadWrapper = $( '<div class="frozen-thead-wrapper"></div>' ).append( $frozenThead );
$frozenColumnWrapper.append( $frozenColumn );
repeaterWrapper.append( $frozenTheadWrapper );
this.$canvas.addClass( 'frozen-enabled' );
}
this.list_sizeFrozenColumns();
$( '.frozen-thead-wrapper .repeater-list-heading' ).on( 'click', function() {
var index = $( this ).parent( 'th' ).index();
index = index + 1;
self.$element.find( '.repeater-list-wrapper > table thead th:nth-child(' + index + ') .repeater-list-heading' )[ 0 ].click();
} );
};
$.fn.repeater.Constructor.prototype.list_positionColumns = function() {
var $wrapper = this.$element.find( '.repeater-canvas' );
var scrollTop = $wrapper.scrollTop();
var scrollLeft = $wrapper.scrollLeft();
var frozenEnabled = this.viewOptions.list_frozenColumns || this.viewOptions.list_selectable === 'multi';
var actionsEnabled = this.viewOptions.list_actions;
var canvasWidth = this.$element.find( '.repeater-canvas' ).outerWidth();
var tableWidth = this.$element.find( '.repeater-list .repeater-list-wrapper > table' ).outerWidth();
var actionsWidth = this.$element.find( '.table-actions' ) ? this.$element.find( '.table-actions' ).outerWidth() : 0;
var shouldScroll = ( tableWidth - ( canvasWidth - actionsWidth ) ) >= scrollLeft;
if ( scrollTop > 0 ) {
$wrapper.find( '.repeater-list-heading' ).css( 'top', scrollTop );
} else {
$wrapper.find( '.repeater-list-heading' ).css( 'top', '0' );
}
if ( scrollLeft > 0 ) {
if ( frozenEnabled ) {
$wrapper.find( '.frozen-thead-wrapper' ).css( 'left', scrollLeft );
$wrapper.find( '.frozen-column-wrapper' ).css( 'left', scrollLeft );
}
if ( actionsEnabled && shouldScroll ) {
$wrapper.find( '.actions-thead-wrapper' ).css( 'right', -scrollLeft );
$wrapper.find( '.actions-column-wrapper' ).css( 'right', -scrollLeft );
}
} else {
if ( frozenEnabled ) {
$wrapper.find( '.frozen-thead-wrapper' ).css( 'left', '0' );
$wrapper.find( '.frozen-column-wrapper' ).css( 'left', '0' );
}
if ( actionsEnabled ) {
$wrapper.find( '.actions-thead-wrapper' ).css( 'right', '0' );
$wrapper.find( '.actions-column-wrapper' ).css( 'right', '0' );
}
}
};
$.fn.repeater.Constructor.prototype.list_createItemActions = function() {
var actionsHtml = '';
var self = this;
var i, length;
var $table = this.$element.find( '.repeater-list .repeater-list-wrapper > table' );
var $actionsTable = this.$canvas.find( '.table-actions' );
for ( i = 0, length = this.viewOptions.list_actions.items.length; i < length; i++ ) {
var action = this.viewOptions.list_actions.items[ i ];
var html = action.html;
actionsHtml += '<li><a href="#" data-action="' + action.name + '" class="action-item"> ' + html + '</a></li>';
}
var selectlist = '<div class="btn-group">' +
'<button type="button" class="btn btn-xs btn-default dropdown-toggle repeater-actions-button" data-toggle="dropdown" data-flip="auto" aria-expanded="false">' +
'<span class="caret"></span>' +
'</button>' +
'<ul class="dropdown-menu dropdown-menu-right" role="menu">' +
actionsHtml +
'</ul></div>';
if ( $actionsTable.length < 1 ) {
var $actionsColumnWrapper = $( '<div class="actions-column-wrapper" style="width: ' + this.list_actions_width + 'px"></div>' ).insertBefore( $table );
var $actionsColumn = $table.clone().addClass( 'table-actions' );
$actionsColumn.find( 'th:not(:last-child)' ).remove();
$actionsColumn.find( 'tr td:not(:last-child)' ).remove();
// Dont show actions dropdown in header if not multi select
if ( this.viewOptions.list_selectable === 'multi' || this.viewOptions.list_selectable === 'action' ) {
$actionsColumn.find( 'thead tr' ).html( '<th><div class="repeater-list-heading">' + selectlist + '</div></th>' );
if ( this.viewOptions.list_selectable !== 'action' ) {
//disable the header dropdown until an item is selected
$actionsColumn.find( 'thead .btn' ).attr( 'disabled', 'disabled' );
}
} else {
var label = this.viewOptions.list_actions.label || '<span class="actions-hidden">a</span>';
$actionsColumn.find( 'thead tr' ).addClass( 'empty-heading' ).html( '<th>' + label + '<div class="repeater-list-heading">' + label + '</div></th>' );
}
// Create Actions dropdown for each cell in actions table
var $actionsCells = $actionsColumn.find( 'td' );
$actionsCells.each( function( i ) {
$( this ).html( selectlist );
$( this ).find( 'a' ).attr( 'data-row', parseInt( [ i ] ) + 1 );
} );
$actionsColumnWrapper.append( $actionsColumn );
this.$canvas.addClass( 'actions-enabled' );
}
this.list_sizeActionsTable();
//row level actions click
this.$element.find( '.table-actions tbody .action-item' ).on( 'click', function( e ) {
if ( !self.isDisabled ) {
var actionName = $( this ).data( 'action' );
var row = $( this ).data( 'row' );
var selected = {
actionName: actionName,
rows: [ row ]
};
self.list_getActionItems( selected, e );
}
} );
// bulk actions click
this.$element.find( '.table-actions thead .action-item' ).on( 'click', function( e ) {
if ( !self.isDisabled ) {
var actionName = $( this ).data( 'action' );
var selected = {
actionName: actionName,
rows: []
};
var selector = '.repeater-list-wrapper > table .selected';
if ( self.viewOptions.list_selectable === 'action' ) {
selector = '.repeater-list-wrapper > table tr';
}
self.$element.find( selector ).each( function() {
var index = $( this ).index();
index = index + 1;
selected.rows.push( index );
} );
self.list_getActionItems( selected, e );
}
} );
};
$.fn.repeater.Constructor.prototype.list_getActionItems = function( selected, e ) {
var i;
var selectedObj = [];
var actionObj = $.grep( this.viewOptions.list_actions.items, function( actions ) {
return actions.name === selected.actionName;
} )[ 0 ];
for ( i = 0; i < selected.rows.length; i++ ) {
var clickedRow = this.$canvas.find( '.repeater-list-wrapper > table tbody tr:nth-child(' + selected.rows[ i ] + ')' );
selectedObj.push( {
item: clickedRow,
rowData: clickedRow.data( 'item_data' )
} );
}
if ( selectedObj.length === 1 ) {
selectedObj = selectedObj[ 0 ];
}
if ( actionObj.clickAction ) {
var callback = function callback() {}; // for backwards compatibility. No idea why this was originally here...
actionObj.clickAction( selectedObj, callback, e );
}
};
$.fn.repeater.Constructor.prototype.list_sizeActionsTable = function() {
var $actionsTable = this.$element.find( '.repeater-list table.table-actions' );
var $actionsTableHeader = $actionsTable.find( 'thead tr th' );
var $table = this.$element.find( '.repeater-list-wrapper > table' );
$actionsTableHeader.outerHeight( $table.find( 'thead tr th' ).outerHeight() );
$actionsTableHeader.find( '.repeater-list-heading' ).outerHeight( $actionsTableHeader.outerHeight() );
$actionsTable.find( 'tbody tr td:first-child' ).each( function( i, elem ) {
$( this ).outerHeight( $table.find( 'tbody tr:eq(' + i + ') td' ).outerHeight() );
} );
};
$.fn.repeater.Constructor.prototype.list_sizeFrozenColumns = function() {
var $table = this.$element.find( '.repeater-list .repeater-list-wrapper > table' );
this.$element.find( '.repeater-list table.table-frozen tr' ).each( function( i ) {
$( this ).height( $table.find( 'tr:eq(' + i + ')' ).height() );
} );
var columnWidth = $table.find( 'td:eq(0)' ).outerWidth();
this.$element.find( '.frozen-column-wrapper, .frozen-thead-wrapper' ).width( columnWidth );
};
$.fn.repeater.Constructor.prototype.list_frozenOptionsInitialize = function() {
var $checkboxes = this.$element.find( '.frozen-column-wrapper .checkbox-inline' );
var $everyTable = this.$element.find( '.repeater-list table' );
var self = this;
//Make sure if row is hovered that it is shown in frozen column as well
this.$element.find( 'tr.selectable' ).on( 'mouseover mouseleave', function( e ) {
var index = $( this ).index();
index = index + 1;
if ( e.type === 'mouseover' ) {
$everyTable.find( 'tbody tr:nth-child(' + index + ')' ).addClass( 'hovered' );
} else {
$everyTable.find( 'tbody tr:nth-child(' + index + ')' ).removeClass( 'hovered' );
}
} );
$checkboxes.checkbox();
this.$element.find( '.table-frozen tbody .checkbox-inline' ).on( 'change', function( e ) {
e.preventDefault();
if ( !self.list_revertingCheckbox ) {
if ( self.isDisabled ) {
revertCheckbox( $( e.currentTarget ) );
} else {
var row = $( this ).attr( 'data-row' );
row = parseInt( row ) + 1;
self.$element.find( '.repeater-list-wrapper > table tbody tr:nth-child(' + row + ')' ).click();
}
}
} );
this.$element.find( '.frozen-thead-wrapper thead .checkbox-inline' ).on( 'change', function( e ) {
if ( !self.list_revertingCheckbox ) {
if ( self.isDisabled ) {
revertCheckbox( $( e.currentTarget ) );
} else {
if ( $( this ).checkbox( 'isChecked' ) ) {
self.$element.find( '.repeater-list-wrapper > table tbody tr:not(.selected)' ).click();
self.$element.trigger( 'selected.fu.repeaterList', $checkboxes );
} else {
self.$element.find( '.repeater-list-wrapper > table tbody tr.selected' ).click();
self.$element.trigger( 'deselected.fu.repeaterList', $checkboxes );
}
}
}
} );
function revertCheckbox( $checkbox ) {
self.list_revertingCheckbox = true;
$checkbox.checkbox( 'toggle' );
delete self.list_revertingCheckbox;
}
};
//ADDITIONAL DEFAULT OPTIONS
$.fn.repeater.defaults = $.extend( {}, $.fn.repeater.defaults, {
list_columnRendered: null,
list_columnSizing: true,
list_columnSyncing: true,
list_highlightSortedColumn: true,
list_infiniteScroll: false,
list_noItemsHTML: 'no items found',
list_selectable: false,
list_sortClearing: false,
list_rowRendered: null,
list_frozenColumns: 0,
list_actions: false
} );
//EXTENSION DEFINITION
$.fn.repeater.viewTypes.list = {
cleared: function() {
if ( this.viewOptions.list_columnSyncing ) {
this.list_sizeHeadings();
}
},
dataOptions: function( options ) {
if ( this.list_sortDirection ) {
options.sortDirection = this.list_sortDirection;
}
if ( this.list_sortProperty ) {
options.sortProperty = this.list_sortProperty;
}
return options;
},
enabled: function( helpers ) {
if ( this.viewOptions.list_actions ) {
if ( !helpers.status ) {
this.$canvas.find( '.repeater-actions-button' ).attr( 'disabled', 'disabled' );
} else {
this.$canvas.find( '.repeater-actions-button' ).removeAttr( 'disabled' );
toggleActionsHeaderButton.call( this );
}
}
},
initialize: function( helpers, callback ) {
this.list_sortDirection = null;
this.list_sortProperty = null;
this.list_specialBrowserClass = specialBrowserClass();
this.list_actions_width = ( this.viewOptions.list_actions.width !== undefined ) ? this.viewOptions.list_actions.width : 37;
this.list_noItems = false;
callback();
},
resize: function() {
sizeColumns.call( this, this.$element.find( '.repeater-list-wrapper > table thead tr' ) );
if ( this.viewOptions.list_actions ) {
this.list_sizeActionsTable();
}
if ( this.viewOptions.list_frozenColumns || this.viewOptions.list_selectable === 'multi' ) {
this.list_sizeFrozenColumns();
}
if ( this.viewOptions.list_columnSyncing ) {
this.list_sizeHeadings();
}
},
selected: function() {
var infScroll = this.viewOptions.list_infiniteScroll;
var opts;
this.list_firstRender = true;
this.$loader.addClass( 'noHeader' );
if ( infScroll ) {
opts = ( typeof infScroll === 'object' ) ? infScroll : {};
this.infiniteScrolling( true, opts );
}
},
before: function( helpers ) {
var $listContainer = helpers.container.find( '.repeater-list' );
var self = this;
var $table;
if ( $listContainer.length < 1 ) {
$listContainer = $( '<div class="repeater-list ' + this.list_specialBrowserClass + '" data-preserve="shallow"><div class="repeater-list-wrapper" data-infinite="true" data-preserve="shallow"><table aria-readonly="true" class="table" data-preserve="shallow" role="grid"></table></div></div>' );
$listContainer.find( '.repeater-list-wrapper' ).on( 'scroll.fu.repeaterList', function() {
if ( self.viewOptions.list_columnSyncing ) {
self.list_positionHeadings();
}
} );
if ( self.viewOptions.list_frozenColumns || self.viewOptions.list_actions || self.viewOptions.list_selectable === 'multi' ) {
helpers.container.on( 'scroll.fu.repeaterList', function() {
self.list_positionColumns();
} );
}
helpers.container.append( $listContainer );
}
helpers.container.removeClass( 'actions-enabled actions-enabled multi-select-enabled' );
$table = $listContainer.find( 'table' );
renderThead.call( this, $table, helpers.data );
renderTbody.call( this, $table, helpers.data );
return false;
},
renderItem: function( helpers ) {
renderRow.call( this, helpers.container, helpers.subset, helpers.index );
return false;
},
after: function() {
var $sorted;
if ( ( this.viewOptions.list_frozenColumns || this.viewOptions.list_selectable === 'multi' ) && !this.list_noItems ) {
this.list_setFrozenColumns();
}
if ( this.viewOptions.list_actions && !this.list_noItems ) {
this.list_createItemActions();
this.list_sizeActionsTable();
}
if ( ( this.viewOptions.list_frozenColumns || this.viewOptions.list_actions || this.viewOptions.list_selectable === 'multi' ) && !this.list_noItems ) {
this.list_positionColumns();
this.list_frozenOptionsInitialize();
}
if ( this.viewOptions.list_columnSyncing ) {
this.list_sizeHeadings();
this.list_positionHeadings();
}
$sorted = this.$canvas.find( '.repeater-list-wrapper > table .repeater-list-heading.sorted' );
if ( $sorted.length > 0 ) {
this.list_highlightColumn( $sorted.data( 'fu_item_index' ) );
}
return false;
}
};
}
//ADDITIONAL METHODS
function areDifferentColumns( oldCols, newCols ) {
if ( !newCols ) {
return false;
}
if ( !oldCols || ( newCols.length !== oldCols.length ) ) {
return true;
}
for ( var i = 0; i < newCols.length; i++ ) {
if ( !oldCols[ i ] ) {
return true;
} else {
for ( var j in newCols[ i ] ) {
if ( oldCols[ i ][ j ] !== newCols[ i ][ j ] ) {
return true;
}
}
}
}
return false;
}
function renderColumn( $row, rows, rowIndex, columns, columnIndex ) {
var className = columns[ columnIndex ].className;
var content = rows[ rowIndex ][ columns[ columnIndex ].property ];
var $col = $( '<td></td>' );
var width = columns[ columnIndex ]._auto_width;
var property = columns[ columnIndex ].property;
if ( this.viewOptions.list_actions !== false && property === '@_ACTIONS_@' ) {
content = '<div class="repeater-list-actions-placeholder" style="width: ' + this.list_actions_width + 'px"></div>';
}
content = ( content !== undefined ) ? content : '';
$col.addClass( ( ( className !== undefined ) ? className : '' ) ).append( content );
if ( width !== undefined ) {
$col.outerWidth( width );
}
$row.append( $col );
if ( this.viewOptions.list_selectable === 'multi' && columns[ columnIndex ].property === '@_CHECKBOX_@' ) {
var checkBoxMarkup = '<label data-row="' + rowIndex + '" class="checkbox-custom checkbox-inline body-checkbox repeater-select-checkbox">' +
'<input class="sr-only" type="checkbox"></label>';
$col.html( checkBoxMarkup );
}
if ( !( columns[ columnIndex ].property === '@_CHECKBOX_@' || columns[ columnIndex ].property === '@_ACTIONS_@' ) && this.viewOptions.list_columnRendered ) {
this.viewOptions.list_columnRendered( {
container: $row,
columnAttr: columns[ columnIndex ].property,
item: $col,
rowData: rows[ rowIndex ]
}, function() {} );
}
}
function renderHeader( $tr, columns, index ) {
var chevDown = 'glyphicon-chevron-down';
var chevron = '.glyphicon.rlc:first';
var chevUp = 'glyphicon-chevron-up';
var $div = $( '<div class="repeater-list-heading"><span class="glyphicon rlc"></span></div>' );
var checkBoxMarkup = '<div class="repeater-list-heading header-checkbox"><label class="checkbox-custom checkbox-inline repeater-select-checkbox">' +
'<input class="sr-only" type="checkbox"></label><div class="clearfix"></div></div>';
var $header = $( '<th></th>' );
var self = this;
var $both, className, sortable, $span, $spans;
$div.data( 'fu_item_index', index );
$div.prepend( columns[ index ].label );
$header.html( $div.html() ).find( '[id]' ).removeAttr( 'id' );
if ( columns[ index ].property !== '@_CHECKBOX_@' ) {
$header.append( $div );
} else {
$header.append( checkBoxMarkup );
}
$both = $header.add( $div );
$span = $div.find( chevron );
$spans = $span.add( $header.find( chevron ) );
if ( this.viewOptions.list_actions && columns[ index ].property === '@_ACTIONS_@' ) {
var width = this.list_actions_width;
$header.css( 'width', width );
$div.css( 'width', width );
}
className = columns[ index ].className;
if ( className !== undefined ) {
$both.addClass( className );
}
sortable = columns[ index ].sortable;
if ( sortable ) {
$both.addClass( 'sortable' );
$div.on( 'click.fu.repeaterList', function() {
if ( !self.isDisabled ) {
self.list_sortProperty = ( typeof sortable === 'string' ) ? sortable : columns[ index ].property;
if ( $div.hasClass( 'sorted' ) ) {
if ( $span.hasClass( chevUp ) ) {
$spans.removeClass( chevUp ).addClass( chevDown );
self.list_sortDirection = 'desc';
} else {
if ( !self.viewOptions.list_sortClearing ) {
$spans.removeClass( chevDown ).addClass( chevUp );
self.list_sortDirection = 'asc';
} else {
$both.removeClass( 'sorted' );
$spans.removeClass( chevDown );
self.list_sortDirection = null;
self.list_sortProperty = null;
}
}
} else {
$tr.find( 'th, .repeater-list-heading' ).removeClass( 'sorted' );
$spans.removeClass( chevDown ).addClass( chevUp );
self.list_sortDirection = 'asc';
$both.addClass( 'sorted' );
}
self.render( {
clearInfinite: true,
pageIncrement: null
} );
}
} );
}
if ( columns[ index ].sortDirection === 'asc' || columns[ index ].sortDirection === 'desc' ) {
$tr.find( 'th, .repeater-list-heading' ).removeClass( 'sorted' );
$both.addClass( 'sortable sorted' );
if ( columns[ index ].sortDirection === 'asc' ) {
$spans.addClass( chevUp );
this.list_sortDirection = 'asc';
} else {
$spans.addClass( chevDown );
this.list_sortDirection = 'desc';
}
this.list_sortProperty = ( typeof sortable === 'string' ) ? sortable : columns[ index ].property;
}
$tr.append( $header );
}
function renderRow( $tbody, rows, index ) {
var $row = $( '<tr></tr>' );
var self = this;
var i, length;
var isMulti = this.viewOptions.list_selectable === 'multi';
var isActions = this.viewOptions.list_actions;
if ( this.viewOptions.list_selectable ) {
$row.data( 'item_data', rows[ index ] );
if ( this.viewOptions.list_selectable !== 'action' ) {
$row.addClass( 'selectable' );
$row.attr( 'tabindex', 0 ); // allow items to be tabbed to / focused on
$row.on( 'click.fu.repeaterList', function() {
if ( !self.isDisabled ) {
var $item = $( this );
var index = $( this ).index();
index = index + 1;
var $frozenRow = self.$element.find( '.frozen-column-wrapper tr:nth-child(' + index + ')' );
var $actionsRow = self.$element.find( '.actions-column-wrapper tr:nth-child(' + index + ')' );
var $checkBox = self.$element.find( '.frozen-column-wrapper tr:nth-child(' + index + ') .checkbox-inline' );
if ( $item.is( '.selected' ) ) {
$item.removeClass( 'selected' );
if ( isMulti ) {
$checkBox.checkbox( 'uncheck' );
$frozenRow.removeClass( 'selected' );
if ( isActions ) {
$actionsRow.removeClass( 'selected' );
}
} else {
$item.find( '.repeater-list-check' ).remove();
}
self.$element.trigger( 'deselected.fu.repeaterList', $item );
} else {
if ( !isMulti ) {
self.$canvas.find( '.repeater-list-check' ).remove();
self.$canvas.find( '.repeater-list tbody tr.selected' ).each( function() {
$( this ).removeClass( 'selected' );
self.$element.trigger( 'deselected.fu.repeaterList', $( this ) );
} );
$item.find( 'td:first' ).prepend( '<div class="repeater-list-check"><span class="glyphicon glyphicon-ok"></span></div>' );
$item.addClass( 'selected' );
$frozenRow.addClass( 'selected' );
} else {
$checkBox.checkbox( 'check' );
$item.addClass( 'selected' );
$frozenRow.addClass( 'selected' );
if ( isActions ) {
$actionsRow.addClass( 'selected' );
}
}
self.$element.trigger( 'selected.fu.repeaterList', $item );
}
toggleActionsHeaderButton.call( self );
}
} );
// allow selection via enter key
$row.keyup( function( e ) {
if ( e.keyCode === 13 ) {
// triggering a standard click event to be caught by the row click handler above
$row.trigger( 'click.fu.repeaterList' );
}
} );
}
}
if ( this.viewOptions.list_actions && !this.viewOptions.list_selectable ) {
$row.data( 'item_data', rows[ index ] );
}
$tbody.append( $row );
for ( i = 0, length = this.list_columns.length; i < length; i++ ) {
renderColumn.call( this, $row, rows, index, this.list_columns, i );
}
if ( this.viewOptions.list_rowRendered ) {
this.viewOptions.list_rowRendered( {
container: $tbody,
item: $row,
rowData: rows[ index ]
}, function() {} );
}
}
function renderTbody( $table, data ) {
var $tbody = $table.find( 'tbody' );
var $empty;
if ( $tbody.length < 1 ) {
$tbody = $( '<tbody data-container="true"></tbody>' );
$table.append( $tbody );
}
if ( typeof data.error === 'string' && data.error.length > 0 ) {
$empty = $( '<tr class="empty text-danger"><td colspan="' + this.list_columns.length + '"></td></tr>' );
$empty.find( 'td' ).append( data.error );
$tbody.append( $empty );
} else if ( data.items && data.items.length < 1 ) {
$empty = $( '<tr class="empty"><td colspan="' + this.list_columns.length + '"></td></tr>' );
$empty.find( 'td' ).append( this.viewOptions.list_noItemsHTML );
$tbody.append( $empty );
}
}
function renderThead( $table, data ) {
var columns = data.columns || [];
var $thead = $table.find( 'thead' );
var i, length, $tr;
if ( this.list_firstRender || areDifferentColumns( this.list_columns, columns ) || $thead.length === 0 ) {
$thead.remove();
if ( data.count < 1 ) {
this.list_noItems = true;
}
if ( this.viewOptions.list_selectable === 'multi' && !this.list_noItems ) {
var checkboxColumn = {
label: 'c',
property: '@_CHECKBOX_@',
sortable: false
};
columns.splice( 0, 0, checkboxColumn );
}
this.list_columns = columns;
this.list_firstRender = false;
this.$loader.removeClass( 'noHeader' );
if ( this.viewOptions.list_actions && !this.list_noItems ) {
var actionsColumn = {
label: this.viewOptions.list_actions.label || '<span class="actions-hidden">a</span>',
property: '@_ACTIONS_@',
sortable: false,
width: this.list_actions_width
};
columns.push( actionsColumn );
}
$thead = $( '<thead data-preserve="deep"><tr></tr></thead>' );
$tr = $thead.find( 'tr' );
for ( i = 0, length = columns.length; i < length; i++ ) {
renderHeader.call( this, $tr, columns, i );
}
$table.prepend( $thead );
if ( this.viewOptions.list_selectable === 'multi' && !this.list_noItems ) {
//after checkbox column is created need to get width of checkbox column from
//its css class
var checkboxWidth = this.$element.find( '.repeater-list-wrapper .header-checkbox' ).outerWidth();
var selectColumn = $.grep( columns, function( column ) {
return column.property === '@_CHECKBOX_@';
} )[ 0 ];
selectColumn.width = checkboxWidth;
}
sizeColumns.call( this, $tr );
}
}
function sizeColumns( $tr ) {
var automaticallyGeneratedWidths = [];
var self = this;
var i, length, newWidth, widthTaken;
if ( this.viewOptions.list_columnSizing ) {
i = 0;
widthTaken = 0;
$tr.find( 'th' ).each( function() {
var $th = $( this );
var width;
if ( self.list_columns[ i ].width !== undefined ) {
width = self.list_columns[ i ].width;
$th.outerWidth( width );
widthTaken += $th.outerWidth();
self.list_columns[ i ]._auto_width = width;
} else {
var outerWidth = $th.find( '.repeater-list-heading' ).outerWidth();
automaticallyGeneratedWidths.push( {
col: $th,
index: i,
minWidth: outerWidth
} );
}
i++;
} );
length = automaticallyGeneratedWidths.length;
if ( length > 0 ) {
var canvasWidth = this.$canvas.find( '.repeater-list-wrapper' ).outerWidth();
newWidth = Math.floor( ( canvasWidth - widthTaken ) / length );
for ( i = 0; i < length; i++ ) {
if ( automaticallyGeneratedWidths[ i ].minWidth > newWidth ) {
newWidth = automaticallyGeneratedWidths[ i ].minWidth;
}
automaticallyGeneratedWidths[ i ].col.outerWidth( newWidth );
this.list_columns[ automaticallyGeneratedWidths[ i ].index ]._auto_width = newWidth;
}
}
}
}
function specialBrowserClass() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf( "MSIE " );
var firefox = ua.indexOf( 'Firefox' );
if ( msie > 0 ) {
return 'ie-' + parseInt( ua.substring( msie + 5, ua.indexOf( ".", msie ) ) );
} else if ( firefox > 0 ) {
return 'firefox';
} else {
return '';
}
}
function toggleActionsHeaderButton() {
var selectedSelector = '.repeater-list-wrapper > table .selected';
var $actionsColumn = this.$element.find( '.table-actions' );
var $selected;
if ( this.viewOptions.list_selectable === 'action' ) {
selectedSelector = '.repeater-list-wrapper > table tr';
}
$selected = this.$canvas.find( selectedSelector );
if ( $selected.length > 0 ) {
$actionsColumn.find( 'thead .btn' ).removeAttr( 'disabled' );
} else {
$actionsColumn.find( 'thead .btn' ).attr( 'disabled', 'disabled' );
}
}
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Repeater - Thumbnail View Plugin
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
if ( $.fn.repeater ) {
//ADDITIONAL METHODS
$.fn.repeater.Constructor.prototype.thumbnail_clearSelectedItems = function() {
this.$canvas.find( '.repeater-thumbnail-cont .selectable.selected' ).removeClass( 'selected' );
};
$.fn.repeater.Constructor.prototype.thumbnail_getSelectedItems = function() {
var selected = [];
this.$canvas.find( '.repeater-thumbnail-cont .selectable.selected' ).each( function() {
selected.push( $( this ) );
} );
return selected;
};
$.fn.repeater.Constructor.prototype.thumbnail_setSelectedItems = function( items, force ) {
var selectable = this.viewOptions.thumbnail_selectable;
var self = this;
var i, $item, l, n;
//this function is necessary because lint yells when a function is in a loop
function compareItemIndex() {
if ( n === items[ i ].index ) {
$item = $( this );
return false;
} else {
n++;
}
}
//this function is necessary because lint yells when a function is in a loop
function compareItemSelector() {
$item = $( this );
if ( $item.is( items[ i ].selector ) ) {
selectItem( $item, items[ i ].selected );
}
}
function selectItem( $itm, select ) {
select = ( select !== undefined ) ? select : true;
if ( select ) {
if ( !force && selectable !== 'multi' ) {
self.thumbnail_clearSelectedItems();
}
$itm.addClass( 'selected' );
} else {
$itm.removeClass( 'selected' );
}
}
if ( !$.isArray( items ) ) {
items = [ items ];
}
if ( force === true || selectable === 'multi' ) {
l = items.length;
} else if ( selectable ) {
l = ( items.length > 0 ) ? 1 : 0;
} else {
l = 0;
}
for ( i = 0; i < l; i++ ) {
if ( items[ i ].index !== undefined ) {
$item = $();
n = 0;
this.$canvas.find( '.repeater-thumbnail-cont .selectable' ).each( compareItemIndex );
if ( $item.length > 0 ) {
selectItem( $item, items[ i ].selected );
}
} else if ( items[ i ].selector ) {
this.$canvas.find( '.repeater-thumbnail-cont .selectable' ).each( compareItemSelector );
}
}
};
//ADDITIONAL DEFAULT OPTIONS
$.fn.repeater.defaults = $.extend( {}, $.fn.repeater.defaults, {
thumbnail_alignment: 'left',
thumbnail_infiniteScroll: false,
thumbnail_itemRendered: null,
thumbnail_noItemsHTML: 'no items found',
thumbnail_selectable: false,
thumbnail_template: '<div class="thumbnail repeater-thumbnail"><img height="75" src="{{src}}" width="65"><span>{{name}}</span></div>'
} );
//EXTENSION DEFINITION
$.fn.repeater.viewTypes.thumbnail = {
selected: function() {
var infScroll = this.viewOptions.thumbnail_infiniteScroll;
var opts;
if ( infScroll ) {
opts = ( typeof infScroll === 'object' ) ? infScroll : {};
this.infiniteScrolling( true, opts );
}
},
before: function( helpers ) {
var alignment = this.viewOptions.thumbnail_alignment;
var $cont = this.$canvas.find( '.repeater-thumbnail-cont' );
var data = helpers.data;
var response = {};
var $empty, validAlignments;
if ( $cont.length < 1 ) {
$cont = $( '<div class="clearfix repeater-thumbnail-cont" data-container="true" data-infinite="true" data-preserve="shallow"></div>' );
if ( alignment && alignment !== 'none' ) {
validAlignments = {
'center': 1,
'justify': 1,
'left': 1,
'right': 1
};
alignment = ( validAlignments[ alignment ] ) ? alignment : 'justify';
$cont.addClass( 'align-' + alignment );
this.thumbnail_injectSpacers = true;
} else {
this.thumbnail_injectSpacers = false;
}
response.item = $cont;
} else {
response.action = 'none';
}
if ( data.items && data.items.length < 1 ) {
$empty = $( '<div class="empty"></div>' );
$empty.append( this.viewOptions.thumbnail_noItemsHTML );
$cont.append( $empty );
} else {
$cont.find( '.empty:first' ).remove();
}
return response;
},
renderItem: function( helpers ) {
var selectable = this.viewOptions.thumbnail_selectable;
var selected = 'selected';
var self = this;
var $thumbnail = $( fillTemplate( helpers.subset[ helpers.index ], this.viewOptions.thumbnail_template ) );
$thumbnail.data( 'item_data', helpers.data.items[ helpers.index ] );
if ( selectable ) {
$thumbnail.addClass( 'selectable' );
$thumbnail.on( 'click', function() {
if ( self.isDisabled ) return;
if ( !$thumbnail.hasClass( selected ) ) {
if ( selectable !== 'multi' ) {
self.$canvas.find( '.repeater-thumbnail-cont .selectable.selected' ).each( function() {
var $itm = $( this );
$itm.removeClass( selected );
self.$element.trigger( 'deselected.fu.repeaterThumbnail', $itm );
} );
}
$thumbnail.addClass( selected );
self.$element.trigger( 'selected.fu.repeaterThumbnail', $thumbnail );
} else {
$thumbnail.removeClass( selected );
self.$element.trigger( 'deselected.fu.repeaterThumbnail', $thumbnail );
}
} );
}
helpers.container.append( $thumbnail );
if ( this.thumbnail_injectSpacers ) {
$thumbnail.after( '<span class="spacer"> </span>' );
}
if ( this.viewOptions.thumbnail_itemRendered ) {
this.viewOptions.thumbnail_itemRendered( {
container: helpers.container,
item: $thumbnail,
itemData: helpers.subset[ helpers.index ]
}, function() {} );
}
return false;
}
};
}
//ADDITIONAL METHODS
function fillTemplate( itemData, template ) {
var invalid = false;
function replace() {
var end, start, val;
start = template.indexOf( '{{' );
end = template.indexOf( '}}', start + 2 );
if ( start > -1 && end > -1 ) {
val = $.trim( template.substring( start + 2, end ) );
val = ( itemData[ val ] !== undefined ) ? itemData[ val ] : '';
template = template.substring( 0, start ) + val + template.substring( end + 2 );
} else {
invalid = true;
}
}
while ( !invalid && template.search( '{{' ) >= 0 ) {
replace( template );
}
return template;
}
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Scheduler
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.scheduler;
// SCHEDULER CONSTRUCTOR AND PROTOTYPE
var Scheduler = function Scheduler( element, options ) {
var self = this;
this.$element = $( element );
this.options = $.extend( {}, $.fn.scheduler.defaults, options );
// cache elements
this.$startDate = this.$element.find( '.start-datetime .start-date' );
this.$startTime = this.$element.find( '.start-datetime .start-time' );
this.$timeZone = this.$element.find( '.timezone-container .timezone' );
this.$repeatIntervalPanel = this.$element.find( '.repeat-every-panel' );
this.$repeatIntervalSelect = this.$element.find( '.repeat-options' );
this.$repeatIntervalSpinbox = this.$element.find( '.repeat-every' );
this.$repeatIntervalTxt = this.$element.find( '.repeat-every-text' );
this.$end = this.$element.find( '.repeat-end' );
this.$endSelect = this.$end.find( '.end-options' );
this.$endAfter = this.$end.find( '.end-after' );
this.$endDate = this.$end.find( '.end-on-date' );
// panels
this.$recurrencePanels = this.$element.find( '.repeat-panel' );
this.$repeatIntervalSelect.selectlist();
//initialize sub-controls
this.$element.find( '.selectlist' ).selectlist();
this.$startDate.datepicker( this.options.startDateOptions );
var startDateResponse = ( typeof this.options.startDateChanged === "function" ) ? this.options.startDateChanged : this._guessEndDate;
this.$startDate.on( 'change changed.fu.datepicker dateClicked.fu.datepicker', $.proxy( startDateResponse, this ) );
this.$startTime.combobox();
// init start time
if ( this.$startTime.find( 'input' ).val() === '' ) {
this.$startTime.combobox( 'selectByIndex', 0 );
}
// every 0 days/hours doesn't make sense, change if not set
if ( this.$repeatIntervalSpinbox.find( 'input' ).val() === '0' ) {
this.$repeatIntervalSpinbox.spinbox( {
'value': 1,
'min': 1,
'limitToStep': true
} );
} else {
this.$repeatIntervalSpinbox.spinbox( {
'min': 1,
'limitToStep': true
} );
}
this.$endAfter.spinbox( {
'value': 1,
'min': 1,
'limitToStep': true
} );
this.$endDate.datepicker( this.options.endDateOptions );
this.$element.find( '.radio-custom' ).radio();
// bind events: 'change' is a Bootstrap JS fired event
this.$repeatIntervalSelect.on( 'changed.fu.selectlist', $.proxy( this.repeatIntervalSelectChanged, this ) );
this.$endSelect.on( 'changed.fu.selectlist', $.proxy( this.endSelectChanged, this ) );
this.$element.find( '.repeat-days-of-the-week .btn-group .btn' ).on( 'change.fu.scheduler', function( e, data ) {
self.changed( e, data, true );
} );
this.$element.find( '.combobox' ).on( 'changed.fu.combobox', $.proxy( this.changed, this ) );
this.$element.find( '.datepicker' ).on( 'changed.fu.datepicker', $.proxy( this.changed, this ) );
this.$element.find( '.datepicker' ).on( 'dateClicked.fu.datepicker', $.proxy( this.changed, this ) );
this.$element.find( '.selectlist' ).on( 'changed.fu.selectlist', $.proxy( this.changed, this ) );
this.$element.find( '.spinbox' ).on( 'changed.fu.spinbox', $.proxy( this.changed, this ) );
this.$element.find( '.repeat-monthly .radio-custom, .repeat-yearly .radio-custom' ).on( 'change.fu.scheduler', $.proxy( this.changed, this ) );
};
var _getFormattedDate = function _getFormattedDate( dateObj, dash ) {
var fdate = '';
var item;
fdate += dateObj.getFullYear();
fdate += dash;
item = dateObj.getMonth() + 1; //because 0 indexing makes sense when dealing with months /sarcasm
fdate += ( item < 10 ) ? '0' + item : item;
fdate += dash;
item = dateObj.getDate();
fdate += ( item < 10 ) ? '0' + item : item;
return fdate;
};
var ONE_SECOND = 1000;
var ONE_MINUTE = ONE_SECOND * 60;
var ONE_HOUR = ONE_MINUTE * 60;
var ONE_DAY = ONE_HOUR * 24;
var ONE_WEEK = ONE_DAY * 7;
var ONE_MONTH = ONE_WEEK * 5; // No good way to increment by one month using vanilla JS. Since this is an end date, we only need to ensure that this date occurs after at least one or more repeat increments, but there is no reason for it to be exact.
var ONE_YEAR = ONE_WEEK * 52;
var INTERVALS = {
secondly: ONE_SECOND,
minutely: ONE_MINUTE,
hourly: ONE_HOUR,
daily: ONE_DAY,
weekly: ONE_WEEK,
monthly: ONE_MONTH,
yearly: ONE_YEAR
};
var _incrementDate = function _incrementDate( start, end, interval, increment ) {
return new Date( start.getTime() + ( INTERVALS[ interval ] * increment ) );
};
Scheduler.prototype = {
constructor: Scheduler,
destroy: function destroy() {
var markup;
// set input value attribute
this.$element.find( 'input' ).each( function() {
$( this ).attr( 'value', $( this ).val() );
} );
// empty elements to return to original markup and store
this.$element.find( '.datepicker .calendar' ).empty();
markup = this.$element[ 0 ].outerHTML;
// destroy components
this.$element.find( '.combobox' ).combobox( 'destroy' );
this.$element.find( '.datepicker' ).datepicker( 'destroy' );
this.$element.find( '.selectlist' ).selectlist( 'destroy' );
this.$element.find( '.spinbox' ).spinbox( 'destroy' );
this.$element.find( '.radio-custom' ).radio( 'destroy' );
this.$element.remove();
// any external bindings
// [none]
return markup;
},
changed: function changed( e, data, propagate ) {
if ( !propagate ) {
e.stopPropagation();
}
this.$element.trigger( 'changed.fu.scheduler', {
data: ( data !== undefined ) ? data : $( e.currentTarget ).data(),
originalEvent: e,
value: this.getValue()
} );
},
disable: function disable() {
this.toggleState( 'disable' );
},
enable: function enable() {
this.toggleState( 'enable' );
},
setUtcTime: function setUtcTime( day, time, offset ) {
var dateSplit = day.split( '-' );
var timeSplit = time.split( ':' );
function z( n ) {
return ( n < 10 ? '0' : '' ) + n;
}
var utcDate = new Date( Date.UTC( dateSplit[ 0 ], ( dateSplit[ 1 ] - 1 ), dateSplit[ 2 ], timeSplit[ 0 ], timeSplit[ 1 ], ( timeSplit[ 2 ] ? timeSplit[ 2 ] : 0 ) ) );
if ( offset === 'Z' ) {
utcDate.setUTCHours( utcDate.getUTCHours() + 0 );
} else {
var expression = [];
expression[ 0 ] = '(.)'; // Any Single Character 1
expression[ 1 ] = '.*?'; // Non-greedy match on filler
expression[ 2 ] = '\\d'; // Uninteresting and ignored: d
expression[ 3 ] = '.*?'; // Non-greedy match on filler
expression[ 4 ] = '(\\d)'; // Any Single Digit 1
var p = new RegExp( expression.join( '' ), [ "i" ] );
var offsetMatch = p.exec( offset );
if ( offsetMatch !== null ) {
var offsetDirection = offsetMatch[ 1 ];
var offsetInteger = offsetMatch[ 2 ];
var modifier = ( offsetDirection === '+' ) ? 1 : -1;
utcDate.setUTCHours( utcDate.getUTCHours() + ( modifier * parseInt( offsetInteger, 10 ) ) );
}
}
var localDifference = utcDate.getTimezoneOffset();
utcDate.setMinutes( localDifference );
return utcDate;
},
// called when the end range changes
// (Never, After, On date)
endSelectChanged: function endSelectChanged( e, data ) {
var selectedItem, val;
if ( !data ) {
selectedItem = this.$endSelect.selectlist( 'selectedItem' );
val = selectedItem.value;
} else {
val = data.value;
}
// hide all panels
this.$endAfter.parent().addClass( 'hidden' );
this.$endAfter.parent().attr( 'aria-hidden', 'true' );
this.$endDate.parent().addClass( 'hidden' );
this.$endDate.parent().attr( 'aria-hidden', 'true' );
if ( val === 'after' ) {
this.$endAfter.parent().removeClass( 'hide hidden' ); // hide is deprecated
this.$endAfter.parent().attr( 'aria-hidden', 'false' );
} else if ( val === 'date' ) {
this.$endDate.parent().removeClass( 'hide hidden' ); // hide is deprecated
this.$endDate.parent().attr( 'aria-hidden', 'false' );
}
},
_guessEndDate: function _guessEndDate() {
var interval = this.$repeatIntervalSelect.selectlist( 'selectedItem' ).value;
var end = new Date( this.$endDate.datepicker( 'getDate' ) );
var start = new Date( this.$startDate.datepicker( 'getDate' ) );
var increment = this.$repeatIntervalSpinbox.find( 'input' ).val();
if ( interval !== "none" && end <= start ) {
// if increment spinbox is hidden, user has no idea what it is set to and it is probably not set to
// something they intended. Safest option is to set date forward by an increment of 1.
// this will keep monthly & yearly from auto-incrementing by more than a single interval
if ( !this.$repeatIntervalSpinbox.is( ':visible' ) ) {
increment = 1;
}
// treat weekdays as weekly. This treats all "weekdays" as a single set, of which a single increment
// is one week.
if ( interval === "weekdays" ) {
increment = 1;
interval = "weekly";
}
end = _incrementDate( start, end, interval, increment );
this.$endDate.datepicker( 'setDate', end );
}
},
getValue: function getValue() {
// FREQ = frequency (secondly, minutely, hourly, daily, weekdays, weekly, monthly, yearly)
// BYDAY = when picking days (MO,TU,WE,etc)
// BYMONTH = when picking months (Jan,Feb,March) - note the values should be 1,2,3...
// BYMONTHDAY = when picking days of the month (1,2,3...)
// BYSETPOS = when picking First,Second,Third,Fourth,Last (1,2,3,4,-1)
var interval = this.$repeatIntervalSpinbox.spinbox( 'value' );
var pattern = '';
var repeat = this.$repeatIntervalSelect.selectlist( 'selectedItem' ).value;
var startTime;
if ( this.$startTime.combobox( 'selectedItem' ).value ) {
startTime = this.$startTime.combobox( 'selectedItem' ).value;
startTime = startTime.toLowerCase();
} else {
startTime = this.$startTime.combobox( 'selectedItem' ).text.toLowerCase();
}
var timeZone = this.$timeZone.selectlist( 'selectedItem' );
var day, days, hasAm, hasPm, month, pos, startDateTime, type;
startDateTime = '' + _getFormattedDate( this.$startDate.datepicker( 'getDate' ), '-' );
startDateTime += 'T';
hasAm = ( startTime.search( 'am' ) >= 0 );
hasPm = ( startTime.search( 'pm' ) >= 0 );
startTime = $.trim( startTime.replace( /am/g, '' ).replace( /pm/g, '' ) ).split( ':' );
startTime[ 0 ] = parseInt( startTime[ 0 ], 10 );
startTime[ 1 ] = parseInt( startTime[ 1 ], 10 );
if ( hasAm && startTime[ 0 ] > 11 ) {
startTime[ 0 ] = 0;
} else if ( hasPm && startTime[ 0 ] < 12 ) {
startTime[ 0 ] += 12;
}
startDateTime += ( startTime[ 0 ] < 10 ) ? '0' + startTime[ 0 ] : startTime[ 0 ];
startDateTime += ':';
startDateTime += ( startTime[ 1 ] < 10 ) ? '0' + startTime[ 1 ] : startTime[ 1 ];
startDateTime += ( timeZone.offset === '+00:00' ) ? 'Z' : timeZone.offset;
if ( repeat === 'none' ) {
pattern = 'FREQ=DAILY;INTERVAL=1;COUNT=1;';
} else if ( repeat === 'secondly' ) {
pattern = 'FREQ=SECONDLY;';
pattern += 'INTERVAL=' + interval + ';';
} else if ( repeat === 'minutely' ) {
pattern = 'FREQ=MINUTELY;';
pattern += 'INTERVAL=' + interval + ';';
} else if ( repeat === 'hourly' ) {
pattern = 'FREQ=HOURLY;';
pattern += 'INTERVAL=' + interval + ';';
} else if ( repeat === 'daily' ) {
pattern += 'FREQ=DAILY;';
pattern += 'INTERVAL=' + interval + ';';
} else if ( repeat === 'weekdays' ) {
pattern += 'FREQ=WEEKLY;';
pattern += 'BYDAY=MO,TU,WE,TH,FR;';
pattern += 'INTERVAL=1;';
} else if ( repeat === 'weekly' ) {
days = [];
this.$element.find( '.repeat-days-of-the-week .btn-group input:checked' ).each( function() {
days.push( $( this ).data().value );
} );
pattern += 'FREQ=WEEKLY;';
pattern += 'BYDAY=' + days.join( ',' ) + ';';
pattern += 'INTERVAL=' + interval + ';';
} else if ( repeat === 'monthly' ) {
pattern += 'FREQ=MONTHLY;';
pattern += 'INTERVAL=' + interval + ';';
type = this.$element.find( 'input[name=repeat-monthly]:checked' ).val();
if ( type === 'bymonthday' ) {
day = parseInt( this.$element.find( '.repeat-monthly-date .selectlist' ).selectlist( 'selectedItem' ).text, 10 );
pattern += 'BYMONTHDAY=' + day + ';';
} else if ( type === 'bysetpos' ) {
days = this.$element.find( '.repeat-monthly-day .month-days' ).selectlist( 'selectedItem' ).value;
pos = this.$element.find( '.repeat-monthly-day .month-day-pos' ).selectlist( 'selectedItem' ).value;
pattern += 'BYDAY=' + days + ';';
pattern += 'BYSETPOS=' + pos + ';';
}
} else if ( repeat === 'yearly' ) {
pattern += 'FREQ=YEARLY;';
type = this.$element.find( 'input[name=repeat-yearly]:checked' ).val();
if ( type === 'bymonthday' ) {
// there are multiple .year-month classed elements in scheduler markup
month = this.$element.find( '.repeat-yearly-date .year-month' ).selectlist( 'selectedItem' ).value;
day = this.$element.find( '.repeat-yearly-date .year-month-day' ).selectlist( 'selectedItem' ).text;
pattern += 'BYMONTH=' + month + ';';
pattern += 'BYMONTHDAY=' + day + ';';
} else if ( type === 'bysetpos' ) {
days = this.$element.find( '.repeat-yearly-day .year-month-days' ).selectlist( 'selectedItem' ).value;
pos = this.$element.find( '.repeat-yearly-day .year-month-day-pos' ).selectlist( 'selectedItem' ).value;
// there are multiple .year-month classed elements in scheduler markup
month = this.$element.find( '.repeat-yearly-day .year-month' ).selectlist( 'selectedItem' ).value;
pattern += 'BYDAY=' + days + ';';
pattern += 'BYSETPOS=' + pos + ';';
pattern += 'BYMONTH=' + month + ';';
}
}
var end = this.$endSelect.selectlist( 'selectedItem' ).value;
var duration = '';
// if both UNTIL and COUNT are not specified, the recurrence will repeat forever
// http://tools.ietf.org/html/rfc2445#section-4.3.10
if ( repeat !== 'none' ) {
if ( end === 'after' ) {
duration = 'COUNT=' + this.$endAfter.spinbox( 'value' ) + ';';
} else if ( end === 'date' ) {
duration = 'UNTIL=' + _getFormattedDate( this.$endDate.datepicker( 'getDate' ), '' ) + ';';
}
}
pattern += duration;
// remove trailing semicolon
pattern = pattern.substring( pattern.length - 1 ) === ';' ? pattern.substring( 0, pattern.length - 1 ) : pattern;
var data = {
startDateTime: startDateTime,
timeZone: timeZone,
recurrencePattern: pattern
};
return data;
},
// called when the repeat interval changes
// (None, Hourly, Daily, Weekdays, Weekly, Monthly, Yearly
repeatIntervalSelectChanged: function repeatIntervalSelectChanged( e, data ) {
var selectedItem, val, txt;
if ( !data ) {
selectedItem = this.$repeatIntervalSelect.selectlist( 'selectedItem' );
val = selectedItem.value || "";
txt = selectedItem.text || "";
} else {
val = data.value;
txt = data.text;
}
// set the text
this.$repeatIntervalTxt.text( txt );
switch ( val.toLowerCase() ) {
case 'hourly':
case 'daily':
case 'weekly':
case 'monthly':
this.$repeatIntervalPanel.removeClass( 'hide hidden' ); // hide is deprecated
this.$repeatIntervalPanel.attr( 'aria-hidden', 'false' );
break;
default:
this.$repeatIntervalPanel.addClass( 'hidden' ); // hide is deprecated
this.$repeatIntervalPanel.attr( 'aria-hidden', 'true' );
break;
}
// hide all panels
this.$recurrencePanels.addClass( 'hidden' );
this.$recurrencePanels.attr( 'aria-hidden', 'true' );
// show panel for current selection
this.$element.find( '.repeat-' + val ).removeClass( 'hide hidden' ); // hide is deprecated
this.$element.find( '.repeat-' + val ).attr( 'aria-hidden', 'false' );
// the end selection should only be shown when
// the repeat interval is not "None (run once)"
if ( val === 'none' ) {
this.$end.addClass( 'hidden' );
this.$end.attr( 'aria-hidden', 'true' );
} else {
this.$end.removeClass( 'hide hidden' ); // hide is deprecated
this.$end.attr( 'aria-hidden', 'false' );
}
this._guessEndDate();
},
_parseAndSetRecurrencePattern: function( recurrencePattern, startTime ) {
var recur = {};
var i = 0;
var item = '';
var commaPatternSplit;
var $repeatMonthlyDate, $repeatYearlyDate, $repeatYearlyDay;
var semiColonPatternSplit = recurrencePattern.toUpperCase().split( ';' );
for ( i = 0; i < semiColonPatternSplit.length; i++ ) {
if ( semiColonPatternSplit[ i ] !== '' ) {
item = semiColonPatternSplit[ i ].split( '=' );
recur[ item[ 0 ] ] = item[ 1 ];
}
}
if ( recur.FREQ === 'DAILY' ) {
if ( recur.BYDAY === 'MO,TU,WE,TH,FR' ) {
item = 'weekdays';
} else {
if ( recur.INTERVAL === '1' && recur.COUNT === '1' ) {
item = 'none';
} else {
item = 'daily';
}
}
} else if ( recur.FREQ === 'SECONDLY' ) {
item = 'secondly';
} else if ( recur.FREQ === 'MINUTELY' ) {
item = 'minutely';
} else if ( recur.FREQ === 'HOURLY' ) {
item = 'hourly';
} else if ( recur.FREQ === 'WEEKLY' ) {
item = 'weekly';
if ( recur.BYDAY ) {
if ( recur.BYDAY === 'MO,TU,WE,TH,FR' ) {
item = 'weekdays';
} else {
var el = this.$element.find( '.repeat-days-of-the-week .btn-group' );
el.find( 'label' ).removeClass( 'active' );
commaPatternSplit = recur.BYDAY.split( ',' );
for ( i = 0; i < commaPatternSplit.length; i++ ) {
el.find( 'input[data-value="' + commaPatternSplit[ i ] + '"]' ).prop( 'checked', true ).parent().addClass( 'active' );
}
}
}
} else if ( recur.FREQ === 'MONTHLY' ) {
this.$element.find( '.repeat-monthly input' ).removeAttr( 'checked' ).removeClass( 'checked' );
this.$element.find( '.repeat-monthly label.radio-custom' ).removeClass( 'checked' );
if ( recur.BYMONTHDAY ) {
$repeatMonthlyDate = this.$element.find( '.repeat-monthly-date' );
$repeatMonthlyDate.find( 'input' ).addClass( 'checked' ).prop( 'checked', true );
$repeatMonthlyDate.find( 'label.radio-custom' ).addClass( 'checked' );
$repeatMonthlyDate.find( '.selectlist' ).selectlist( 'selectByValue', recur.BYMONTHDAY );
} else if ( recur.BYDAY ) {
var $repeatMonthlyDay = this.$element.find( '.repeat-monthly-day' );
$repeatMonthlyDay.find( 'input' ).addClass( 'checked' ).prop( 'checked', true );
$repeatMonthlyDay.find( 'label.radio-custom' ).addClass( 'checked' );
if ( recur.BYSETPOS ) {
$repeatMonthlyDay.find( '.month-day-pos' ).selectlist( 'selectByValue', recur.BYSETPOS );
}
$repeatMonthlyDay.find( '.month-days' ).selectlist( 'selectByValue', recur.BYDAY );
}
item = 'monthly';
} else if ( recur.FREQ === 'YEARLY' ) {
this.$element.find( '.repeat-yearly input' ).removeAttr( 'checked' ).removeClass( 'checked' );
this.$element.find( '.repeat-yearly label.radio-custom' ).removeClass( 'checked' );
if ( recur.BYMONTHDAY ) {
$repeatYearlyDate = this.$element.find( '.repeat-yearly-date' );
$repeatYearlyDate.find( 'input' ).addClass( 'checked' ).prop( 'checked', true );
$repeatYearlyDate.find( 'label.radio-custom' ).addClass( 'checked' );
if ( recur.BYMONTH ) {
$repeatYearlyDate.find( '.year-month' ).selectlist( 'selectByValue', recur.BYMONTH );
}
$repeatYearlyDate.find( '.year-month-day' ).selectlist( 'selectByValue', recur.BYMONTHDAY );
} else if ( recur.BYSETPOS ) {
$repeatYearlyDay = this.$element.find( '.repeat-yearly-day' );
$repeatYearlyDay.find( 'input' ).addClass( 'checked' ).prop( 'checked', true );
$repeatYearlyDay.find( 'label.radio-custom' ).addClass( 'checked' );
$repeatYearlyDay.find( '.year-month-day-pos' ).selectlist( 'selectByValue', recur.BYSETPOS );
if ( recur.BYDAY ) {
$repeatYearlyDay.find( '.year-month-days' ).selectlist( 'selectByValue', recur.BYDAY );
}
if ( recur.BYMONTH ) {
$repeatYearlyDay.find( '.year-month' ).selectlist( 'selectByValue', recur.BYMONTH );
}
}
item = 'yearly';
} else {
item = 'none';
}
if ( recur.COUNT ) {
this.$endAfter.spinbox( 'value', parseInt( recur.COUNT, 10 ) );
this.$endSelect.selectlist( 'selectByValue', 'after' );
} else if ( recur.UNTIL ) {
var untilSplit, untilDate;
if ( recur.UNTIL.length === 8 ) {
untilSplit = recur.UNTIL.split( '' );
untilSplit.splice( 4, 0, '-' );
untilSplit.splice( 7, 0, '-' );
untilDate = untilSplit.join( '' );
}
var timeZone = this.$timeZone.selectlist( 'selectedItem' );
var timezoneOffset = ( timeZone.offset === '+00:00' ) ? 'Z' : timeZone.offset;
var utcEndHours = this.setUtcTime( untilDate, startTime.time24HourFormat, timezoneOffset );
this.$endDate.datepicker( 'setDate', utcEndHours );
this.$endSelect.selectlist( 'selectByValue', 'date' );
} else {
this.$endSelect.selectlist( 'selectByValue', 'never' );
}
this.endSelectChanged();
if ( recur.INTERVAL ) {
this.$repeatIntervalSpinbox.spinbox( 'value', parseInt( recur.INTERVAL, 10 ) );
}
this.$repeatIntervalSelect.selectlist( 'selectByValue', item );
this.repeatIntervalSelectChanged();
},
_parseStartDateTime: function( startTimeISO8601 ) {
var startTime = {};
var startDate, startDateTimeISO8601FormatSplit, hours, minutes, period;
startTime.time24HourFormat = startTimeISO8601.split( '+' )[ 0 ].split( '-' )[ 0 ];
if ( startTimeISO8601.search( /\+/ ) > -1 ) {
startTime.timeZoneOffset = '+' + $.trim( startTimeISO8601.split( '+' )[ 1 ] );
} else if ( startTimeISO8601.search( /\-/ ) > -1 ) {
startTime.timeZoneOffset = '-' + $.trim( startTimeISO8601.split( '-' )[ 1 ] );
} else {
startTime.timeZoneOffset = '+00:00';
}
startTime.time24HourFormatSplit = startTime.time24HourFormat.split( ':' );
hours = parseInt( startTime.time24HourFormatSplit[ 0 ], 10 );
minutes = ( startTime.time24HourFormatSplit[ 1 ] ) ? parseInt( startTime.time24HourFormatSplit[ 1 ].split( '+' )[ 0 ].split( '-' )[ 0 ].split( 'Z' )[ 0 ], 10 ) : 0;
period = ( hours < 12 ) ? 'AM' : 'PM';
if ( hours === 0 ) {
hours = 12;
} else if ( hours > 12 ) {
hours -= 12;
}
minutes = ( minutes < 10 ) ? '0' + minutes : minutes;
startTime.time12HourFormat = hours + ':' + minutes;
startTime.time12HourFormatWithPeriod = hours + ':' + minutes + ' ' + period;
return startTime;
},
_parseTimeZone: function( options, startTime ) {
startTime.timeZoneQuerySelector = '';
if ( options.timeZone ) {
if ( typeof( options.timeZone ) === 'string' ) {
startTime.timeZoneQuerySelector += 'li[data-name="' + options.timeZone + '"]';
} else {
$.each( options.timeZone, function( key, value ) {
startTime.timeZoneQuerySelector += 'li[data-' + key + '="' + value + '"]';
} );
}
startTime.timeZoneOffset = options.timeZone.offset;
} else if ( options.startDateTime ) {
// Time zone has not been specified via options object, therefore use the timeZoneOffset from _parseAndSetStartDateTime
startTime.timeZoneOffset = ( startTime.timeZoneOffset === '+00:00' ) ? 'Z' : startTime.timeZoneOffset;
startTime.timeZoneQuerySelector += 'li[data-offset="' + startTime.timeZoneOffset + '"]';
} else {
startTime.timeZoneOffset = 'Z';
}
return startTime.timeZoneOffset;
},
_setTimeUI: function( time12HourFormatWithPeriod ) {
this.$startTime.find( 'input' ).val( time12HourFormatWithPeriod );
this.$startTime.combobox( 'selectByText', time12HourFormatWithPeriod );
},
_setTimeZoneUI: function( querySelector ) {
this.$timeZone.selectlist( 'selectBySelector', querySelector );
},
setValue: function setValue( options ) {
var startTime = {};
var startDateTime, startDate, startTimeISO8601, timeOffset, utcStartHours;
// TIME
if ( options.startDateTime ) {
startDateTime = options.startDateTime.split( 'T' );
startDate = startDateTime[ 0 ];
startTimeISO8601 = startDateTime[ 1 ];
if ( startTimeISO8601 ) {
startTime = this._parseStartDateTime( startTimeISO8601 );
this._setTimeUI( startTime.time12HourFormatWithPeriod );
} else {
startTime.time12HourFormat = '00:00';
startTime.time24HourFormat = '00:00';
}
} else {
startTime.time12HourFormat = '00:00';
startTime.time24HourFormat = '00:00';
var currentDate = this.$startDate.datepicker( 'getDate' );
startDate = currentDate.getFullYear() + '-' + currentDate.getMonth() + '-' + currentDate.getDate();
}
// TIMEZONE
this._parseTimeZone( options, startTime );
if ( startTime.timeZoneQuerySelector ) {
this._setTimeZoneUI( startTime.timeZoneQuerySelector );
}
// RECURRENCE PATTERN
if ( options.recurrencePattern ) {
this._parseAndSetRecurrencePattern( options.recurrencePattern, startTime );
}
utcStartHours = this.setUtcTime( startDate, startTime.time24HourFormat, startTime.timeZoneOffset );
this.$startDate.datepicker( 'setDate', utcStartHours );
},
toggleState: function toggleState( action ) {
this.$element.find( '.combobox' ).combobox( action );
this.$element.find( '.datepicker' ).datepicker( action );
this.$element.find( '.selectlist' ).selectlist( action );
this.$element.find( '.spinbox' ).spinbox( action );
this.$element.find( '.radio-custom' ).radio( action );
if ( action === 'disable' ) {
action = 'addClass';
} else {
action = 'removeClass';
}
this.$element.find( '.repeat-days-of-the-week .btn-group' )[ action ]( 'disabled' );
},
value: function value( options ) {
if ( options ) {
return this.setValue( options );
} else {
return this.getValue();
}
}
};
// SCHEDULER PLUGIN DEFINITION
$.fn.scheduler = function scheduler( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.scheduler' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.scheduler', ( data = new Scheduler( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.scheduler.defaults = {};
$.fn.scheduler.Constructor = Scheduler;
$.fn.scheduler.noConflict = function noConflict() {
$.fn.scheduler = old;
return this;
};
// DATA-API
$( document ).on( 'mousedown.fu.scheduler.data-api', '[data-initialize=scheduler]', function( e ) {
var $control = $( e.target ).closest( '.scheduler' );
if ( !$control.data( 'fu.scheduler' ) ) {
$control.scheduler( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=scheduler]' ).each( function() {
var $this = $( this );
if ( $this.data( 'scheduler' ) ) return;
$this.scheduler( $this.data() );
} );
} );
} )( jQuery );
( function( $ ) {
/*
* Fuel UX Picker
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2014 ExactTarget
* Licensed under the BSD New license.
*/
// -- BEGIN MODULE CODE HERE --
var old = $.fn.picker;
// PLACARD CONSTRUCTOR AND PROTOTYPE
var Picker = function Picker( element, options ) {
var self = this;
this.$element = $( element );
this.options = $.extend( {}, $.fn.picker.defaults, options );
this.$accept = this.$element.find( '.picker-accept' );
this.$cancel = this.$element.find( '.picker-cancel' );
this.$trigger = this.$element.find( '.picker-trigger' );
this.$footer = this.$element.find( '.picker-footer' );
this.$header = this.$element.find( '.picker-header' );
this.$popup = this.$element.find( '.picker-popup' );
this.$body = this.$element.find( '.picker-body' );
this.clickStamp = '_';
this.isInput = this.$trigger.is( 'input' );
this.$trigger.on( 'keydown.fu.picker', $.proxy( this.keyComplete, this ) );
this.$trigger.on( 'focus.fu.picker', $.proxy( function inputFocus( e ) {
if ( typeof e === "undefined" || $( e.target ).is( 'input[type=text]' ) ) {
$.proxy( this.show(), this );
}
}, this ) );
this.$trigger.on( 'click.fu.picker', $.proxy( function triggerClick( e ) {
if ( !$( e.target ).is( 'input[type=text]' ) ) {
$.proxy( this.toggle(), this );
} else {
$.proxy( this.show(), this );
}
}, this ) );
this.$accept.on( 'click.fu.picker', $.proxy( this.complete, this, 'accepted' ) );
this.$cancel.on( 'click.fu.picker', function( e ) {
e.preventDefault();
self.complete( 'cancelled' );
} );
};
var _isOffscreen = function _isOffscreen( picker ) {
var windowHeight = Math.max( document.documentElement.clientHeight, window.innerHeight || 0 );
var scrollTop = $( document ).scrollTop();
var popupTop = picker.$popup.offset();
var popupBottom = popupTop.top + picker.$popup.outerHeight( true );
//if the bottom of the popup goes off the page, but the top does not, dropup.
if ( popupBottom > windowHeight + scrollTop || popupTop.top < scrollTop ) {
return true;
} else { //otherwise, prefer showing the top of the popup only vs the bottom
return false;
}
};
var _display = function _display( picker ) {
picker.$popup.css( 'visibility', 'hidden' );
_showBelow( picker );
//if part of the popup is offscreen try to show it above
if ( _isOffscreen( picker ) ) {
_showAbove( picker );
//if part of the popup is still offscreen, prefer cutting off the bottom
if ( _isOffscreen( picker ) ) {
_showBelow( picker );
}
}
picker.$popup.css( 'visibility', 'visible' );
};
var _showAbove = function _showAbove( picker ) {
picker.$popup.css( 'top', -picker.$popup.outerHeight( true ) + 'px' );
};
var _showBelow = function _showBelow( picker ) {
picker.$popup.css( 'top', picker.$trigger.outerHeight( true ) + 'px' );
};
Picker.prototype = {
constructor: Picker,
complete: function complete( action ) {
var EVENT_CALLBACK_MAP = {
'accepted': 'onAccept',
'cancelled': 'onCancel',
'exited': 'onExit'
};
var func = this.options[ EVENT_CALLBACK_MAP[ action ] ];
var obj = {
contents: this.$body
};
if ( func ) {
func( obj );
this.$element.trigger( action + '.fu.picker', obj );
} else {
this.$element.trigger( action + '.fu.picker', obj );
this.hide();
}
},
keyComplete: function keyComplete( e ) {
if ( this.isInput && e.keyCode === 13 ) {
this.complete( 'accepted' );
this.$trigger.blur();
} else if ( e.keyCode === 27 ) {
this.complete( 'exited' );
this.$trigger.blur();
}
},
destroy: function destroy() {
this.$element.remove();
// remove any external bindings
$( document ).off( 'click.fu.picker.externalClick.' + this.clickStamp );
// empty elements to return to original markup
// [none]
// return string of markup
return this.$element[ 0 ].outerHTML;
},
disable: function disable() {
this.$element.addClass( 'disabled' );
this.$trigger.attr( 'disabled', 'disabled' );
},
enable: function enable() {
this.$element.removeClass( 'disabled' );
this.$trigger.removeAttr( 'disabled' );
},
toggle: function toggle() {
if ( this.$element.hasClass( 'showing' ) ) {
this.hide();
} else {
this.show();
}
},
hide: function hide() {
if ( !this.$element.hasClass( 'showing' ) ) {
return;
}
this.$element.removeClass( 'showing' );
$( document ).off( 'click.fu.picker.externalClick.' + this.clickStamp );
this.$element.trigger( 'hidden.fu.picker' );
},
externalClickListener: function externalClickListener( e, force ) {
if ( force === true || this.isExternalClick( e ) ) {
this.complete( 'exited' );
}
},
isExternalClick: function isExternalClick( e ) {
var el = this.$element.get( 0 );
var exceptions = this.options.externalClickExceptions || [];
var $originEl = $( e.target );
var i, l;
if ( e.target === el || $originEl.parents( '.picker:first' ).get( 0 ) === el ) {
return false;
} else {
for ( i = 0, l = exceptions.length; i < l; i++ ) {
if ( $originEl.is( exceptions[ i ] ) || $originEl.parents( exceptions[ i ] ).length > 0 ) {
return false;
}
}
}
return true;
},
show: function show() {
var other;
other = $( document ).find( '.picker.showing' );
if ( other.length > 0 ) {
if ( other.data( 'fu.picker' ) && other.data( 'fu.picker' ).options.explicit ) {
return;
}
other.picker( 'externalClickListener', {}, true );
}
this.$element.addClass( 'showing' );
_display( this );
this.$element.trigger( 'shown.fu.picker' );
this.clickStamp = new Date().getTime() + ( Math.floor( Math.random() * 100 ) + 1 );
if ( !this.options.explicit ) {
$( document ).on( 'click.fu.picker.externalClick.' + this.clickStamp, $.proxy( this.externalClickListener, this ) );
}
}
};
// PLACARD PLUGIN DEFINITION
$.fn.picker = function picker( option ) {
var args = Array.prototype.slice.call( arguments, 1 );
var methodReturn;
var $set = this.each( function() {
var $this = $( this );
var data = $this.data( 'fu.picker' );
var options = typeof option === 'object' && option;
if ( !data ) {
$this.data( 'fu.picker', ( data = new Picker( this, options ) ) );
}
if ( typeof option === 'string' ) {
methodReturn = data[ option ].apply( data, args );
}
} );
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.picker.defaults = {
onAccept: undefined,
onCancel: undefined,
onExit: undefined,
externalClickExceptions: [],
explicit: false
};
$.fn.picker.Constructor = Picker;
$.fn.picker.noConflict = function noConflict() {
$.fn.picker = old;
return this;
};
// DATA-API
$( document ).on( 'focus.fu.picker.data-api', '[data-initialize=picker]', function( e ) {
var $control = $( e.target ).closest( '.picker' );
if ( !$control.data( 'fu.picker' ) ) {
$control.picker( $control.data() );
}
} );
// Must be domReady for AMD compatibility
$( function() {
$( '[data-initialize=picker]' ).each( function() {
var $this = $( this );
if ( $this.data( 'fu.picker' ) ) return;
$this.picker( $this.data() );
} );
} );
} )( jQuery );
} ) );
|
var gulp = require('gulp'),
gulpWatch = require('gulp-watch'),
del = require('del'),
runSequence = require('run-sequence'),
argv = process.argv;
/**
* Ionic hooks
* Add ':before' or ':after' to any Ionic project command name to run the specified
* tasks before or after the command.
*/
gulp.task('serve:before', ['watch']);
gulp.task('emulate:before', ['build']);
gulp.task('deploy:before', ['build']);
gulp.task('build:before', ['build']);
// we want to 'watch' when livereloading
var shouldWatch = argv.indexOf('-l') > -1 || argv.indexOf('--livereload') > -1;
gulp.task('run:before', [shouldWatch ? 'watch' : 'build']);
/**
* Ionic Gulp tasks, for more information on each see
* https://github.com/driftyco/ionic-gulp-tasks
*
* Using these will allow you to stay up to date if the default Ionic 2 build
* changes, but you are of course welcome (and encouraged) to customize your
* build however you see fit.
*/
var buildBrowserify = require('ionic-gulp-browserify-typescript');
var buildSass = require('ionic-gulp-sass-build');
var copyHTML = require('ionic-gulp-html-copy');
var copyFonts = require('ionic-gulp-fonts-copy');
var copyScripts = require('ionic-gulp-scripts-copy');
var isRelease = argv.indexOf('--release') > -1;
gulp.task('watch', ['clean'], function(done){
runSequence(
['sass', 'html', 'fonts', 'scripts'],
function(){
gulpWatch('app/**/*.scss', function(){ gulp.start('sass'); });
gulpWatch('app/**/*.html', function(){ gulp.start('html'); });
buildBrowserify({ watch: true }).on('end', done);
}
);
});
gulp.task('build', ['clean'], function(done){
runSequence(
['sass', 'html', 'fonts', 'scripts'],
function(){
buildBrowserify({
minify: isRelease,
browserifyOptions: {
debug: !isRelease
},
uglifyOptions: {
mangle: false
}
}).on('end', done);
}
);
});
gulp.task('sass', buildSass);
gulp.task('html', copyHTML);
gulp.task('fonts', copyFonts);
gulp.task('scripts', copyScripts);
gulp.task('clean', function(){
return del('www/build');
});
|
/*!
* inferno-create-class v1.0.0-beta2
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoCreateClass = factory());
}(this, (function () { 'use strict';
var Lifecycle = function Lifecycle() {
this._listeners = [];
};
Lifecycle.prototype.addListener = function addListener (callback) {
this._listeners.push(callback);
};
Lifecycle.prototype.trigger = function trigger () {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
};
var NO_OP = '$NO_OP';
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndef(obj) {
return isUndefined(obj) || isNull(obj);
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
var ChildrenTypes = {
NON_KEYED: 1,
KEYED: 2,
NODE: 3,
TEXT: 4,
UNKNOWN: 5
};
var NodeTypes = {
ELEMENT: 1,
OPT_ELEMENT: 2,
TEXT: 3,
FRAGMENT: 4,
OPT_BLUEPRINT: 5,
COMPONENT: 6,
PLACEHOLDER: 7
};
function createVFragment(children, childrenType) {
return {
children: children,
childrenType: childrenType || ChildrenTypes.UNKNOWN,
dom: null,
pointer: null,
type: NodeTypes.FRAGMENT
};
}
function createVPlaceholder() {
return {
dom: null,
type: NodeTypes.PLACEHOLDER
};
}
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
var componentCallbackQueue = new Map();
function addToQueue(component, force, callback) {
// TODO this function needs to be revised and improved on
var queue = componentCallbackQueue.get(component);
if (!queue) {
queue = [];
componentCallbackQueue.set(component, queue);
requestAnimationFrame(function () {
applyState(component, force, function () {
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
});
componentCallbackQueue.delete(component);
component._processingSetState = false;
});
}
if (callback) {
queue.push(callback);
}
}
function queueStateChanges(component, newState, callback) {
if (isFunction(newState)) {
newState = newState(component.state);
}
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
if (component._processingSetState || callback) {
addToQueue(component, false, callback);
}
else {
component._processingSetState = true;
applyState(component, false, callback);
component._processingSetState = false;
}
}
else {
component.state = Object.assign({}, component.state, component._pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if ((!component._deferSetState || force) && !component._blockRender) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var prevState = component.state;
var nextState = Object.assign({}, prevState, pendingState);
var props = component.props;
var context = component.context;
component._pendingState = {};
var nextInput = component._updateComponent(prevState, nextState, props, props, context, force);
if (nextInput === NO_OP) {
nextInput = component._lastInput;
}
else if (isArray(nextInput)) {
nextInput = createVFragment(nextInput, null);
}
else if (isNullOrUndef(nextInput)) {
nextInput = createVPlaceholder();
}
var lastInput = component._lastInput;
var parentDom = lastInput.dom.parentNode;
var subLifecycle = new Lifecycle();
var childContext = component.getChildContext();
if (!isNullOrUndef(childContext)) {
childContext = Object.assign({}, context, component._childContext, childContext);
}
else {
childContext = Object.assign({}, context, component._childContext);
}
component._lastInput = nextInput;
component._patch(lastInput, nextInput, parentDom, subLifecycle, childContext, component._isSVG, false);
component._vComponent.dom = nextInput.dom;
component._componentToDOMNodeMap.set(component, nextInput.dom);
component.componentDidUpdate(props, prevState);
subLifecycle.trigger();
if (!isNullOrUndef(callback)) {
callback();
}
}
}
var Component = function Component(props, context) {
this.state = {};
this.refs = {};
this._processingSetState = false;
this._blockRender = false;
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._lastInput = null;
this._vComponent = null;
this._unmounted = true;
this._childContext = null;
this._patch = null;
this._isSVG = false;
this._componentToDOMNodeMap = null;
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.context = context || {};
if (!this.componentDidMount) {
this.componentDidMount = null;
}
};
Component.prototype.render = function render (nextProps, nextContext) {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
}
else {
{
throwError('cannot update state via setState() in componentWillUpdate().');
}
throwError();
}
};
Component.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState, prevContext) {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps, nextState, context) {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps, context) {
};
Component.prototype.componentWillUpdate = function componentWillUpdate (nextProps, nextState, nextContext) {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force) {
if (this._unmounted === true) {
throw new Error('You can\'t update an unmounted component!');
}
if (!isNullOrUndef(nextProps) && isNullOrUndef(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockRender = true;
this.componentWillReceiveProps(nextProps, context);
this._blockRender = false;
if (this._pendingSetState) {
nextState = Object.assign({}, nextState, this._pendingState);
this._pendingSetState = false;
this._pendingState = {};
}
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState, context);
if (shouldUpdate !== false || force) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState, context);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
this.context = context;
return this.render(nextProps, context);
}
}
return NO_OP;
};
// don't autobind these methods since they already have guaranteed context.
var AUTOBIND_BLACKLIST = {
constructor: 1,
render: 1,
shouldComponentUpdate: 1,
componentWillRecieveProps: 1,
componentWillUpdate: 1,
componentDidUpdate: 1,
componentWillMount: 1,
componentDidMount: 1,
componentWillUnmount: 1,
componentDidUnmount: 1
};
function F() {
}
function extend(base, props, all) {
for (var key in props) {
if (all === true || !isNullOrUndef(props[key])) {
base[key] = props[key];
}
}
return base;
}
function bindAll(ctx) {
for (var i in ctx) {
var v = ctx[i];
if (typeof v === 'function' && !v.__bound && !AUTOBIND_BLACKLIST.hasOwnProperty(i)) {
(ctx[i] = v.bind(ctx)).__bound = true;
}
}
}
function createClass$1(obj) {
function Cl(props) {
extend(this, obj);
Component.call(this, props);
bindAll(this);
if (this.getInitialState) {
this.state = this.getInitialState();
}
}
F.prototype = Component.prototype;
Cl.prototype = new F();
Cl.prototype.constructor = Cl;
if (obj.getDefaultProps) {
Cl.defaultProps = obj.getDefaultProps();
}
Cl.displayName = obj.displayName || 'Component';
return Cl;
}
return createClass$1;
})));
|
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-art.production.min.js');
} else {
module.exports = require('./cjs/react-art.development.js');
}
|
var d3_selectionRoot = d3_selection([[document]]);
d3_selectionRoot[0].parentNode = d3_selectRoot;
// TODO fast singleton implementation!
// TODO select(function)
d3.select = function(selector) {
return typeof selector === "string"
? d3_selectionRoot.select(selector)
: d3_selection([[selector]]); // assume node
};
// TODO selectAll(function)
d3.selectAll = function(selector) {
return typeof selector === "string"
? d3_selectionRoot.selectAll(selector)
: d3_selection([d3_array(selector)]); // assume node[]
};
|
//! moment.js locale configuration
//! locale : Montenegrin [me]
//! author : Miodrag Nikač <miodrag@restartit.me> : https://github.com/miodragnikac
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
//! moment.js locale configuration
var translator = {
words: {
//Different grammatical cases
ss: ['sekund', 'sekunda', 'sekundi'],
m: ['jedan minut', 'jednog minuta'],
mm: ['minut', 'minuta', 'minuta'],
h: ['jedan sat', 'jednog sata'],
hh: ['sat', 'sata', 'sati'],
dd: ['dan', 'dana', 'dana'],
MM: ['mjesec', 'mjeseca', 'mjeseci'],
yy: ['godina', 'godine', 'godina'],
},
correctGrammaticalCase: function (number, wordKey) {
return number === 1
? wordKey[0]
: number >= 2 && number <= 4
? wordKey[1]
: wordKey[2];
},
translate: function (number, withoutSuffix, key) {
var wordKey = translator.words[key];
if (key.length === 1) {
return withoutSuffix ? wordKey[0] : wordKey[1];
} else {
return (
number +
' ' +
translator.correctGrammaticalCase(number, wordKey)
);
}
},
};
var me = moment.defineLocale('me', {
months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split(
'_'
),
monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split(
'_'
),
monthsParseExact: true,
weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split(
'_'
),
weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'H:mm',
LTS: 'H:mm:ss',
L: 'DD.MM.YYYY',
LL: 'D. MMMM YYYY',
LLL: 'D. MMMM YYYY H:mm',
LLLL: 'dddd, D. MMMM YYYY H:mm',
},
calendar: {
sameDay: '[danas u] LT',
nextDay: '[sjutra u] LT',
nextWeek: function () {
switch (this.day()) {
case 0:
return '[u] [nedjelju] [u] LT';
case 3:
return '[u] [srijedu] [u] LT';
case 6:
return '[u] [subotu] [u] LT';
case 1:
case 2:
case 4:
case 5:
return '[u] dddd [u] LT';
}
},
lastDay: '[juče u] LT',
lastWeek: function () {
var lastWeekDays = [
'[prošle] [nedjelje] [u] LT',
'[prošlog] [ponedjeljka] [u] LT',
'[prošlog] [utorka] [u] LT',
'[prošle] [srijede] [u] LT',
'[prošlog] [četvrtka] [u] LT',
'[prošlog] [petka] [u] LT',
'[prošle] [subote] [u] LT',
];
return lastWeekDays[this.day()];
},
sameElse: 'L',
},
relativeTime: {
future: 'za %s',
past: 'prije %s',
s: 'nekoliko sekundi',
ss: translator.translate,
m: translator.translate,
mm: translator.translate,
h: translator.translate,
hh: translator.translate,
d: 'dan',
dd: translator.translate,
M: 'mjesec',
MM: translator.translate,
y: 'godinu',
yy: translator.translate,
},
dayOfMonthOrdinalParse: /\d{1,2}\./,
ordinal: '%d.',
week: {
dow: 1, // Monday is the first day of the week.
doy: 7, // The week that contains Jan 7th is the first week of the year.
},
});
return me;
})));
|
import {atan, cos, sin} from "../math";
import {azimuthalInvert} from "./azimuthal";
import projection from "./index";
export function gnomonicRaw(x, y) {
var cy = cos(y), k = cos(x) * cy;
return [cy * sin(x) / k, sin(y) / k];
}
gnomonicRaw.invert = azimuthalInvert(atan);
export default function() {
return projection(gnomonicRaw)
.scale(144.049)
.clipAngle(60);
}
|
/**
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*
* Grid-light theme for Highcharts JS
* @author Torstein Honsi
*/
'use strict';
import Highcharts from '../parts/Globals.js';
/* global document */
// Load the fonts
Highcharts.createElement('link', {
href: 'https://fonts.googleapis.com/css?family=Dosis:400,600',
rel: 'stylesheet',
type: 'text/css'
}, null, document.getElementsByTagName('head')[0]);
Highcharts.theme = {
colors: ['#7cb5ec', '#f7a35c', '#90ee7e', '#7798BF', '#aaeeee', '#ff0066',
'#eeaaee', '#55BF3B', '#DF5353', '#7798BF', '#aaeeee'],
chart: {
backgroundColor: null,
style: {
fontFamily: 'Dosis, sans-serif'
}
},
title: {
style: {
fontSize: '16px',
fontWeight: 'bold',
textTransform: 'uppercase'
}
},
tooltip: {
borderWidth: 0,
backgroundColor: 'rgba(219,219,216,0.8)',
shadow: false
},
legend: {
itemStyle: {
fontWeight: 'bold',
fontSize: '13px'
}
},
xAxis: {
gridLineWidth: 1,
labels: {
style: {
fontSize: '12px'
}
}
},
yAxis: {
minorTickInterval: 'auto',
title: {
style: {
textTransform: 'uppercase'
}
},
labels: {
style: {
fontSize: '12px'
}
}
},
plotOptions: {
candlestick: {
lineColor: '#404048'
}
},
// General
background2: '#F0F0EA'
};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);
|
/*! UIkit 2.19.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(t){"use strict";function o(o,i){i=t.$.extend({duration:1e3,transition:"easeOutExpo",offset:0,complete:function(){}},i);var n=o.offset().top-i.offset,s=t.$doc.height(),e=window.innerHeight;n+e>s&&(n=s-e),t.$("html,body").stop().animate({scrollTop:n},i.duration,i.transition).promise().done(i.complete)}t.component("smoothScroll",{boot:function(){t.$html.on("click.smooth-scroll.uikit","[data-uk-smooth-scroll]",function(){var o=t.$(this);if(!o.data("smoothScroll")){{t.smoothScroll(o,t.Utils.options(o.attr("data-uk-smooth-scroll")))}o.trigger("click")}return!1})},init:function(){var i=this;this.on("click",function(n){n.preventDefault(),o(t.$(this.hash).length?t.$(this.hash):t.$("body"),i.options)})}}),t.Utils.scrollToElement=o,t.$.easing.easeOutExpo||(t.$.easing.easeOutExpo=function(t,o,i,n,s){return o==s?i+n:n*(-Math.pow(2,-10*o/s)+1)+i})}(UIkit);
|
'use strict';
var clc = require('../');
var text = '.........\n' + '. Hello .\n' + '.........\n';
var style = { ".": clc.yellowBright("X") };
process.stdout.write(clc.art(text, style));
|
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// The module to be exported.
var fail = module.exports = {};
// Error codes.
fail.code = {
FATAL_ERROR: 1,
MISSING_GRUNTFILE: 2,
TASK_FAILURE: 3,
TEMPLATE_ERROR: 4,
INVALID_AUTOCOMPLETE: 5,
WARNING: 6,
};
// DRY it up!
function writeln(e, mode) {
grunt.log.muted = false;
var msg = String(e.message || e);
if (!grunt.option('no-color')) { msg += '\x07'; } // Beep!
if (mode === 'warn') {
msg = 'Warning: ' + msg + ' ';
msg += (grunt.option('force') ? 'Used --force, continuing.'.underline : 'Use --force to continue.');
msg = msg.yellow;
} else {
msg = ('Fatal error: ' + msg).red;
}
grunt.log.writeln(msg);
}
// If --stack is enabled, log the appropriate error stack (if it exists).
function dumpStack(e) {
if (grunt.option('stack')) {
if (e.origError && e.origError.stack) {
console.log(e.origError.stack);
} else if (e.stack) {
console.log(e.stack);
}
}
}
// A fatal error occurred. Abort immediately.
fail.fatal = function(e, errcode) {
writeln(e, 'fatal');
dumpStack(e);
grunt.util.exit(typeof errcode === 'number' ? errcode : fail.code.FATAL_ERROR);
};
// Keep track of error and warning counts.
fail.errorcount = 0;
fail.warncount = 0;
// A warning occurred. Abort immediately unless -f or --force was used.
fail.warn = function(e, errcode) {
var message = typeof e === 'string' ? e : e.message;
fail.warncount++;
writeln(message, 'warn');
// If -f or --force aren't used, stop script processing.
if (!grunt.option('force')) {
dumpStack(e);
grunt.log.writeln().fail('Aborted due to warnings.');
grunt.util.exit(typeof errcode === 'number' ? errcode : fail.code.WARNING);
}
};
// This gets called at the very end.
fail.report = function() {
if (fail.warncount > 0) {
grunt.log.writeln().fail('Done, but with warnings.');
} else {
grunt.log.writeln().success('Done, without errors.');
}
};
|
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
/**
* Intercept mutating methods and emit events
*/
;[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator () {
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
let i = arguments.length
const args = new Array(i)
while (i--) {
args[i] = arguments[i]
}
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
inserted = args
break
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
|
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var DateTimeFormatting = Windows.Globalization.DateTimeFormatting;
var DateTimeFormatter = DateTimeFormatting.DateTimeFormatter;
var page = WinJS.UI.Pages.define("/html/scenario3-parameterizedTemplate.html", {
ready: function (element, options) {
document.getElementById("displayButton").addEventListener("click", doDisplay, false);
}
});
function doDisplay() {
// This scenario uses the DateTimeFormatter class
// to format a date/time by specifying a template via parameters. Note that the current language
// and region value will determine the pattern of the date returned based on the
// specified parts.
SdkSample.clearFormattingResults();
SdkSample.appendCurrentLanguage();
// Obtain the date that will be formatted.
var dateToFormat = new Date();
SdkSample.appendFormattingResults("Dates:", [
new DateTimeFormatter(
DateTimeFormatting.YearFormat.full,
DateTimeFormatting.MonthFormat.abbreviated,
DateTimeFormatting.DayFormat.default,
DateTimeFormatting.DayOfWeekFormat.abbreviated),
new DateTimeFormatter(
DateTimeFormatting.YearFormat.abbreviated,
DateTimeFormatting.MonthFormat.abbreviated,
DateTimeFormatting.DayFormat.default,
DateTimeFormatting.DayOfWeekFormat.none),
new DateTimeFormatter(
DateTimeFormatting.YearFormat.full,
DateTimeFormatting.MonthFormat.full,
DateTimeFormatting.DayFormat.none,
DateTimeFormatting.DayOfWeekFormat.none),
new DateTimeFormatter(
DateTimeFormatting.YearFormat.none,
DateTimeFormatting.MonthFormat.full,
DateTimeFormatting.DayFormat.default,
DateTimeFormatting.DayOfWeekFormat.none)
], function (formatter) {
// Perform the actual formatting.
return formatter.template + ": " + formatter.format(dateToFormat);
});
SdkSample.appendFormattingResults("Times:", [
new DateTimeFormatter(
DateTimeFormatting.HourFormat.default,
DateTimeFormatting.MinuteFormat.default,
DateTimeFormatting.SecondFormat.default),
new DateTimeFormatter(
DateTimeFormatting.HourFormat.default,
DateTimeFormatting.MinuteFormat.default,
DateTimeFormatting.SecondFormat.none),
new DateTimeFormatter(
DateTimeFormatting.HourFormat.default,
DateTimeFormatting.MinuteFormat.none,
DateTimeFormatting.SecondFormat.none)
], function (formatter) {
// Perform the actual formatting.
return formatter.template + ": " + formatter.format(dateToFormat);
});
}
})();
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.2.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var events_1 = require("./events");
var ColumnChangeEvent = (function () {
function ColumnChangeEvent(type) {
this.type = type;
}
ColumnChangeEvent.prototype.toString = function () {
var result = 'ColumnChangeEvent {type: ' + this.type;
if (this.column) {
result += ', column: ' + this.column.getColId();
}
if (this.columnGroup) {
result += ', columnGroup: ' + this.columnGroup.getColGroupDef() ? this.columnGroup.getColGroupDef().headerName : '(not defined]';
}
if (this.toIndex) {
result += ', toIndex: ' + this.toIndex;
}
if (this.visible) {
result += ', visible: ' + this.visible;
}
if (this.pinned) {
result += ', pinned: ' + this.pinned;
}
if (typeof this.finished == 'boolean') {
result += ', finished: ' + this.finished;
}
result += '}';
return result;
};
ColumnChangeEvent.prototype.withPinned = function (pinned) {
this.pinned = pinned;
return this;
};
ColumnChangeEvent.prototype.withVisible = function (visible) {
this.visible = visible;
return this;
};
ColumnChangeEvent.prototype.isVisible = function () {
return this.visible;
};
ColumnChangeEvent.prototype.getPinned = function () {
return this.pinned;
};
ColumnChangeEvent.prototype.withColumn = function (column) {
this.column = column;
return this;
};
ColumnChangeEvent.prototype.withColumns = function (columns) {
this.columns = columns;
return this;
};
ColumnChangeEvent.prototype.withFinished = function (finished) {
this.finished = finished;
return this;
};
ColumnChangeEvent.prototype.withColumnGroup = function (columnGroup) {
this.columnGroup = columnGroup;
return this;
};
ColumnChangeEvent.prototype.withToIndex = function (toIndex) {
this.toIndex = toIndex;
return this;
};
ColumnChangeEvent.prototype.getToIndex = function () {
return this.toIndex;
};
ColumnChangeEvent.prototype.getType = function () {
return this.type;
};
ColumnChangeEvent.prototype.getColumn = function () {
return this.column;
};
ColumnChangeEvent.prototype.getColumns = function () {
return this.columns;
};
ColumnChangeEvent.prototype.getColumnGroup = function () {
return this.columnGroup;
};
ColumnChangeEvent.prototype.isPinnedPanelVisibilityImpacted = function () {
return this.type === events_1.Events.EVENT_COLUMN_EVERYTHING_CHANGED ||
this.type === events_1.Events.EVENT_COLUMN_GROUP_OPENED ||
this.type === events_1.Events.EVENT_COLUMN_VISIBLE ||
this.type === events_1.Events.EVENT_PIVOT_VALUE_CHANGED ||
this.type === events_1.Events.EVENT_COLUMN_PINNED;
};
ColumnChangeEvent.prototype.isContainerWidthImpacted = function () {
return this.type === events_1.Events.EVENT_COLUMN_EVERYTHING_CHANGED ||
this.type === events_1.Events.EVENT_COLUMN_GROUP_OPENED ||
this.type === events_1.Events.EVENT_COLUMN_VISIBLE ||
this.type === events_1.Events.EVENT_COLUMN_RESIZED ||
this.type === events_1.Events.EVENT_COLUMN_PINNED ||
this.type === events_1.Events.EVENT_PIVOT_VALUE_CHANGED ||
this.type === events_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED;
};
ColumnChangeEvent.prototype.isIndividualColumnResized = function () {
return this.type === events_1.Events.EVENT_COLUMN_RESIZED && this.column !== undefined && this.column !== null;
};
ColumnChangeEvent.prototype.isFinished = function () {
return this.finished;
};
return ColumnChangeEvent;
})();
exports.ColumnChangeEvent = ColumnChangeEvent;
|
/*!
* QUnit 2.5.0
* https://qunitjs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2018-01-10T02:56Z
*/
(function (global$1) {
'use strict';
global$1 = global$1 && global$1.hasOwnProperty('default') ? global$1['default'] : global$1;
var window = global$1.window;
var self$1 = global$1.self;
var console = global$1.console;
var setTimeout = global$1.setTimeout;
var clearTimeout = global$1.clearTimeout;
var document = window && window.document;
var navigator = window && window.navigator;
var localSessionStorage = function () {
var x = "qunit-test-string";
try {
global$1.sessionStorage.setItem(x, x);
global$1.sessionStorage.removeItem(x);
return global$1.sessionStorage;
} catch (e) {
return undefined;
}
}();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
var toString = Object.prototype.toString;
var hasOwn = Object.prototype.hasOwnProperty;
var now = Date.now || function () {
return new Date().getTime();
};
var defined = {
document: window && window.document !== undefined,
setTimeout: setTimeout !== undefined
};
// Returns a new Array with the elements that are in a but not in b
function diff(a, b) {
var i,
j,
result = a.slice();
for (i = 0; i < result.length; i++) {
for (j = 0; j < b.length; j++) {
if (result[i] === b[j]) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
/**
* Determines whether an element exists in a given array or not.
*
* @method inArray
* @param {Any} elem
* @param {Array} array
* @return {Boolean}
*/
function inArray(elem, array) {
return array.indexOf(elem) !== -1;
}
/**
* Makes a clone of an object using only Array or Object as base,
* and copies over the own enumerable properties.
*
* @param {Object} obj
* @return {Object} New object with only the own properties (recursively).
*/
function objectValues(obj) {
var key,
val,
vals = is("array", obj) ? [] : {};
for (key in obj) {
if (hasOwn.call(obj, key)) {
val = obj[key];
vals[key] = val === Object(val) ? objectValues(val) : val;
}
}
return vals;
}
function extend(a, b, undefOnly) {
for (var prop in b) {
if (hasOwn.call(b, prop)) {
if (b[prop] === undefined) {
delete a[prop];
} else if (!(undefOnly && typeof a[prop] !== "undefined")) {
a[prop] = b[prop];
}
}
}
return a;
}
function objectType(obj) {
if (typeof obj === "undefined") {
return "undefined";
}
// Consider: typeof null === object
if (obj === null) {
return "null";
}
var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
type = match && match[1];
switch (type) {
case "Number":
if (isNaN(obj)) {
return "nan";
}
return "number";
case "String":
case "Boolean":
case "Array":
case "Set":
case "Map":
case "Date":
case "RegExp":
case "Function":
case "Symbol":
return type.toLowerCase();
default:
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
}
}
// Safe object type checking
function is(type, obj) {
return objectType(obj) === type;
}
// Based on Java's String.hashCode, a simple but not
// rigorously collision resistant hashing function
function generateHash(module, testName) {
var str = module + "\x1C" + testName;
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0;
}
// Convert the possibly negative integer hash code into an 8 character hex string, which isn't
// strictly necessary but increases user understanding that the id is a SHA-like hash
var hex = (0x100000000 + hash).toString(16);
if (hex.length < 8) {
hex = "0000000" + hex;
}
return hex.slice(-8);
}
// Test for equality any JavaScript type.
// Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
var equiv = (function () {
// Value pairs queued for comparison. Used for breadth-first processing order, recursion
// detection and avoiding repeated comparison (see below for details).
// Elements are { a: val, b: val }.
var pairs = [];
var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};
function useStrictEquality(a, b) {
// This only gets called if a and b are not strict equal, and is used to compare on
// the primitive values inside object wrappers. For example:
// `var i = 1;`
// `var j = new Number(1);`
// Neither a nor b can be null, as a !== b and they have the same type.
if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
a = a.valueOf();
}
if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
b = b.valueOf();
}
return a === b;
}
function compareConstructors(a, b) {
var protoA = getProto(a);
var protoB = getProto(b);
// Comparing constructors is more strict than using `instanceof`
if (a.constructor === b.constructor) {
return true;
}
// Ref #851
// If the obj prototype descends from a null constructor, treat it
// as a null prototype.
if (protoA && protoA.constructor === null) {
protoA = null;
}
if (protoB && protoB.constructor === null) {
protoB = null;
}
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
return true;
}
return false;
}
function getRegExpFlags(regexp) {
return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
}
function isContainer(val) {
return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
}
function breadthFirstCompareChild(a, b) {
// If a is a container not reference-equal to b, postpone the comparison to the
// end of the pairs queue -- unless (a, b) has been seen before, in which case skip
// over the pair.
if (a === b) {
return true;
}
if (!isContainer(a)) {
return typeEquiv(a, b);
}
if (pairs.every(function (pair) {
return pair.a !== a || pair.b !== b;
})) {
// Not yet started comparing this pair
pairs.push({ a: a, b: b });
}
return true;
}
var callbacks = {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"symbol": useStrictEquality,
"date": useStrictEquality,
"nan": function nan() {
return true;
},
"regexp": function regexp(a, b) {
return a.source === b.source &&
// Include flags in the comparison
getRegExpFlags(a) === getRegExpFlags(b);
},
// abort (identical references / instance methods were skipped earlier)
"function": function _function() {
return false;
},
"array": function array(a, b) {
var i, len;
len = a.length;
if (len !== b.length) {
// Safe and faster
return false;
}
for (i = 0; i < len; i++) {
// Compare non-containers; queue non-reference-equal containers
if (!breadthFirstCompareChild(a[i], b[i])) {
return false;
}
}
return true;
},
// Define sets a and b to be equivalent if for each element aVal in a, there
// is some element bVal in b such that aVal and bVal are equivalent. Element
// repetitions are not counted, so these are equivalent:
// a = new Set( [ {}, [], [] ] );
// b = new Set( [ {}, {}, [] ] );
"set": function set$$1(a, b) {
var innerEq,
outerEq = true;
if (a.size !== b.size) {
// This optimization has certain quirks because of the lack of
// repetition counting. For instance, adding the same
// (reference-identical) element to two equivalent sets can
// make them non-equivalent.
return false;
}
a.forEach(function (aVal) {
// Short-circuit if the result is already known. (Using for...of
// with a break clause would be cleaner here, but it would cause
// a syntax error on older Javascript implementations even if
// Set is unused)
if (!outerEq) {
return;
}
innerEq = false;
b.forEach(function (bVal) {
var parentPairs;
// Likewise, short-circuit if the result is already known
if (innerEq) {
return;
}
// Swap out the global pairs list, as the nested call to
// innerEquiv will clobber its contents
parentPairs = pairs;
if (innerEquiv(bVal, aVal)) {
innerEq = true;
}
// Replace the global pairs list
pairs = parentPairs;
});
if (!innerEq) {
outerEq = false;
}
});
return outerEq;
},
// Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
// in a, there is some key-value pair (bKey, bVal) in b such that
// [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
// counted, so these are equivalent:
// a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
// b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
"map": function map(a, b) {
var innerEq,
outerEq = true;
if (a.size !== b.size) {
// This optimization has certain quirks because of the lack of
// repetition counting. For instance, adding the same
// (reference-identical) key-value pair to two equivalent maps
// can make them non-equivalent.
return false;
}
a.forEach(function (aVal, aKey) {
// Short-circuit if the result is already known. (Using for...of
// with a break clause would be cleaner here, but it would cause
// a syntax error on older Javascript implementations even if
// Map is unused)
if (!outerEq) {
return;
}
innerEq = false;
b.forEach(function (bVal, bKey) {
var parentPairs;
// Likewise, short-circuit if the result is already known
if (innerEq) {
return;
}
// Swap out the global pairs list, as the nested call to
// innerEquiv will clobber its contents
parentPairs = pairs;
if (innerEquiv([bVal, bKey], [aVal, aKey])) {
innerEq = true;
}
// Replace the global pairs list
pairs = parentPairs;
});
if (!innerEq) {
outerEq = false;
}
});
return outerEq;
},
"object": function object(a, b) {
var i,
aProperties = [],
bProperties = [];
if (compareConstructors(a, b) === false) {
return false;
}
// Be strict: don't ensure hasOwnProperty and go deep
for (i in a) {
// Collect a's properties
aProperties.push(i);
// Skip OOP methods that look the same
if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
continue;
}
// Compare non-containers; queue non-reference-equal containers
if (!breadthFirstCompareChild(a[i], b[i])) {
return false;
}
}
for (i in b) {
// Collect b's properties
bProperties.push(i);
}
// Ensures identical properties name
return typeEquiv(aProperties.sort(), bProperties.sort());
}
};
function typeEquiv(a, b) {
var type = objectType(a);
// Callbacks for containers will append to the pairs queue to achieve breadth-first
// search order. The pairs queue is also used to avoid reprocessing any pair of
// containers that are reference-equal to a previously visited pair (a special case
// this being recursion detection).
//
// Because of this approach, once typeEquiv returns a false value, it should not be
// called again without clearing the pair queue else it may wrongly report a visited
// pair as being equivalent.
return objectType(b) === type && callbacks[type](a, b);
}
function innerEquiv(a, b) {
var i, pair;
// We're done when there's nothing more to compare
if (arguments.length < 2) {
return true;
}
// Clear the global pair queue and add the top-level values being compared
pairs = [{ a: a, b: b }];
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
// Perform type-specific comparison on any pairs that are not strictly
// equal. For container types, that comparison will postpone comparison
// of any sub-container pair to the end of the pair queue. This gives
// breadth-first search order. It also avoids the reprocessing of
// reference-equal siblings, cousins etc, which can have a significant speed
// impact when comparing a container of small objects each of which has a
// reference to the same (singleton) large object.
if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
return false;
}
}
// ...across all consecutive argument pairs
return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
}
return function () {
var result = innerEquiv.apply(undefined, arguments);
// Release any retained objects
pairs.length = 0;
return result;
};
})();
/**
* Config object: Maintain internal state
* Later exposed as QUnit.config
* `config` initialized at top of scope
*/
var config = {
// The queue of tests to run
queue: [],
// Block until document ready
blocking: true,
// By default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// By default, modify document.title when suite is done
altertitle: true,
// HTML Reporter: collapse every test except the first failing test
// If false, all failing tests will be expanded
collapse: true,
// By default, scroll to top of the page when suite is done
scrolltop: true,
// Depth up-to which object will be dumped
maxDepth: 5,
// When enabled, all tests must call expect()
requireExpects: false,
// Placeholder for user-configurable form-exposed URL parameters
urlConfig: [],
// Set of all modules.
modules: [],
// The first unnamed module
currentModule: {
name: "",
tests: [],
childModules: [],
testsRun: 0,
unskippedTestsRun: 0,
hooks: {
before: [],
beforeEach: [],
afterEach: [],
after: []
}
},
callbacks: {},
// The storage module to use for reordering tests
storage: localSessionStorage
};
// take a predefined QUnit.config and extend the defaults
var globalConfig = window && window.QUnit && window.QUnit.config;
// only extend the global config if there is no QUnit overload
if (window && window.QUnit && !window.QUnit.version) {
extend(config, globalConfig);
}
// Push a loose unnamed module to the modules collection
config.modules.push(config.currentModule);
// Based on jsDump by Ariel Flesler
// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
var dump = (function () {
function quote(str) {
return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
}
function literal(o) {
return o + "";
}
function join(pre, arr, post) {
var s = dump.separator(),
base = dump.indent(),
inner = dump.indent(1);
if (arr.join) {
arr = arr.join("," + s + inner);
}
if (!arr) {
return pre + post;
}
return [pre, inner + arr, base + post].join(s);
}
function array(arr, stack) {
var i = arr.length,
ret = new Array(i);
if (dump.maxDepth && dump.depth > dump.maxDepth) {
return "[object Array]";
}
this.up();
while (i--) {
ret[i] = this.parse(arr[i], undefined, stack);
}
this.down();
return join("[", ret, "]");
}
function isArray(obj) {
return (
//Native Arrays
toString.call(obj) === "[object Array]" ||
// NodeList objects
typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
);
}
var reName = /^function (\w+)/,
dump = {
// The objType is used mostly internally, you can fix a (custom) type in advance
parse: function parse(obj, objType, stack) {
stack = stack || [];
var res,
parser,
parserType,
objIndex = stack.indexOf(obj);
if (objIndex !== -1) {
return "recursion(" + (objIndex - stack.length) + ")";
}
objType = objType || this.typeOf(obj);
parser = this.parsers[objType];
parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
if (parserType === "function") {
stack.push(obj);
res = parser.call(this, obj, stack);
stack.pop();
return res;
}
return parserType === "string" ? parser : this.parsers.error;
},
typeOf: function typeOf(obj) {
var type;
if (obj === null) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (is("regexp", obj)) {
type = "regexp";
} else if (is("date", obj)) {
type = "date";
} else if (is("function", obj)) {
type = "function";
} else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (isArray(obj)) {
type = "array";
} else if (obj.constructor === Error.prototype.constructor) {
type = "error";
} else {
type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
}
return type;
},
separator: function separator() {
if (this.multiline) {
return this.HTML ? "<br />" : "\n";
} else {
return this.HTML ? " " : " ";
}
},
// Extra can be a number, shortcut for increasing-calling-decreasing
indent: function indent(extra) {
if (!this.multiline) {
return "";
}
var chr = this.indentChar;
if (this.HTML) {
chr = chr.replace(/\t/g, " ").replace(/ /g, " ");
}
return new Array(this.depth + (extra || 0)).join(chr);
},
up: function up(a) {
this.depth += a || 1;
},
down: function down(a) {
this.depth -= a || 1;
},
setParser: function setParser(name, parser) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote: quote,
literal: literal,
join: join,
depth: 1,
maxDepth: config.maxDepth,
// This is the list of parsers, to modify them, use dump.setParser
parsers: {
window: "[Window]",
document: "[Document]",
error: function error(_error) {
return "Error(\"" + _error.message + "\")";
},
unknown: "[Unknown]",
"null": "null",
"undefined": "undefined",
"function": function _function(fn) {
var ret = "function",
// Functions never have name in IE
name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
if (name) {
ret += " " + name;
}
ret += "(";
ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
return join(ret, dump.parse(fn, "functionCode"), "}");
},
array: array,
nodelist: array,
"arguments": array,
object: function object(map, stack) {
var keys,
key,
val,
i,
nonEnumerableProperties,
ret = [];
if (dump.maxDepth && dump.depth > dump.maxDepth) {
return "[object Object]";
}
dump.up();
keys = [];
for (key in map) {
keys.push(key);
}
// Some properties are not always enumerable on Error objects.
nonEnumerableProperties = ["message", "name"];
for (i in nonEnumerableProperties) {
key = nonEnumerableProperties[i];
if (key in map && !inArray(key, keys)) {
keys.push(key);
}
}
keys.sort();
for (i = 0; i < keys.length; i++) {
key = keys[i];
val = map[key];
ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
}
dump.down();
return join("{", ret, "}");
},
node: function node(_node) {
var len,
i,
val,
open = dump.HTML ? "<" : "<",
close = dump.HTML ? ">" : ">",
tag = _node.nodeName.toLowerCase(),
ret = open + tag,
attrs = _node.attributes;
if (attrs) {
for (i = 0, len = attrs.length; i < len; i++) {
val = attrs[i].nodeValue;
// IE6 includes all attributes in .attributes, even ones not explicitly
// set. Those have values like undefined, null, 0, false, "" or
// "inherit".
if (val && val !== "inherit") {
ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
}
}
}
ret += close;
// Show content of TextNode or CDATASection
if (_node.nodeType === 3 || _node.nodeType === 4) {
ret += _node.nodeValue;
}
return ret + open + "/" + tag + close;
},
// Function calls it internally, it's the arguments part of the function
functionArgs: function functionArgs(fn) {
var args,
l = fn.length;
if (!l) {
return "";
}
args = new Array(l);
while (l--) {
// 97 is 'a'
args[l] = String.fromCharCode(97 + l);
}
return " " + args.join(", ") + " ";
},
// Object calls it internally, the key part of an item in a map
key: quote,
// Function calls it internally, it's the content of the function
functionCode: "[code]",
// Node calls it internally, it's a html attribute value
attribute: quote,
string: quote,
date: quote,
regexp: literal,
number: literal,
"boolean": literal,
symbol: function symbol(sym) {
return sym.toString();
}
},
// If true, entities are escaped ( <, >, \t, space and \n )
HTML: false,
// Indentation unit
indentChar: " ",
// If true, items in a collection, are separated by a \n, else just a space.
multiline: true
};
return dump;
})();
var LISTENERS = Object.create(null);
var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
/**
* Emits an event with the specified data to all currently registered listeners.
* Callbacks will fire in the order in which they are registered (FIFO). This
* function is not exposed publicly; it is used by QUnit internals to emit
* logging events.
*
* @private
* @method emit
* @param {String} eventName
* @param {Object} data
* @return {Void}
*/
function emit(eventName, data) {
if (objectType(eventName) !== "string") {
throw new TypeError("eventName must be a string when emitting an event");
}
// Clone the callbacks in case one of them registers a new callback
var originalCallbacks = LISTENERS[eventName];
var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](data);
}
}
/**
* Registers a callback as a listener to the specified event.
*
* @public
* @method on
* @param {String} eventName
* @param {Function} callback
* @return {Void}
*/
function on(eventName, callback) {
if (objectType(eventName) !== "string") {
throw new TypeError("eventName must be a string when registering a listener");
} else if (!inArray(eventName, SUPPORTED_EVENTS)) {
var events = SUPPORTED_EVENTS.join(", ");
throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + ".");
} else if (objectType(callback) !== "function") {
throw new TypeError("callback must be a function when registering a listener");
}
if (!LISTENERS[eventName]) {
LISTENERS[eventName] = [];
}
// Don't register the same callback more than once
if (!inArray(callback, LISTENERS[eventName])) {
LISTENERS[eventName].push(callback);
}
}
// Register logging callbacks
function registerLoggingCallbacks(obj) {
var i,
l,
key,
callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
function registerLoggingCallback(key) {
var loggingCallback = function loggingCallback(callback) {
if (objectType(callback) !== "function") {
throw new Error("QUnit logging methods require a callback function as their first parameters.");
}
config.callbacks[key].push(callback);
};
return loggingCallback;
}
for (i = 0, l = callbackNames.length; i < l; i++) {
key = callbackNames[i];
// Initialize key collection of logging callback
if (objectType(config.callbacks[key]) === "undefined") {
config.callbacks[key] = [];
}
obj[key] = registerLoggingCallback(key);
}
}
function runLoggingCallbacks(key, args) {
var i, l, callbacks;
callbacks = config.callbacks[key];
for (i = 0, l = callbacks.length; i < l; i++) {
callbacks[i](args);
}
}
// Doesn't support IE9, it will return undefined on these browsers
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
function extractStacktrace(e, offset) {
offset = offset === undefined ? 4 : offset;
var stack, include, i;
if (e && e.stack) {
stack = e.stack.split("\n");
if (/^error$/i.test(stack[0])) {
stack.shift();
}
if (fileName) {
include = [];
for (i = offset; i < stack.length; i++) {
if (stack[i].indexOf(fileName) !== -1) {
break;
}
include.push(stack[i]);
}
if (include.length) {
return include.join("\n");
}
}
return stack[offset];
}
}
function sourceFromStacktrace(offset) {
var error = new Error();
// Support: Safari <=7 only, IE <=10 - 11 only
// Not all browsers generate the `stack` property for `new Error()`, see also #636
if (!error.stack) {
try {
throw error;
} catch (err) {
error = err;
}
}
return extractStacktrace(error, offset);
}
var priorityCount = 0;
var unitSampler = void 0;
/**
* Advances the ProcessingQueue to the next item if it is ready.
* @param {Boolean} last
*/
function advance() {
var start = now();
config.depth = (config.depth || 0) + 1;
while (config.queue.length && !config.blocking) {
var elapsedTime = now() - start;
if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) {
if (priorityCount > 0) {
priorityCount--;
}
config.queue.shift()();
} else {
setTimeout(advance);
break;
}
}
config.depth--;
if (!config.blocking && !config.queue.length && config.depth === 0) {
done();
}
}
function addToQueueImmediate(callback) {
if (objectType(callback) === "array") {
while (callback.length) {
addToQueueImmediate(callback.pop());
}
return;
}
config.queue.unshift(callback);
priorityCount++;
}
/**
* Adds a function to the ProcessingQueue for execution.
* @param {Function|Array} callback
* @param {Boolean} priority
* @param {String} seed
*/
function addToQueue(callback, prioritize, seed) {
if (prioritize) {
config.queue.splice(priorityCount++, 0, callback);
} else if (seed) {
if (!unitSampler) {
unitSampler = unitSamplerGenerator(seed);
}
// Insert into a random position after all prioritized items
var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
config.queue.splice(priorityCount + index, 0, callback);
} else {
config.queue.push(callback);
}
}
/**
* Creates a seeded "sample" generator which is used for randomizing tests.
*/
function unitSamplerGenerator(seed) {
// 32-bit xorshift, requires only a nonzero seed
// http://excamera.com/sphinx/article-xorshift.html
var sample = parseInt(generateHash(seed), 16) || -1;
return function () {
sample ^= sample << 13;
sample ^= sample >>> 17;
sample ^= sample << 5;
// ECMAScript has no unsigned number type
if (sample < 0) {
sample += 0x100000000;
}
return sample / 0x100000000;
};
}
/**
* This function is called when the ProcessingQueue is done processing all
* items. It handles emitting the final run events.
*/
function done() {
var storage = config.storage;
ProcessingQueue.finished = true;
var runtime = now() - config.started;
var passed = config.stats.all - config.stats.bad;
emit("runEnd", globalSuite.end(true));
runLoggingCallbacks("done", {
passed: passed,
failed: config.stats.bad,
total: config.stats.all,
runtime: runtime
});
// Clear own storage items if all tests passed
if (storage && config.stats.bad === 0) {
for (var i = storage.length - 1; i >= 0; i--) {
var key = storage.key(i);
if (key.indexOf("qunit-test-") === 0) {
storage.removeItem(key);
}
}
}
}
var ProcessingQueue = {
finished: false,
add: addToQueue,
addImmediate: addToQueueImmediate,
advance: advance
};
var TestReport = function () {
function TestReport(name, suite, options) {
classCallCheck(this, TestReport);
this.name = name;
this.suiteName = suite.name;
this.fullName = suite.fullName.concat(name);
this.runtime = 0;
this.assertions = [];
this.skipped = !!options.skip;
this.todo = !!options.todo;
this.valid = options.valid;
this._startTime = 0;
this._endTime = 0;
suite.pushTest(this);
}
createClass(TestReport, [{
key: "start",
value: function start(recordTime) {
if (recordTime) {
this._startTime = Date.now();
}
return {
name: this.name,
suiteName: this.suiteName,
fullName: this.fullName.slice()
};
}
}, {
key: "end",
value: function end(recordTime) {
if (recordTime) {
this._endTime = Date.now();
}
return extend(this.start(), {
runtime: this.getRuntime(),
status: this.getStatus(),
errors: this.getFailedAssertions(),
assertions: this.getAssertions()
});
}
}, {
key: "pushAssertion",
value: function pushAssertion(assertion) {
this.assertions.push(assertion);
}
}, {
key: "getRuntime",
value: function getRuntime() {
return this._endTime - this._startTime;
}
}, {
key: "getStatus",
value: function getStatus() {
if (this.skipped) {
return "skipped";
}
var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
if (!testPassed) {
return "failed";
} else if (this.todo) {
return "todo";
} else {
return "passed";
}
}
}, {
key: "getFailedAssertions",
value: function getFailedAssertions() {
return this.assertions.filter(function (assertion) {
return !assertion.passed;
});
}
}, {
key: "getAssertions",
value: function getAssertions() {
return this.assertions.slice();
}
// Remove actual and expected values from assertions. This is to prevent
// leaking memory throughout a test suite.
}, {
key: "slimAssertions",
value: function slimAssertions() {
this.assertions = this.assertions.map(function (assertion) {
delete assertion.actual;
delete assertion.expected;
return assertion;
});
}
}]);
return TestReport;
}();
var focused$1 = false;
function Test(settings) {
var i, l;
++Test.count;
this.expected = null;
this.assertions = [];
this.semaphore = 0;
this.module = config.currentModule;
this.stack = sourceFromStacktrace(3);
this.steps = [];
this.timeout = undefined;
// If a module is skipped, all its tests and the tests of the child suites
// should be treated as skipped even if they are defined as `only` or `todo`.
// As for `todo` module, all its tests will be treated as `todo` except for
// tests defined as `skip` which will be left intact.
//
// So, if a test is defined as `todo` and is inside a skipped module, we should
// then treat that test as if was defined as `skip`.
if (this.module.skip) {
settings.skip = true;
settings.todo = false;
// Skipped tests should be left intact
} else if (this.module.todo && !settings.skip) {
settings.todo = true;
}
extend(this, settings);
this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
todo: settings.todo,
skip: settings.skip,
valid: this.valid()
});
// Register unique strings
for (i = 0, l = this.module.tests; i < l.length; i++) {
if (this.module.tests[i].name === this.testName) {
this.testName += " ";
}
}
this.testId = generateHash(this.module.name, this.testName);
this.module.tests.push({
name: this.testName,
testId: this.testId,
skip: !!settings.skip
});
if (settings.skip) {
// Skipped tests will fully ignore any sent callback
this.callback = function () {};
this.async = false;
this.expected = 0;
} else {
if (typeof this.callback !== "function") {
var method = this.todo ? "todo" : "test";
// eslint-disable-next-line max-len
throw new TypeError("You must provide a function as a test callback to QUnit." + method + "(\"" + settings.testName + "\")");
}
this.assert = new Assert(this);
}
}
Test.count = 0;
function getNotStartedModules(startModule) {
var module = startModule,
modules = [];
while (module && module.testsRun === 0) {
modules.push(module);
module = module.parentModule;
}
return modules;
}
Test.prototype = {
before: function before() {
var i,
startModule,
module = this.module,
notStartedModules = getNotStartedModules(module);
for (i = notStartedModules.length - 1; i >= 0; i--) {
startModule = notStartedModules[i];
startModule.stats = { all: 0, bad: 0, started: now() };
emit("suiteStart", startModule.suiteReport.start(true));
runLoggingCallbacks("moduleStart", {
name: startModule.name,
tests: startModule.tests
});
}
config.current = this;
this.testEnvironment = extend({}, module.testEnvironment);
this.started = now();
emit("testStart", this.testReport.start(true));
runLoggingCallbacks("testStart", {
name: this.testName,
module: module.name,
testId: this.testId,
previousFailure: this.previousFailure
});
if (!config.pollution) {
saveGlobal();
}
},
run: function run() {
var promise;
config.current = this;
this.callbackStarted = now();
if (config.notrycatch) {
runTest(this);
return;
}
try {
runTest(this);
} catch (e) {
this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
// Else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if (config.blocking) {
internalRecover(this);
}
}
function runTest(test) {
promise = test.callback.call(test.testEnvironment, test.assert);
test.resolvePromise(promise);
// If the test has a "lock" on it, but the timeout is 0, then we push a
// failure as the test should be synchronous.
if (test.timeout === 0 && test.semaphore !== 0) {
pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2));
}
}
},
after: function after() {
checkPollution();
},
queueHook: function queueHook(hook, hookName, hookOwner) {
var _this = this;
var callHook = function callHook() {
var promise = hook.call(_this.testEnvironment, _this.assert);
_this.resolvePromise(promise, hookName);
};
var runHook = function runHook() {
if (hookName === "before") {
if (hookOwner.unskippedTestsRun !== 0) {
return;
}
_this.preserveEnvironment = true;
}
if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) {
return;
}
config.current = _this;
if (config.notrycatch) {
callHook();
return;
}
try {
callHook();
} catch (error) {
_this.pushFailure(hookName + " failed on " + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0));
}
};
return runHook;
},
// Currently only used for module level hooks, can be used to add global level ones
hooks: function hooks(handler) {
var hooks = [];
function processHooks(test, module) {
if (module.parentModule) {
processHooks(test, module.parentModule);
}
if (module.hooks[handler].length) {
for (var i = 0; i < module.hooks[handler].length; i++) {
hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
}
}
}
// Hooks are ignored on skipped tests
if (!this.skip) {
processHooks(this, this.module);
}
return hooks;
},
finish: function finish() {
config.current = this;
if (config.requireExpects && this.expected === null) {
this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
} else if (this.expected !== null && this.expected !== this.assertions.length) {
this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
} else if (this.expected === null && !this.assertions.length) {
this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
}
var i,
module = this.module,
moduleName = module.name,
testName = this.testName,
skipped = !!this.skip,
todo = !!this.todo,
bad = 0,
storage = config.storage;
this.runtime = now() - this.started;
config.stats.all += this.assertions.length;
module.stats.all += this.assertions.length;
for (i = 0; i < this.assertions.length; i++) {
if (!this.assertions[i].result) {
bad++;
config.stats.bad++;
module.stats.bad++;
}
}
notifyTestsRan(module, skipped);
// Store result when possible
if (storage) {
if (bad) {
storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
} else {
storage.removeItem("qunit-test-" + moduleName + "-" + testName);
}
}
// After emitting the js-reporters event we cleanup the assertion data to
// avoid leaking it. It is not used by the legacy testDone callbacks.
emit("testEnd", this.testReport.end(true));
this.testReport.slimAssertions();
runLoggingCallbacks("testDone", {
name: testName,
module: moduleName,
skipped: skipped,
todo: todo,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length,
runtime: skipped ? 0 : this.runtime,
// HTML Reporter use
assertions: this.assertions,
testId: this.testId,
// Source of Test
source: this.stack
});
if (module.testsRun === numberOfTests(module)) {
logSuiteEnd(module);
// Check if the parent modules, iteratively, are done. If that the case,
// we emit the `suiteEnd` event and trigger `moduleDone` callback.
var parent = module.parentModule;
while (parent && parent.testsRun === numberOfTests(parent)) {
logSuiteEnd(parent);
parent = parent.parentModule;
}
}
config.current = undefined;
function logSuiteEnd(module) {
emit("suiteEnd", module.suiteReport.end(true));
runLoggingCallbacks("moduleDone", {
name: module.name,
tests: module.tests,
failed: module.stats.bad,
passed: module.stats.all - module.stats.bad,
total: module.stats.all,
runtime: now() - module.stats.started
});
}
},
preserveTestEnvironment: function preserveTestEnvironment() {
if (this.preserveEnvironment) {
this.module.testEnvironment = this.testEnvironment;
this.testEnvironment = extend({}, this.module.testEnvironment);
}
},
queue: function queue() {
var test = this;
if (!this.valid()) {
return;
}
function runTest() {
// Each of these can by async
ProcessingQueue.addImmediate([function () {
test.before();
}, test.hooks("before"), function () {
test.preserveTestEnvironment();
}, test.hooks("beforeEach"), function () {
test.run();
}, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
test.after();
}, function () {
test.finish();
}]);
}
var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
// Prioritize previously failed tests, detected from storage
var prioritize = config.reorder && !!previousFailCount;
this.previousFailure = !!previousFailCount;
ProcessingQueue.add(runTest, prioritize, config.seed);
// If the queue has already finished, we manually process the new test
if (ProcessingQueue.finished) {
ProcessingQueue.advance();
}
},
pushResult: function pushResult(resultInfo) {
if (this !== config.current) {
throw new Error("Assertion occurred after test had finished.");
}
// Destructure of resultInfo = { result, actual, expected, message, negative }
var source,
details = {
module: this.module.name,
name: this.testName,
result: resultInfo.result,
message: resultInfo.message,
actual: resultInfo.actual,
testId: this.testId,
negative: resultInfo.negative || false,
runtime: now() - this.started,
todo: !!this.todo
};
if (hasOwn.call(resultInfo, "expected")) {
details.expected = resultInfo.expected;
}
if (!resultInfo.result) {
source = resultInfo.source || sourceFromStacktrace();
if (source) {
details.source = source;
}
}
this.logAssertion(details);
this.assertions.push({
result: !!resultInfo.result,
message: resultInfo.message
});
},
pushFailure: function pushFailure(message, source, actual) {
if (!(this instanceof Test)) {
throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
}
this.pushResult({
result: false,
message: message || "error",
actual: actual || null,
source: source
});
},
/**
* Log assertion details using both the old QUnit.log interface and
* QUnit.on( "assertion" ) interface.
*
* @private
*/
logAssertion: function logAssertion(details) {
runLoggingCallbacks("log", details);
var assertion = {
passed: details.result,
actual: details.actual,
expected: details.expected,
message: details.message,
stack: details.source,
todo: details.todo
};
this.testReport.pushAssertion(assertion);
emit("assertion", assertion);
},
resolvePromise: function resolvePromise(promise, phase) {
var then,
resume,
message,
test = this;
if (promise != null) {
then = promise.then;
if (objectType(then) === "function") {
resume = internalStop(test);
if (config.notrycatch) {
then.call(promise, function () {
resume();
});
} else {
then.call(promise, function () {
resume();
}, function (error) {
message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
test.pushFailure(message, extractStacktrace(error, 0));
// Else next test will carry the responsibility
saveGlobal();
// Unblock
resume();
});
}
}
}
},
valid: function valid() {
var filter = config.filter,
regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
module = config.module && config.module.toLowerCase(),
fullName = this.module.name + ": " + this.testName;
function moduleChainNameMatch(testModule) {
var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
if (testModuleName === module) {
return true;
} else if (testModule.parentModule) {
return moduleChainNameMatch(testModule.parentModule);
} else {
return false;
}
}
function moduleChainIdMatch(testModule) {
return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
}
// Internally-generated tests are always valid
if (this.callback && this.callback.validTest) {
return true;
}
if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
return false;
}
if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
return false;
}
if (module && !moduleChainNameMatch(this.module)) {
return false;
}
if (!filter) {
return true;
}
return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
},
regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
var regex = new RegExp(pattern, flags);
var match = regex.test(fullName);
return match !== exclude;
},
stringFilter: function stringFilter(filter, fullName) {
filter = filter.toLowerCase();
fullName = fullName.toLowerCase();
var include = filter.charAt(0) !== "!";
if (!include) {
filter = filter.slice(1);
}
// If the filter matches, we need to honour include
if (fullName.indexOf(filter) !== -1) {
return include;
}
// Otherwise, do the opposite
return !include;
}
};
function pushFailure() {
if (!config.current) {
throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
}
// Gets current test obj
var currentTest = config.current;
return currentTest.pushFailure.apply(currentTest, arguments);
}
function saveGlobal() {
config.pollution = [];
if (config.noglobals) {
for (var key in global$1) {
if (hasOwn.call(global$1, key)) {
// In Opera sometimes DOM element ids show up here, ignore them
if (/^qunit-test-output/.test(key)) {
continue;
}
config.pollution.push(key);
}
}
}
}
function checkPollution() {
var newGlobals,
deletedGlobals,
old = config.pollution;
saveGlobal();
newGlobals = diff(config.pollution, old);
if (newGlobals.length > 0) {
pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
}
deletedGlobals = diff(old, config.pollution);
if (deletedGlobals.length > 0) {
pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
}
}
// Will be exposed as QUnit.test
function test(testName, callback) {
if (focused$1) {
return;
}
var newTest = new Test({
testName: testName,
callback: callback
});
newTest.queue();
}
function todo(testName, callback) {
if (focused$1) {
return;
}
var newTest = new Test({
testName: testName,
callback: callback,
todo: true
});
newTest.queue();
}
// Will be exposed as QUnit.skip
function skip(testName) {
if (focused$1) {
return;
}
var test = new Test({
testName: testName,
skip: true
});
test.queue();
}
// Will be exposed as QUnit.only
function only(testName, callback) {
if (focused$1) {
return;
}
config.queue.length = 0;
focused$1 = true;
var newTest = new Test({
testName: testName,
callback: callback
});
newTest.queue();
}
// Put a hold on processing and return a function that will release it.
function internalStop(test) {
test.semaphore += 1;
config.blocking = true;
// Set a recovery timeout, if so configured.
if (defined.setTimeout) {
var timeoutDuration = void 0;
if (typeof test.timeout === "number") {
timeoutDuration = test.timeout;
} else if (typeof config.testTimeout === "number") {
timeoutDuration = config.testTimeout;
}
if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
clearTimeout(config.timeout);
config.timeout = setTimeout(function () {
pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
internalRecover(test);
}, timeoutDuration);
}
}
var released = false;
return function resume() {
if (released) {
return;
}
released = true;
test.semaphore -= 1;
internalStart(test);
};
}
// Forcefully release all processing holds.
function internalRecover(test) {
test.semaphore = 0;
internalStart(test);
}
// Release a processing hold, scheduling a resumption attempt if no holds remain.
function internalStart(test) {
// If semaphore is non-numeric, throw error
if (isNaN(test.semaphore)) {
test.semaphore = 0;
pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
return;
}
// Don't start until equal number of stop-calls
if (test.semaphore > 0) {
return;
}
// Throw an Error if start is called more often than stop
if (test.semaphore < 0) {
test.semaphore = 0;
pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
return;
}
// Add a slight delay to allow more assertions etc.
if (defined.setTimeout) {
if (config.timeout) {
clearTimeout(config.timeout);
}
config.timeout = setTimeout(function () {
if (test.semaphore > 0) {
return;
}
if (config.timeout) {
clearTimeout(config.timeout);
}
begin();
});
} else {
begin();
}
}
function collectTests(module) {
var tests = [].concat(module.tests);
var modules = [].concat(toConsumableArray(module.childModules));
// Do a breadth-first traversal of the child modules
while (modules.length) {
var nextModule = modules.shift();
tests.push.apply(tests, nextModule.tests);
modules.push.apply(modules, toConsumableArray(nextModule.childModules));
}
return tests;
}
function numberOfTests(module) {
return collectTests(module).length;
}
function numberOfUnskippedTests(module) {
return collectTests(module).filter(function (test) {
return !test.skip;
}).length;
}
function notifyTestsRan(module, skipped) {
module.testsRun++;
if (!skipped) {
module.unskippedTestsRun++;
}
while (module = module.parentModule) {
module.testsRun++;
if (!skipped) {
module.unskippedTestsRun++;
}
}
}
/**
* Returns a function that proxies to the given method name on the globals
* console object. The proxy will also detect if the console doesn't exist and
* will appropriately no-op. This allows support for IE9, which doesn't have a
* console if the developer tools are not open.
*/
function consoleProxy(method) {
return function () {
if (console) {
console[method].apply(console, arguments);
}
};
}
var Logger = {
warn: consoleProxy("warn")
};
var Assert = function () {
function Assert(testContext) {
classCallCheck(this, Assert);
this.test = testContext;
}
// Assert helpers
createClass(Assert, [{
key: "timeout",
value: function timeout(duration) {
if (typeof duration !== "number") {
throw new Error("You must pass a number as the duration to assert.timeout");
}
this.test.timeout = duration;
}
// Documents a "step", which is a string value, in a test as a passing assertion
}, {
key: "step",
value: function step(message) {
var result = !!message;
this.test.steps.push(message);
return this.pushResult({
result: result,
message: message || "You must provide a message to assert.step"
});
}
// Verifies the steps in a test match a given array of string values
}, {
key: "verifySteps",
value: function verifySteps(steps, message) {
this.deepEqual(this.test.steps, steps, message);
this.test.steps.length = 0;
}
// Specify the number of expected assertions to guarantee that failed test
// (no assertions are run at all) don't slip through.
}, {
key: "expect",
value: function expect(asserts) {
if (arguments.length === 1) {
this.test.expected = asserts;
} else {
return this.test.expected;
}
}
// Put a hold on processing and return a function that will release it a maximum of once.
}, {
key: "async",
value: function async(count) {
var test$$1 = this.test;
var popped = false,
acceptCallCount = count;
if (typeof acceptCallCount === "undefined") {
acceptCallCount = 1;
}
var resume = internalStop(test$$1);
return function done() {
if (config.current !== test$$1) {
throw Error("assert.async callback called after test finished.");
}
if (popped) {
test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
return;
}
acceptCallCount -= 1;
if (acceptCallCount > 0) {
return;
}
popped = true;
resume();
};
}
// Exports test.push() to the user API
// Alias of pushResult.
}, {
key: "push",
value: function push(result, actual, expected, message, negative) {
Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).");
var currentAssert = this instanceof Assert ? this : config.current.assert;
return currentAssert.pushResult({
result: result,
actual: actual,
expected: expected,
message: message,
negative: negative
});
}
}, {
key: "pushResult",
value: function pushResult(resultInfo) {
// Destructure of resultInfo = { result, actual, expected, message, negative }
var assert = this;
var currentTest = assert instanceof Assert && assert.test || config.current;
// Backwards compatibility fix.
// Allows the direct use of global exported assertions and QUnit.assert.*
// Although, it's use is not recommended as it can leak assertions
// to other tests from async tests, because we only get a reference to the current test,
// not exactly the test where assertion were intended to be called.
if (!currentTest) {
throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
}
if (!(assert instanceof Assert)) {
assert = currentTest.assert;
}
return assert.test.pushResult(resultInfo);
}
}, {
key: "ok",
value: function ok(result, message) {
if (!message) {
message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
}
this.pushResult({
result: !!result,
actual: result,
expected: true,
message: message
});
}
}, {
key: "notOk",
value: function notOk(result, message) {
if (!message) {
message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
}
this.pushResult({
result: !result,
actual: result,
expected: false,
message: message
});
}
}, {
key: "equal",
value: function equal(actual, expected, message) {
// eslint-disable-next-line eqeqeq
var result = expected == actual;
this.pushResult({
result: result,
actual: actual,
expected: expected,
message: message
});
}
}, {
key: "notEqual",
value: function notEqual(actual, expected, message) {
// eslint-disable-next-line eqeqeq
var result = expected != actual;
this.pushResult({
result: result,
actual: actual,
expected: expected,
message: message,
negative: true
});
}
}, {
key: "propEqual",
value: function propEqual(actual, expected, message) {
actual = objectValues(actual);
expected = objectValues(expected);
this.pushResult({
result: equiv(actual, expected),
actual: actual,
expected: expected,
message: message
});
}
}, {
key: "notPropEqual",
value: function notPropEqual(actual, expected, message) {
actual = objectValues(actual);
expected = objectValues(expected);
this.pushResult({
result: !equiv(actual, expected),
actual: actual,
expected: expected,
message: message,
negative: true
});
}
}, {
key: "deepEqual",
value: function deepEqual(actual, expected, message) {
this.pushResult({
result: equiv(actual, expected),
actual: actual,
expected: expected,
message: message
});
}
}, {
key: "notDeepEqual",
value: function notDeepEqual(actual, expected, message) {
this.pushResult({
result: !equiv(actual, expected),
actual: actual,
expected: expected,
message: message,
negative: true
});
}
}, {
key: "strictEqual",
value: function strictEqual(actual, expected, message) {
this.pushResult({
result: expected === actual,
actual: actual,
expected: expected,
message: message
});
}
}, {
key: "notStrictEqual",
value: function notStrictEqual(actual, expected, message) {
this.pushResult({
result: expected !== actual,
actual: actual,
expected: expected,
message: message,
negative: true
});
}
}, {
key: "throws",
value: function throws(block, expected, message) {
var actual = void 0,
result = false;
var currentTest = this instanceof Assert && this.test || config.current;
// 'expected' is optional unless doing string comparison
if (objectType(expected) === "string") {
if (message == null) {
message = expected;
expected = null;
} else {
throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary.");
}
}
currentTest.ignoreGlobalErrors = true;
try {
block.call(currentTest.testEnvironment);
} catch (e) {
actual = e;
}
currentTest.ignoreGlobalErrors = false;
if (actual) {
var expectedType = objectType(expected);
// We don't want to validate thrown error
if (!expected) {
result = true;
expected = null;
// Expected is a regexp
} else if (expectedType === "regexp") {
result = expected.test(errorString(actual));
// Expected is a constructor, maybe an Error constructor
} else if (expectedType === "function" && actual instanceof expected) {
result = true;
// Expected is an Error object
} else if (expectedType === "object") {
result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
// Expected is a validation function which returns true if validation passed
} else if (expectedType === "function" && expected.call({}, actual) === true) {
expected = null;
result = true;
}
}
currentTest.assert.pushResult({
result: result,
actual: actual,
expected: expected,
message: message
});
}
}, {
key: "rejects",
value: function rejects(promise, expected, message) {
var result = false;
var currentTest = this instanceof Assert && this.test || config.current;
// 'expected' is optional unless doing string comparison
if (objectType(expected) === "string") {
if (message === undefined) {
message = expected;
expected = undefined;
} else {
message = "assert.rejects does not accept a string value for the expected " + "argument.\nUse a non-string object value (e.g. validator function) instead " + "if necessary.";
currentTest.assert.pushResult({
result: false,
message: message
});
return;
}
}
var then = promise && promise.then;
if (objectType(then) !== "function") {
var _message = "The value provided to `assert.rejects` in " + "\"" + currentTest.testName + "\" was not a promise.";
currentTest.assert.pushResult({
result: false,
message: _message,
actual: promise
});
return;
}
var done = this.async();
return then.call(promise, function handleFulfillment() {
var message = "The promise returned by the `assert.rejects` callback in " + "\"" + currentTest.testName + "\" did not reject.";
currentTest.assert.pushResult({
result: false,
message: message,
actual: promise
});
done();
}, function handleRejection(actual) {
if (actual) {
var expectedType = objectType(expected);
// We don't want to validate
if (expected === undefined) {
result = true;
expected = null;
// Expected is a regexp
} else if (expectedType === "regexp") {
result = expected.test(errorString(actual));
// Expected is a constructor, maybe an Error constructor
} else if (expectedType === "function" && actual instanceof expected) {
result = true;
// Expected is an Error object
} else if (expectedType === "object") {
result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
// Expected is a validation function which returns true if validation passed
} else {
if (expectedType === "function") {
result = expected.call({}, actual) === true;
expected = null;
// Expected is some other invalid type
} else {
result = false;
message = "invalid expected value provided to `assert.rejects` " + "callback in \"" + currentTest.testName + "\": " + expectedType + ".";
}
}
}
currentTest.assert.pushResult({
result: result,
actual: actual,
expected: expected,
message: message
});
done();
});
}
}]);
return Assert;
}();
// Provide an alternative to assert.throws(), for environments that consider throws a reserved word
// Known to us are: Closure Compiler, Narwhal
// eslint-disable-next-line dot-notation
Assert.prototype.raises = Assert.prototype["throws"];
/**
* Converts an error into a simple string for comparisons.
*
* @param {Error} error
* @return {String}
*/
function errorString(error) {
var resultErrorString = error.toString();
if (resultErrorString.substring(0, 7) === "[object") {
var name = error.name ? error.name.toString() : "Error";
var message = error.message ? error.message.toString() : "";
if (name && message) {
return name + ": " + message;
} else if (name) {
return name;
} else if (message) {
return message;
} else {
return "Error";
}
} else {
return resultErrorString;
}
}
/* global module, exports, define */
function exportQUnit(QUnit) {
if (defined.document) {
// QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
if (window.QUnit && window.QUnit.version) {
throw new Error("QUnit has already been defined.");
}
window.QUnit = QUnit;
}
// For nodejs
if (typeof module !== "undefined" && module && module.exports) {
module.exports = QUnit;
// For consistency with CommonJS environments' exports
module.exports.QUnit = QUnit;
}
// For CommonJS with exports, but without module.exports, like Rhino
if (typeof exports !== "undefined" && exports) {
exports.QUnit = QUnit;
}
if (typeof define === "function" && define.amd) {
define(function () {
return QUnit;
});
QUnit.config.autostart = false;
}
// For Web/Service Workers
if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
self$1.QUnit = QUnit;
}
}
var SuiteReport = function () {
function SuiteReport(name, parentSuite) {
classCallCheck(this, SuiteReport);
this.name = name;
this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
this.tests = [];
this.childSuites = [];
if (parentSuite) {
parentSuite.pushChildSuite(this);
}
}
createClass(SuiteReport, [{
key: "start",
value: function start(recordTime) {
if (recordTime) {
this._startTime = Date.now();
}
return {
name: this.name,
fullName: this.fullName.slice(),
tests: this.tests.map(function (test) {
return test.start();
}),
childSuites: this.childSuites.map(function (suite) {
return suite.start();
}),
testCounts: {
total: this.getTestCounts().total
}
};
}
}, {
key: "end",
value: function end(recordTime) {
if (recordTime) {
this._endTime = Date.now();
}
return {
name: this.name,
fullName: this.fullName.slice(),
tests: this.tests.map(function (test) {
return test.end();
}),
childSuites: this.childSuites.map(function (suite) {
return suite.end();
}),
testCounts: this.getTestCounts(),
runtime: this.getRuntime(),
status: this.getStatus()
};
}
}, {
key: "pushChildSuite",
value: function pushChildSuite(suite) {
this.childSuites.push(suite);
}
}, {
key: "pushTest",
value: function pushTest(test) {
this.tests.push(test);
}
}, {
key: "getRuntime",
value: function getRuntime() {
return this._endTime - this._startTime;
}
}, {
key: "getTestCounts",
value: function getTestCounts() {
var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
counts = this.tests.reduce(function (counts, test) {
if (test.valid) {
counts[test.getStatus()]++;
counts.total++;
}
return counts;
}, counts);
return this.childSuites.reduce(function (counts, suite) {
return suite.getTestCounts(counts);
}, counts);
}
}, {
key: "getStatus",
value: function getStatus() {
var _getTestCounts = this.getTestCounts(),
total = _getTestCounts.total,
failed = _getTestCounts.failed,
skipped = _getTestCounts.skipped,
todo = _getTestCounts.todo;
if (failed) {
return "failed";
} else {
if (skipped === total) {
return "skipped";
} else if (todo === total) {
return "todo";
} else {
return "passed";
}
}
}
}]);
return SuiteReport;
}();
// Handle an unhandled exception. By convention, returns true if further
// error handling should be suppressed and false otherwise.
// In this case, we will only suppress further error handling if the
// "ignoreGlobalErrors" configuration option is enabled.
function onError(error) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (config.current) {
if (config.current.ignoreGlobalErrors) {
return true;
}
pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
} else {
test("global failure", extend(function () {
pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
}, { validTest: true }));
}
return false;
}
// Handle an unhandled rejection
function onUnhandledRejection(reason) {
var resultInfo = {
result: false,
message: reason.message || "error",
actual: reason,
source: reason.stack || sourceFromStacktrace(3)
};
var currentTest = config.current;
if (currentTest) {
currentTest.assert.pushResult(resultInfo);
} else {
test("global failure", extend(function (assert) {
assert.pushResult(resultInfo);
}, { validTest: true }));
}
}
var focused = false;
var QUnit = {};
var globalSuite = new SuiteReport();
// The initial "currentModule" represents the global (or top-level) module that
// is not explicitly defined by the user, therefore we add the "globalSuite" to
// it since each module has a suiteReport associated with it.
config.currentModule.suiteReport = globalSuite;
var moduleStack = [];
var globalStartCalled = false;
var runStarted = false;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
// Expose the current QUnit version
QUnit.version = "2.5.0";
function createModule(name, testEnvironment, modifiers) {
var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip;
var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo;
var module = {
name: moduleName,
parentModule: parentModule,
tests: [],
moduleId: generateHash(moduleName),
testsRun: 0,
unskippedTestsRun: 0,
childModules: [],
suiteReport: new SuiteReport(name, parentSuite),
// Pass along `skip` and `todo` properties from parent module, in case
// there is one, to childs. And use own otherwise.
// This property will be used to mark own tests and tests of child suites
// as either `skipped` or `todo`.
skip: skip$$1,
todo: skip$$1 ? false : todo$$1
};
var env = {};
if (parentModule) {
parentModule.childModules.push(module);
extend(env, parentModule.testEnvironment);
}
extend(env, testEnvironment);
module.testEnvironment = env;
config.modules.push(module);
return module;
}
function processModule(name, options, executeNow) {
var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var module = createModule(name, options, modifiers);
// Move any hooks to a 'hooks' object
var testEnvironment = module.testEnvironment;
var hooks = module.hooks = {};
setHookFromEnvironment(hooks, testEnvironment, "before");
setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
setHookFromEnvironment(hooks, testEnvironment, "afterEach");
setHookFromEnvironment(hooks, testEnvironment, "after");
function setHookFromEnvironment(hooks, environment, name) {
var potentialHook = environment[name];
hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
delete environment[name];
}
var moduleFns = {
before: setHookFunction(module, "before"),
beforeEach: setHookFunction(module, "beforeEach"),
afterEach: setHookFunction(module, "afterEach"),
after: setHookFunction(module, "after")
};
var currentModule = config.currentModule;
if (objectType(executeNow) === "function") {
moduleStack.push(module);
config.currentModule = module;
executeNow.call(module.testEnvironment, moduleFns);
moduleStack.pop();
module = module.parentModule || currentModule;
}
config.currentModule = module;
}
// TODO: extract this to a new file alongside its related functions
function module$1(name, options, executeNow) {
if (focused) {
return;
}
if (arguments.length === 2) {
if (objectType(options) === "function") {
executeNow = options;
options = undefined;
}
}
processModule(name, options, executeNow);
}
module$1.only = function () {
if (focused) {
return;
}
config.modules.length = 0;
config.queue.length = 0;
module$1.apply(undefined, arguments);
focused = true;
};
module$1.skip = function (name, options, executeNow) {
if (focused) {
return;
}
if (arguments.length === 2) {
if (objectType(options) === "function") {
executeNow = options;
options = undefined;
}
}
processModule(name, options, executeNow, { skip: true });
};
module$1.todo = function (name, options, executeNow) {
if (focused) {
return;
}
if (arguments.length === 2) {
if (objectType(options) === "function") {
executeNow = options;
options = undefined;
}
}
processModule(name, options, executeNow, { todo: true });
};
extend(QUnit, {
on: on,
module: module$1,
test: test,
todo: todo,
skip: skip,
only: only,
start: function start(count) {
var globalStartAlreadyCalled = globalStartCalled;
if (!config.current) {
globalStartCalled = true;
if (runStarted) {
throw new Error("Called start() while test already started running");
} else if (globalStartAlreadyCalled || count > 1) {
throw new Error("Called start() outside of a test context too many times");
} else if (config.autostart) {
throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
} else if (!config.pageLoaded) {
// The page isn't completely loaded yet, so we set autostart and then
// load if we're in Node or wait for the browser's load event.
config.autostart = true;
// Starts from Node even if .load was not previously called. We still return
// early otherwise we'll wind up "beginning" twice.
if (!defined.document) {
QUnit.load();
}
return;
}
} else {
throw new Error("QUnit.start cannot be called inside a test context.");
}
scheduleBegin();
},
config: config,
is: is,
objectType: objectType,
extend: extend,
load: function load() {
config.pageLoaded = true;
// Initialize the configuration options
extend(config, {
stats: { all: 0, bad: 0 },
started: 0,
updateRate: 1000,
autostart: true,
filter: ""
}, true);
if (!runStarted) {
config.blocking = false;
if (config.autostart) {
scheduleBegin();
}
}
},
stack: function stack(offset) {
offset = (offset || 0) + 2;
return sourceFromStacktrace(offset);
},
onError: onError,
onUnhandledRejection: onUnhandledRejection
});
QUnit.pushFailure = pushFailure;
QUnit.assert = Assert.prototype;
QUnit.equiv = equiv;
QUnit.dump = dump;
registerLoggingCallbacks(QUnit);
function scheduleBegin() {
runStarted = true;
// Add a slight delay to allow definition of more modules and tests.
if (defined.setTimeout) {
setTimeout(function () {
begin();
});
} else {
begin();
}
}
function begin() {
var i,
l,
modulesLog = [];
// If the test run hasn't officially begun yet
if (!config.started) {
// Record the time of the test run's beginning
config.started = now();
// Delete the loose unnamed module if unused.
if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
config.modules.shift();
}
// Avoid unnecessary information by not logging modules' test environments
for (i = 0, l = config.modules.length; i < l; i++) {
modulesLog.push({
name: config.modules[i].name,
tests: config.modules[i].tests
});
}
// The test run is officially beginning now
emit("runStart", globalSuite.start(true));
runLoggingCallbacks("begin", {
totalTests: Test.count,
modules: modulesLog
});
}
config.blocking = false;
ProcessingQueue.advance();
}
function setHookFunction(module, hookName) {
return function setHook(callback) {
module.hooks[hookName].push(callback);
};
}
exportQUnit(QUnit);
(function () {
if (typeof window === "undefined" || typeof document === "undefined") {
return;
}
var config = QUnit.config,
hasOwn = Object.prototype.hasOwnProperty;
// Stores fixture HTML for resetting later
function storeFixture() {
// Avoid overwriting user-defined values
if (hasOwn.call(config, "fixture")) {
return;
}
var fixture = document.getElementById("qunit-fixture");
if (fixture) {
config.fixture = fixture.innerHTML;
}
}
QUnit.begin(storeFixture);
// Resets the fixture DOM element if available.
function resetFixture() {
if (config.fixture == null) {
return;
}
var fixture = document.getElementById("qunit-fixture");
if (fixture) {
fixture.innerHTML = config.fixture;
}
}
QUnit.testStart(resetFixture);
})();
(function () {
// Only interact with URLs via window.location
var location = typeof window !== "undefined" && window.location;
if (!location) {
return;
}
var urlParams = getUrlParams();
QUnit.urlParams = urlParams;
// Match module/test by inclusion in an array
QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
QUnit.config.testId = [].concat(urlParams.testId || []);
// Exact case-insensitive match of the module name
QUnit.config.module = urlParams.module;
// Regular expression or case-insenstive substring match against "moduleName: testName"
QUnit.config.filter = urlParams.filter;
// Test order randomization
if (urlParams.seed === true) {
// Generate a random seed if the option is specified without a value
QUnit.config.seed = Math.random().toString(36).slice(2);
} else if (urlParams.seed) {
QUnit.config.seed = urlParams.seed;
}
// Add URL-parameter-mapped config values with UI form rendering data
QUnit.config.urlConfig.push({
id: "hidepassed",
label: "Hide passed tests",
tooltip: "Only show tests and assertions that fail. Stored as query-strings."
}, {
id: "noglobals",
label: "Check for Globals",
tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
}, {
id: "notrycatch",
label: "No try-catch",
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
});
QUnit.begin(function () {
var i,
option,
urlConfig = QUnit.config.urlConfig;
for (i = 0; i < urlConfig.length; i++) {
// Options can be either strings or objects with nonempty "id" properties
option = QUnit.config.urlConfig[i];
if (typeof option !== "string") {
option = option.id;
}
if (QUnit.config[option] === undefined) {
QUnit.config[option] = urlParams[option];
}
}
});
function getUrlParams() {
var i, param, name, value;
var urlParams = Object.create(null);
var params = location.search.slice(1).split("&");
var length = params.length;
for (i = 0; i < length; i++) {
if (params[i]) {
param = params[i].split("=");
name = decodeQueryParam(param[0]);
// Allow just a key to turn on a flag, e.g., test.html?noglobals
value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
if (name in urlParams) {
urlParams[name] = [].concat(urlParams[name], value);
} else {
urlParams[name] = value;
}
}
}
return urlParams;
}
function decodeQueryParam(param) {
return decodeURIComponent(param.replace(/\+/g, "%20"));
}
})();
var stats = {
passedTests: 0,
failedTests: 0,
skippedTests: 0,
todoTests: 0
};
// Escape text for attribute or text content.
function escapeText(s) {
if (!s) {
return "";
}
s = s + "";
// Both single quotes and double quotes (for attributes)
return s.replace(/['"<>&]/g, function (s) {
switch (s) {
case "'":
return "'";
case "\"":
return """;
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
}
});
}
(function () {
// Don't load the HTML Reporter on non-browser environments
if (typeof window === "undefined" || !window.document) {
return;
}
var config = QUnit.config,
document$$1 = window.document,
collapseNext = false,
hasOwn = Object.prototype.hasOwnProperty,
unfilteredUrl = setUrl({ filter: undefined, module: undefined,
moduleId: undefined, testId: undefined }),
modulesList = [];
function addEvent(elem, type, fn) {
elem.addEventListener(type, fn, false);
}
function removeEvent(elem, type, fn) {
elem.removeEventListener(type, fn, false);
}
function addEvents(elems, type, fn) {
var i = elems.length;
while (i--) {
addEvent(elems[i], type, fn);
}
}
function hasClass(elem, name) {
return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
}
function addClass(elem, name) {
if (!hasClass(elem, name)) {
elem.className += (elem.className ? " " : "") + name;
}
}
function toggleClass(elem, name, force) {
if (force || typeof force === "undefined" && !hasClass(elem, name)) {
addClass(elem, name);
} else {
removeClass(elem, name);
}
}
function removeClass(elem, name) {
var set = " " + elem.className + " ";
// Class name may appear multiple times
while (set.indexOf(" " + name + " ") >= 0) {
set = set.replace(" " + name + " ", " ");
}
// Trim for prettiness
elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
}
function id(name) {
return document$$1.getElementById && document$$1.getElementById(name);
}
function abortTests() {
var abortButton = id("qunit-abort-tests-button");
if (abortButton) {
abortButton.disabled = true;
abortButton.innerHTML = "Aborting...";
}
QUnit.config.queue.length = 0;
return false;
}
function interceptNavigation(ev) {
applyUrlParams();
if (ev && ev.preventDefault) {
ev.preventDefault();
}
return false;
}
function getUrlConfigHtml() {
var i,
j,
val,
escaped,
escapedTooltip,
selection = false,
urlConfig = config.urlConfig,
urlConfigHtml = "";
for (i = 0; i < urlConfig.length; i++) {
// Options can be either strings or objects with nonempty "id" properties
val = config.urlConfig[i];
if (typeof val === "string") {
val = {
id: val,
label: val
};
}
escaped = escapeText(val.id);
escapedTooltip = escapeText(val.tooltip);
if (!val.value || typeof val.value === "string") {
urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>";
} else {
urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
if (QUnit.is("array", val.value)) {
for (j = 0; j < val.value.length; j++) {
escaped = escapeText(val.value[j]);
urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
}
} else {
for (j in val.value) {
if (hasOwn.call(val.value, j)) {
urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
}
}
}
if (config[val.id] && !selection) {
escaped = escapeText(config[val.id]);
urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
}
urlConfigHtml += "</select>";
}
}
return urlConfigHtml;
}
// Handle "click" events on toolbar checkboxes and "change" for select menus.
// Updates the URL with the new state of `config.urlConfig` values.
function toolbarChanged() {
var updatedUrl,
value,
tests,
field = this,
params = {};
// Detect if field is a select menu or a checkbox
if ("selectedIndex" in field) {
value = field.options[field.selectedIndex].value || undefined;
} else {
value = field.checked ? field.defaultValue || true : undefined;
}
params[field.name] = value;
updatedUrl = setUrl(params);
// Check if we can apply the change without a page refresh
if ("hidepassed" === field.name && "replaceState" in window.history) {
QUnit.urlParams[field.name] = value;
config[field.name] = value || false;
tests = id("qunit-tests");
if (tests) {
toggleClass(tests, "hidepass", value || false);
}
window.history.replaceState(null, "", updatedUrl);
} else {
window.location = updatedUrl;
}
}
function setUrl(params) {
var key,
arrValue,
i,
querystring = "?",
location = window.location;
params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
for (key in params) {
// Skip inherited or undefined properties
if (hasOwn.call(params, key) && params[key] !== undefined) {
// Output a parameter for each value of this key
// (but usually just one)
arrValue = [].concat(params[key]);
for (i = 0; i < arrValue.length; i++) {
querystring += encodeURIComponent(key);
if (arrValue[i] !== true) {
querystring += "=" + encodeURIComponent(arrValue[i]);
}
querystring += "&";
}
}
}
return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
}
function applyUrlParams() {
var i,
selectedModules = [],
modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
filter = id("qunit-filter-input").value;
for (i = 0; i < modulesList.length; i++) {
if (modulesList[i].checked) {
selectedModules.push(modulesList[i].value);
}
}
window.location = setUrl({
filter: filter === "" ? undefined : filter,
moduleId: selectedModules.length === 0 ? undefined : selectedModules,
// Remove module and testId filter
module: undefined,
testId: undefined
});
}
function toolbarUrlConfigContainer() {
var urlConfigContainer = document$$1.createElement("span");
urlConfigContainer.innerHTML = getUrlConfigHtml();
addClass(urlConfigContainer, "qunit-url-config");
addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
return urlConfigContainer;
}
function abortTestsButton() {
var button = document$$1.createElement("button");
button.id = "qunit-abort-tests-button";
button.innerHTML = "Abort";
addEvent(button, "click", abortTests);
return button;
}
function toolbarLooseFilter() {
var filter = document$$1.createElement("form"),
label = document$$1.createElement("label"),
input = document$$1.createElement("input"),
button = document$$1.createElement("button");
addClass(filter, "qunit-filter");
label.innerHTML = "Filter: ";
input.type = "text";
input.value = config.filter || "";
input.name = "filter";
input.id = "qunit-filter-input";
button.innerHTML = "Go";
label.appendChild(input);
filter.appendChild(label);
filter.appendChild(document$$1.createTextNode(" "));
filter.appendChild(button);
addEvent(filter, "submit", interceptNavigation);
return filter;
}
function moduleListHtml() {
var i,
checked,
html = "";
for (i = 0; i < config.modules.length; i++) {
if (config.modules[i].name !== "") {
checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>";
}
}
return html;
}
function toolbarModuleFilter() {
var allCheckbox,
commit,
reset,
moduleFilter = document$$1.createElement("form"),
label = document$$1.createElement("label"),
moduleSearch = document$$1.createElement("input"),
dropDown = document$$1.createElement("div"),
actions = document$$1.createElement("span"),
dropDownList = document$$1.createElement("ul"),
dirty = false;
moduleSearch.id = "qunit-modulefilter-search";
addEvent(moduleSearch, "input", searchInput);
addEvent(moduleSearch, "input", searchFocus);
addEvent(moduleSearch, "focus", searchFocus);
addEvent(moduleSearch, "click", searchFocus);
label.id = "qunit-modulefilter-search-container";
label.innerHTML = "Module: ";
label.appendChild(moduleSearch);
actions.id = "qunit-modulefilter-actions";
actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>";
allCheckbox = actions.lastChild.firstChild;
commit = actions.firstChild;
reset = commit.nextSibling;
addEvent(commit, "click", applyUrlParams);
dropDownList.id = "qunit-modulefilter-dropdown-list";
dropDownList.innerHTML = moduleListHtml();
dropDown.id = "qunit-modulefilter-dropdown";
dropDown.style.display = "none";
dropDown.appendChild(actions);
dropDown.appendChild(dropDownList);
addEvent(dropDown, "change", selectionChange);
selectionChange();
moduleFilter.id = "qunit-modulefilter";
moduleFilter.appendChild(label);
moduleFilter.appendChild(dropDown);
addEvent(moduleFilter, "submit", interceptNavigation);
addEvent(moduleFilter, "reset", function () {
// Let the reset happen, then update styles
window.setTimeout(selectionChange);
});
// Enables show/hide for the dropdown
function searchFocus() {
if (dropDown.style.display !== "none") {
return;
}
dropDown.style.display = "block";
addEvent(document$$1, "click", hideHandler);
addEvent(document$$1, "keydown", hideHandler);
// Hide on Escape keydown or outside-container click
function hideHandler(e) {
var inContainer = moduleFilter.contains(e.target);
if (e.keyCode === 27 || !inContainer) {
if (e.keyCode === 27 && inContainer) {
moduleSearch.focus();
}
dropDown.style.display = "none";
removeEvent(document$$1, "click", hideHandler);
removeEvent(document$$1, "keydown", hideHandler);
moduleSearch.value = "";
searchInput();
}
}
}
// Processes module search box input
function searchInput() {
var i,
item,
searchText = moduleSearch.value.toLowerCase(),
listItems = dropDownList.children;
for (i = 0; i < listItems.length; i++) {
item = listItems[i];
if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
item.style.display = "";
} else {
item.style.display = "none";
}
}
}
// Processes selection changes
function selectionChange(evt) {
var i,
item,
checkbox = evt && evt.target || allCheckbox,
modulesList = dropDownList.getElementsByTagName("input"),
selectedNames = [];
toggleClass(checkbox.parentNode, "checked", checkbox.checked);
dirty = false;
if (checkbox.checked && checkbox !== allCheckbox) {
allCheckbox.checked = false;
removeClass(allCheckbox.parentNode, "checked");
}
for (i = 0; i < modulesList.length; i++) {
item = modulesList[i];
if (!evt) {
toggleClass(item.parentNode, "checked", item.checked);
} else if (checkbox === allCheckbox && checkbox.checked) {
item.checked = false;
removeClass(item.parentNode, "checked");
}
dirty = dirty || item.checked !== item.defaultChecked;
if (item.checked) {
selectedNames.push(item.parentNode.textContent);
}
}
commit.style.display = reset.style.display = dirty ? "" : "none";
moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
}
return moduleFilter;
}
function appendToolbar() {
var toolbar = id("qunit-testrunner-toolbar");
if (toolbar) {
toolbar.appendChild(toolbarUrlConfigContainer());
toolbar.appendChild(toolbarModuleFilter());
toolbar.appendChild(toolbarLooseFilter());
toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
}
}
function appendHeader() {
var header = id("qunit-header");
if (header) {
header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
}
}
function appendBanner() {
var banner = id("qunit-banner");
if (banner) {
banner.className = "";
}
}
function appendTestResults() {
var tests = id("qunit-tests"),
result = id("qunit-testresult"),
controls;
if (result) {
result.parentNode.removeChild(result);
}
if (tests) {
tests.innerHTML = "";
result = document$$1.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore(result, tests);
result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br /> </div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
controls = id("qunit-testresult-controls");
}
if (controls) {
controls.appendChild(abortTestsButton());
}
}
function appendFilteredTest() {
var testId = QUnit.config.testId;
if (!testId || testId.length <= 0) {
return "";
}
return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
}
function appendUserAgent() {
var userAgent = id("qunit-userAgent");
if (userAgent) {
userAgent.innerHTML = "";
userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
}
}
function appendInterface() {
var qunit = id("qunit");
if (qunit) {
qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
}
appendHeader();
appendBanner();
appendTestResults();
appendUserAgent();
appendToolbar();
}
function appendTestsList(modules) {
var i, l, x, z, test, moduleObj;
for (i = 0, l = modules.length; i < l; i++) {
moduleObj = modules[i];
for (x = 0, z = moduleObj.tests.length; x < z; x++) {
test = moduleObj.tests[x];
appendTest(test.name, test.testId, moduleObj.name);
}
}
}
function appendTest(name, testId, moduleName) {
var title,
rerunTrigger,
testBlock,
assertList,
tests = id("qunit-tests");
if (!tests) {
return;
}
title = document$$1.createElement("strong");
title.innerHTML = getNameHtml(name, moduleName);
rerunTrigger = document$$1.createElement("a");
rerunTrigger.innerHTML = "Rerun";
rerunTrigger.href = setUrl({ testId: testId });
testBlock = document$$1.createElement("li");
testBlock.appendChild(title);
testBlock.appendChild(rerunTrigger);
testBlock.id = "qunit-test-output-" + testId;
assertList = document$$1.createElement("ol");
assertList.className = "qunit-assert-list";
testBlock.appendChild(assertList);
tests.appendChild(testBlock);
}
// HTML Reporter initialization and load
QUnit.begin(function (details) {
var i, moduleObj, tests;
// Sort modules by name for the picker
for (i = 0; i < details.modules.length; i++) {
moduleObj = details.modules[i];
if (moduleObj.name) {
modulesList.push(moduleObj.name);
}
}
modulesList.sort(function (a, b) {
return a.localeCompare(b);
});
// Initialize QUnit elements
appendInterface();
appendTestsList(details.modules);
tests = id("qunit-tests");
if (tests && config.hidepassed) {
addClass(tests, "hidepass");
}
});
QUnit.done(function (details) {
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
abortButton = id("qunit-abort-tests-button"),
totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""),
test,
assertLi,
assertList;
// Update remaing tests to aborted
if (abortButton && abortButton.disabled) {
html = "Tests aborted after " + details.runtime + " milliseconds.";
for (var i = 0; i < tests.children.length; i++) {
test = tests.children[i];
if (test.className === "" || test.className === "running") {
test.className = "aborted";
assertList = test.getElementsByTagName("ol")[0];
assertLi = document$$1.createElement("li");
assertLi.className = "fail";
assertLi.innerHTML = "Test aborted.";
assertList.appendChild(assertLi);
}
}
}
if (banner && (!abortButton || abortButton.disabled === false)) {
banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
}
if (abortButton) {
abortButton.parentNode.removeChild(abortButton);
}
if (tests) {
id("qunit-testresult-display").innerHTML = html;
}
if (config.altertitle && document$$1.title) {
// Show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8
// charset
document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
}
// Scroll back to top to show results
if (config.scrolltop && window.scrollTo) {
window.scrollTo(0, 0);
}
});
function getNameHtml(name, module) {
var nameHtml = "";
if (module) {
nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
}
nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
return nameHtml;
}
QUnit.testStart(function (details) {
var running, testBlock, bad;
testBlock = id("qunit-test-output-" + details.testId);
if (testBlock) {
testBlock.className = "running";
} else {
// Report later registered tests
appendTest(details.name, details.testId, details.module);
}
running = id("qunit-testresult-display");
if (running) {
bad = QUnit.config.reorder && details.previousFailure;
running.innerHTML = [bad ? "Rerunning previously failed test: <br />" : "Running: <br />", getNameHtml(details.name, details.module)].join("");
}
});
function stripHtml(string) {
// Strip tags, html entity and whitespaces
return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
}
QUnit.log(function (details) {
var assertList,
assertLi,
message,
expected,
actual,
diff,
showDiff = false,
testItem = id("qunit-test-output-" + details.testId);
if (!testItem) {
return;
}
message = escapeText(details.message) || (details.result ? "okay" : "failed");
message = "<span class='test-message'>" + message + "</span>";
message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
// The pushFailure doesn't provide details.expected
// when it calls, it's implicit to also not show expected and diff stuff
// Also, we need to check details.expected existence, as it can exist and be undefined
if (!details.result && hasOwn.call(details, "expected")) {
if (details.negative) {
expected = "NOT " + QUnit.dump.parse(details.expected);
} else {
expected = QUnit.dump.parse(details.expected);
}
actual = QUnit.dump.parse(details.actual);
message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
if (actual !== expected) {
message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
if (typeof details.actual === "number" && typeof details.expected === "number") {
if (!isNaN(details.actual) && !isNaN(details.expected)) {
showDiff = true;
diff = details.actual - details.expected;
diff = (diff > 0 ? "+" : "") + diff;
}
} else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
diff = QUnit.diff(expected, actual);
// don't show diff if there is zero overlap
showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
}
if (showDiff) {
message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
}
} else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
} else {
message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
}
if (details.source) {
message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
}
message += "</table>";
// This occurs when pushFailure is set and we have an extracted stack trace
} else if (!details.result && details.source) {
message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
}
assertList = testItem.getElementsByTagName("ol")[0];
assertLi = document$$1.createElement("li");
assertLi.className = details.result ? "pass" : "fail";
assertLi.innerHTML = message;
assertList.appendChild(assertLi);
});
QUnit.testDone(function (details) {
var testTitle,
time,
testItem,
assertList,
good,
bad,
testCounts,
skipped,
sourceName,
tests = id("qunit-tests");
if (!tests) {
return;
}
testItem = id("qunit-test-output-" + details.testId);
assertList = testItem.getElementsByTagName("ol")[0];
good = details.passed;
bad = details.failed;
// This test passed if it has no unexpected failed assertions
var testPassed = details.failed > 0 ? details.todo : !details.todo;
if (testPassed) {
// Collapse the passing tests
addClass(assertList, "qunit-collapsed");
} else if (config.collapse) {
if (!collapseNext) {
// Skip collapsing the first failing test
collapseNext = true;
} else {
// Collapse remaining tests
addClass(assertList, "qunit-collapsed");
}
}
// The testItem.firstChild is the test name
testTitle = testItem.firstChild;
testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
if (details.skipped) {
stats.skippedTests++;
testItem.className = "skipped";
skipped = document$$1.createElement("em");
skipped.className = "qunit-skipped-label";
skipped.innerHTML = "skipped";
testItem.insertBefore(skipped, testTitle);
} else {
addEvent(testTitle, "click", function () {
toggleClass(assertList, "qunit-collapsed");
});
testItem.className = testPassed ? "pass" : "fail";
if (details.todo) {
var todoLabel = document$$1.createElement("em");
todoLabel.className = "qunit-todo-label";
todoLabel.innerHTML = "todo";
testItem.className += " todo";
testItem.insertBefore(todoLabel, testTitle);
}
time = document$$1.createElement("span");
time.className = "runtime";
time.innerHTML = details.runtime + " ms";
testItem.insertBefore(time, assertList);
if (!testPassed) {
stats.failedTests++;
} else if (details.todo) {
stats.todoTests++;
} else {
stats.passedTests++;
}
}
// Show the source of the test when showing assertions
if (details.source) {
sourceName = document$$1.createElement("p");
sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
addClass(sourceName, "qunit-source");
if (testPassed) {
addClass(sourceName, "qunit-collapsed");
}
addEvent(testTitle, "click", function () {
toggleClass(sourceName, "qunit-collapsed");
});
testItem.appendChild(sourceName);
}
});
// Avoid readyState issue with phantomjs
// Ref: #818
var notPhantom = function (p) {
return !(p && p.version && p.version.major > 0);
}(window.phantom);
if (notPhantom && document$$1.readyState === "complete") {
QUnit.load();
} else {
addEvent(window, "load", QUnit.load);
}
// Wrap window.onerror. We will call the original window.onerror to see if
// the existing handler fully handles the error; if not, we will call the
// QUnit.onError function.
var originalWindowOnError = window.onerror;
// Cover uncaught exceptions
// Returning true will suppress the default browser handler,
// returning false will let it run.
window.onerror = function (message, fileName, lineNumber) {
var ret = false;
if (originalWindowOnError) {
for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
args[_key - 3] = arguments[_key];
}
ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
}
// Treat return value as window.onerror itself does,
// Only do our handling if not suppressed.
if (ret !== true) {
var error = {
message: message,
fileName: fileName,
lineNumber: lineNumber
};
ret = QUnit.onError(error);
}
return ret;
};
// Listen for unhandled rejections, and call QUnit.onUnhandledRejection
window.addEventListener("unhandledrejection", function (event) {
QUnit.onUnhandledRejection(event.reason);
});
})();
/*
* This file is a modified version of google-diff-match-patch's JavaScript implementation
* (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
* modifications are licensed as more fully set forth in LICENSE.txt.
*
* The original source of google-diff-match-patch is attributable and licensed as follows:
*
* Copyright 2006 Google Inc.
* https://code.google.com/p/google-diff-match-patch/
*
* 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
*
* https://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.
*
* More Info:
* https://code.google.com/p/google-diff-match-patch/
*
* Usage: QUnit.diff(expected, actual)
*
*/
QUnit.diff = function () {
function DiffMatchPatch() {}
// DIFF FUNCTIONS
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1,
DIFF_INSERT = 1,
DIFF_EQUAL = 0;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean=} optChecklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
*/
DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
// The diff must be complete in up to 1 second.
deadline = new Date().getTime() + 1000;
// Check for null inputs.
if (text1 === null || text2 === null) {
throw new Error("Null input. (DiffMain)");
}
// Check for equality (speedup).
if (text1 === text2) {
if (text1) {
return [[DIFF_EQUAL, text1]];
}
return [];
}
if (typeof optChecklines === "undefined") {
optChecklines = true;
}
checklines = optChecklines;
// Trim off common prefix (speedup).
commonlength = this.diffCommonPrefix(text1, text2);
commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = this.diffCommonSuffix(text1, text2);
commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
diffs = this.diffCompute(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
this.diffCleanupMerge(diffs);
return diffs;
};
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
preIns = false;
// Is there a deletion operation before the last equality.
preDel = false;
// Is there an insertion operation after the last equality.
postIns = false;
// Is there a deletion operation after the last equality.
postDel = false;
while (pointer < diffs.length) {
// Equality found.
if (diffs[pointer][0] === DIFF_EQUAL) {
if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
// Candidate found.
equalities[equalitiesLength++] = pointer;
preIns = postIns;
preDel = postDel;
lastequality = diffs[pointer][1];
} else {
// Not a candidate, and can never become one.
equalitiesLength = 0;
lastequality = null;
}
postIns = postDel = false;
// An insertion or deletion.
} else {
if (diffs[pointer][0] === DIFF_DELETE) {
postDel = true;
} else {
postIns = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
equalitiesLength--; // Throw away the equality we just deleted;
lastequality = null;
if (preIns && preDel) {
// No changes made which could affect previous entry, keep going.
postIns = postDel = true;
equalitiesLength = 0;
} else {
equalitiesLength--; // Throw away the previous equality.
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
postIns = postDel = false;
}
changes = true;
}
}
pointer++;
}
if (changes) {
this.diffCleanupMerge(diffs);
}
};
/**
* Convert a diff array into a pretty HTML report.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {integer} string to be beautified.
* @return {string} HTML representation.
*/
DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
var op,
data,
x,
html = [];
for (x = 0; x < diffs.length; x++) {
op = diffs[x][0]; // Operation (insert, delete, equal)
data = diffs[x][1]; // Text of change.
switch (op) {
case DIFF_INSERT:
html[x] = "<ins>" + escapeText(data) + "</ins>";
break;
case DIFF_DELETE:
html[x] = "<del>" + escapeText(data) + "</del>";
break;
case DIFF_EQUAL:
html[x] = "<span>" + escapeText(data) + "</span>";
break;
}
}
return html.join("");
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
var pointermid, pointermax, pointermin, pointerstart;
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: https://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min(text1.length, text2.length);
pointermid = pointermax;
pointerstart = 0;
while (pointermin < pointermid) {
if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
var pointermid, pointermax, pointermin, pointerend;
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
return 0;
}
// Binary search.
// Performance analysis: https://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min(text1.length, text2.length);
pointermid = pointermax;
pointerend = 0;
while (pointermin < pointermid) {
if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
if (!text1) {
// Just add some text (speedup).
return [[DIFF_INSERT, text2]];
}
if (!text2) {
// Just delete some text (speedup).
return [[DIFF_DELETE, text1]];
}
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
i = longtext.indexOf(shorttext);
if (i !== -1) {
// Shorter text is inside the longer text (speedup).
diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length === 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
// Check to see if the problem can be split in two.
hm = this.diffHalfMatch(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
text1A = hm[0];
text1B = hm[1];
text2A = hm[2];
text2B = hm[3];
midCommon = hm[4];
// Send both pairs off for separate processing.
diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
// Merge the results.
return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
}
if (checklines && text1.length > 100 && text2.length > 100) {
return this.diffLineMode(text1, text2, deadline);
}
return this.diffBisect(text1, text2, deadline);
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
* @private
*/
DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
dmp = this; // 'this' becomes 'window' in a closure.
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diffHalfMatchI(longtext, shorttext, i) {
var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
// Start with a 1/4 length substring at position i as a seed.
seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
j = -1;
bestCommon = "";
while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
if (bestCommon.length < suffixLength + prefixLength) {
bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
bestLongtextA = longtext.substring(0, i - suffixLength);
bestLongtextB = longtext.substring(i + prefixLength);
bestShorttextA = shorttext.substring(0, j - suffixLength);
bestShorttextB = shorttext.substring(j + prefixLength);
}
}
if (bestCommon.length * 2 >= longtext.length) {
return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
// Check again based on the third quarter.
hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
if (!hm1 && !hm2) {
return null;
} else if (!hm2) {
hm = hm1;
} else if (!hm1) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
if (text1.length > text2.length) {
text1A = hm[0];
text1B = hm[1];
text2A = hm[2];
text2B = hm[3];
} else {
text2A = hm[0];
text2B = hm[1];
text1A = hm[2];
text1B = hm[3];
}
midCommon = hm[4];
return [text1A, text1B, text2A, text2B, midCommon];
};
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
// Scan the text on a line-by-line basis first.
a = this.diffLinesToChars(text1, text2);
text1 = a.chars1;
text2 = a.chars2;
linearray = a.lineArray;
diffs = this.DiffMain(text1, text2, false, deadline);
// Convert the diff back to original text.
this.diffCharsToLines(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
this.diffCleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push([DIFF_EQUAL, ""]);
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[pointer][1];
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[pointer][1];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (countDelete >= 1 && countInsert >= 1) {
// Delete the offending records and add the merged ones.
diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
pointer = pointer - countDelete - countInsert;
a = this.DiffMain(textDelete, textInsert, false, deadline);
for (j = a.length - 1; j >= 0; j--) {
diffs.splice(pointer, 0, a[j]);
}
pointer = pointer + a.length;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
pointer++;
}
diffs.pop(); // Remove the dummy entry at the end.
return diffs;
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
maxD = Math.ceil((text1Length + text2Length) / 2);
vOffset = maxD;
vLength = 2 * maxD;
v1 = new Array(vLength);
v2 = new Array(vLength);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (x = 0; x < vLength; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[vOffset + 1] = 0;
v2[vOffset + 1] = 0;
delta = text1Length - text2Length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
front = delta % 2 !== 0;
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
k1start = 0;
k1end = 0;
k2start = 0;
k2end = 0;
for (d = 0; d < maxD; d++) {
// Bail out if deadline is reached.
if (new Date().getTime() > deadline) {
break;
}
// Walk the front path one step.
for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
k1Offset = vOffset + k1;
if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
x1 = v1[k1Offset + 1];
} else {
x1 = v1[k1Offset - 1] + 1;
}
y1 = x1 - k1;
while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
x1++;
y1++;
}
v1[k1Offset] = x1;
if (x1 > text1Length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2Length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
k2Offset = vOffset + delta - k1;
if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - v2[k2Offset];
if (x1 >= x2) {
// Overlap detected.
return this.diffBisectSplit(text1, text2, x1, y1, deadline);
}
}
}
}
// Walk the reverse path one step.
for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
k2Offset = vOffset + k2;
if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
x2 = v2[k2Offset + 1];
} else {
x2 = v2[k2Offset - 1] + 1;
}
y2 = x2 - k2;
while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
x2++;
y2++;
}
v2[k2Offset] = x2;
if (x2 > text1Length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2Length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
k1Offset = vOffset + delta - k2;
if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
x1 = v1[k1Offset];
y1 = vOffset + x1 - k1Offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - x2;
if (x1 >= x2) {
// Overlap detected.
return this.diffBisectSplit(text1, text2, x1, y1, deadline);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
var text1a, text1b, text2a, text2b, diffs, diffsb;
text1a = text1.substring(0, x);
text2a = text2.substring(0, y);
text1b = text1.substring(x);
text2b = text2.substring(y);
// Compute both diffs serially.
diffs = this.DiffMain(text1a, text2a, false, deadline);
diffsb = this.DiffMain(text1b, text2b, false, deadline);
return diffs.concat(diffsb);
};
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
// Number of characters that changed after the equality.
lengthInsertions2 = 0;
lengthDeletions2 = 0;
while (pointer < diffs.length) {
if (diffs[pointer][0] === DIFF_EQUAL) {
// Equality found.
equalities[equalitiesLength++] = pointer;
lengthInsertions1 = lengthInsertions2;
lengthDeletions1 = lengthDeletions2;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = diffs[pointer][1];
} else {
// An insertion or deletion.
if (diffs[pointer][0] === DIFF_INSERT) {
lengthInsertions2 += diffs[pointer][1].length;
} else {
lengthDeletions2 += diffs[pointer][1].length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
// Throw away the equality we just deleted.
equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
equalitiesLength--;
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
// Reset the counters.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = null;
changes = true;
}
}
pointer++;
}
// Normalize the diff.
if (changes) {
this.diffCleanupMerge(diffs);
}
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.length) {
if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
deletion = diffs[pointer - 1][1];
insertion = diffs[pointer][1];
overlapLength1 = this.diffCommonOverlap(deletion, insertion);
overlapLength2 = this.diffCommonOverlap(insertion, deletion);
if (overlapLength1 >= overlapLength2) {
if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
diffs[pointer + 1][1] = insertion.substring(overlapLength1);
pointer++;
}
} else {
if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
diffs[pointer - 1][0] = DIFF_INSERT;
diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
diffs[pointer + 1][0] = DIFF_DELETE;
diffs[pointer + 1][1] = deletion.substring(overlapLength2);
pointer++;
}
}
pointer++;
}
pointer++;
}
};
/**
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
*/
DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
var text1Length, text2Length, textLength, best, length, pattern, found;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
// Eliminate the null case.
if (text1Length === 0 || text2Length === 0) {
return 0;
}
// Truncate the longer string.
if (text1Length > text2Length) {
text1 = text1.substring(text1Length - text2Length);
} else if (text1Length < text2Length) {
text2 = text2.substring(0, text1Length);
}
textLength = Math.min(text1Length, text2Length);
// Quick check for the worst case.
if (text1 === text2) {
return textLength;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: https://neil.fraser.name/news/2010/11/04/
best = 0;
length = 1;
while (true) {
pattern = text1.substring(textLength - length);
found = text2.indexOf(pattern);
if (found === -1) {
return best;
}
length += found;
if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
best = length;
length++;
}
}
};
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
* An object containing the encoded text1, the encoded text2 and
* the array of unique strings.
* The zeroth element of the array of unique strings is intentionally blank.
* @private
*/
DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
var lineArray, lineHash, chars1, chars2;
lineArray = []; // E.g. lineArray[4] === 'Hello\n'
lineHash = {}; // E.g. lineHash['Hello\n'] === 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = "";
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
function diffLinesToCharsMunge(text) {
var chars, lineStart, lineEnd, lineArrayLength, line;
chars = "";
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
lineStart = 0;
lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
lineEnd = text.indexOf("\n", lineStart);
if (lineEnd === -1) {
lineEnd = text.length - 1;
}
line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
var lineHashExists = lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined;
if (lineHashExists) {
chars += String.fromCharCode(lineHash[line]);
} else {
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
}
return chars;
}
chars1 = diffLinesToCharsMunge(text1);
chars2 = diffLinesToCharsMunge(text2);
return {
chars1: chars1,
chars2: chars2,
lineArray: lineArray
};
};
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {!Array.<string>} lineArray Array of unique strings.
* @private
*/
DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
var x, chars, text, y;
for (x = 0; x < diffs.length; x++) {
chars = diffs[x][1];
text = [];
for (y = 0; y < chars.length; y++) {
text[y] = lineArray[chars.charCodeAt(y)];
}
diffs[x][1] = text.join("");
}
};
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[pointer][1];
pointer++;
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[pointer][1];
pointer++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (countDelete + countInsert > 1) {
if (countDelete !== 0 && countInsert !== 0) {
// Factor out any common prefixes.
commonlength = this.diffCommonPrefix(textInsert, textDelete);
if (commonlength !== 0) {
if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
} else {
diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
pointer++;
}
textInsert = textInsert.substring(commonlength);
textDelete = textDelete.substring(commonlength);
}
// Factor out any common suffixies.
commonlength = this.diffCommonSuffix(textInsert, textDelete);
if (commonlength !== 0) {
diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
textInsert = textInsert.substring(0, textInsert.length - commonlength);
textDelete = textDelete.substring(0, textDelete.length - commonlength);
}
}
// Delete the offending records and add the merged ones.
if (countDelete === 0) {
diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
} else if (countInsert === 0) {
diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
} else {
diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
}
pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
} else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
// Merge this equality with the previous one.
diffs[pointer - 1][1] += diffs[pointer][1];
diffs.splice(pointer, 1);
} else {
pointer++;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
}
if (diffs[diffs.length - 1][1] === "") {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
diffPointer = diffs[pointer][1];
position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
// This is a single edit surrounded by equalities.
if (position === diffs[pointer - 1][1]) {
// Shift the edit over the previous equality.
diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
diffs.splice(pointer - 1, 1);
changes = true;
} else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
// Shift the edit over the next equality.
diffs[pointer - 1][1] += diffs[pointer + 1][1];
diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
diffs.splice(pointer + 1, 1);
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes) {
this.diffCleanupMerge(diffs);
}
};
return function (o, n) {
var diff, output, text;
diff = new DiffMatchPatch();
output = diff.DiffMain(o, n);
diff.diffCleanupEfficiency(output);
text = diff.diffPrettyHtml(output);
return text;
};
}();
}((function() { return this; }())));
|
/*!
* json-schema-faker library v0.2.11
* http://json-schema-faker.js.org
* @preserve
*
* Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin
* Released under the MIT license
*
* Date: 2016-02-13 10:19:27.121Z
*/
(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){
var container = require('./util/container'),
traverse = require('./util/traverse'),
formats = require('./util/formats'),
random = require('./util/random'),
merge = require('./util/merge');
var deref = require('deref');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
function generate(schema, refs, ex) {
var $ = deref();
try {
var seen = {};
return traverse($(schema, refs, ex), [], function reduce(sub) {
if (seen[sub.$ref] <= 0) {
delete sub.$ref;
delete sub.oneOf;
delete sub.anyOf;
delete sub.allOf;
return sub;
}
if (typeof sub.$ref === 'string') {
var id = sub.$ref;
delete sub.$ref;
if (!seen[id]) {
// TODO: this should be configurable
seen[id] = random(1, 5);
}
seen[id] -= 1;
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(s) {
merge(sub, reduce(s));
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
var mix = sub.oneOf || sub.anyOf;
delete sub.anyOf;
delete sub.oneOf;
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]);
}
}
return sub;
});
} catch (e) {
if (e.path) {
throw new Error(e.message + ' in ' + '/' + e.path.join('/'));
} else {
throw e;
}
}
}
generate.formats = formats;
// returns itself for chaining
generate.extend = function(name, cb) {
container.set(name, cb);
return generate;
};
module.exports = generate;
},{"./util/container":9,"./util/formats":11,"./util/merge":14,"./util/random":16,"./util/traverse":17,"deref":19}],2:[function(require,module,exports){
var random = require('../util/random'),
traverse = require('../util/traverse'),
hasProps = require('../util/has-props');
var ParseError = require('../util/error');
function unique(path, items, value, sample, resolve) {
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(traverse(value.items || sample, path, resolve));
if (!limit--) {
break;
}
}
return tmp;
}
module.exports = function(value, path, resolve) {
var items = [];
if (!(value.items || value.additionalItems)) {
if (hasProps(value, 'minItems', 'maxItems', 'uniqueItems')) {
throw new ParseError('missing items for ' + JSON.stringify(value), path);
}
return items;
}
if (Array.isArray(value.items)) {
return Array.prototype.concat.apply(items, value.items.map(function(item, key) {
return traverse(item, path.concat(['items', key]), resolve);
}));
}
var length = random(value.minItems, value.maxItems, 1, 5),
sample = typeof value.additionalItems === 'object' ? value.additionalItems : {};
for (var current = items.length; current < length; current += 1) {
items.push(traverse(value.items || sample, path.concat(['items', current]), resolve));
}
if (value.uniqueItems) {
return unique(path.concat(['items']), items, value, sample, resolve);
}
return items;
};
},{"../util/error":10,"../util/has-props":12,"../util/random":16,"../util/traverse":17}],3:[function(require,module,exports){
module.exports = function() {
return Math.random() > 0.5;
};
},{}],4:[function(require,module,exports){
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.
//
module.exports = function(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);
};
},{"./number":6}],5:[function(require,module,exports){
module.exports = function() {
return null;
};
},{}],6:[function(require,module,exports){
var MIN_INTEGER = -100000000,
MAX_INTEGER = 100000000;
var random = require('../util/random'),
string = require('./string');
module.exports = function(value) {
if (value.faker || value.chance) {
return string(value);
}
var multipleOf = value.multipleOf;
var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum,
max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum;
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 (multipleOf) {
return Math.floor(random(min, max) / multipleOf) * multipleOf;
}
if (min > max) {
return NaN;
}
return random({
min: min,
max: max,
hasPrecision: true
});
};
},{"../util/random":16,"./string":8}],7:[function(require,module,exports){
var container = require('../util/container'),
random = require('../util/random'),
words = require('../util/words'),
traverse = require('../util/traverse'),
hasProps = require('../util/has-props');
var RandExp = container.get('randexp'),
randexp = RandExp.randexp;
var ParseError = require('../util/error');
module.exports = function(value, path, resolve) {
var props = {};
if (!(value.properties || value.patternProperties || value.additionalProperties)) {
if (hasProps(value, 'minProperties', 'maxProperties', 'dependencies', 'required')) {
throw new ParseError('missing properties for ' + JSON.stringify(value), path);
}
return props;
}
var reqProps = value.required || [],
allProps = value.properties ? Object.keys(value.properties) : [];
reqProps.forEach(function(key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
}
});
var optProps = allProps.filter(function(prop) {
return reqProps.indexOf(prop) === -1;
});
if (value.patternProperties) {
optProps = Array.prototype.concat.apply(optProps, Object.keys(value.patternProperties));
}
var length = random(value.minProperties, value.maxProperties, 0, optProps.length);
random.shuffle(optProps).slice(0, length).forEach(function(key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
} else {
props[randexp(key)] = value.patternProperties[key];
}
});
var current = Object.keys(props).length,
sample = typeof value.additionalProperties === 'object' ? value.additionalProperties : {};
if (current < length) {
words(length - current).forEach(function(key) {
props[key + randexp('[a-f\\d]{4,7}')] = sample;
});
}
return traverse(props, path.concat(['properties']), resolve);
};
},{"../util/container":9,"../util/error":10,"../util/has-props":12,"../util/random":16,"../util/traverse":17,"../util/words":18}],8:[function(require,module,exports){
var container = require('../util/container');
var faker = container.get('faker'),
chance = container.get('chance'),
RandExp = container.get('randexp'),
randexp = RandExp.randexp;
var words = require('../util/words'),
random = require('../util/random'),
formats = require('../util/formats');
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: '[abcdef\\d]{4}(:[abcdef\\d]{4}){7}',
uri: '[a-zA-Z][a-zA-Z0-9+-.]*'
};
function get(obj, key) {
var parts = key.split('.');
while (parts.length) {
var prop = parts.shift();
if (!obj[prop]) {
break;
}
obj = obj[prop];
}
return obj;
}
function thunk() {
return words().join(' ');
}
function generate(value) {
if (value.use) {
var args = [],
path = value.key;
if (typeof path === 'object') {
path = Object.keys(path)[0];
if (Array.isArray(value.key[path])) {
args = value.key[path];
} else {
args.push(value.key[path]);
}
}
var gen = get(value.gen, path);
if (typeof gen !== 'function') {
throw new Error('unknown ' + value.use + '-generator for ' + JSON.stringify(value.key));
}
return gen.apply(value.gen, args);
}
switch (value.format) {
case 'date-time':
return new Date(random(0, 100000000000000)).toISOString();
case 'email':
case 'hostname':
case 'ipv6':
case 'uri':
return randexp(regexps[value.format]).replace(/\{(\w+)\}/, function(matches, key) {
return randexp(regexps[key]);
});
case 'ipv4':
return [0, 0, 0, 0].map(function() {
return random(0, 255);
}).join('.');
case 'regex':
// TODO: discuss
return '.+?';
default:
var callback = formats(value.format);
if (typeof callback !== 'function') {
throw new Error('unknown generator for ' + JSON.stringify(value.format));
}
var generators = {
faker: faker,
chance: chance,
randexp: randexp
};
return callback(generators, value);
}
}
module.exports = function(value) {
if (value.faker || value.chance) {
return generate({
use: value.faker ? 'faker' : 'chance',
gen: value.faker ? faker : chance,
key: value.faker || value.chance
});
}
if (value.format) {
return generate(value);
}
if (value.pattern) {
return randexp(value.pattern);
}
var min = Math.max(0, value.minLength || 0),
max = random(min, value.maxLength || 140);
var sample = thunk();
while (sample.length < min) {
sample += thunk();
}
if (sample.length > max) {
sample = sample.substr(0, max);
}
return sample;
};
},{"../util/container":9,"../util/formats":11,"../util/random":16,"../util/words":18}],9:[function(require,module,exports){
// static requires - handle both initial dependency load (deps will be available
// among other modules) as well as they will be included by browserify AST
var container = {
faker: null,
chance: null,
// randexp is required for "pattern" values
randexp: require('randexp')
};
module.exports = {
set: function(name, callback) {
if (typeof container[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency is not allowed.');
}
container[name] = callback(container[name]);
},
get: function(name) {
if (typeof container[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency doesn\'t exist.');
}
return container[name];
}
};
},{"randexp":153}],10:[function(require,module,exports){
function ParseError(message, path) {
this.message = message;
this.path = path;
this.name = 'ParseError';
}
ParseError.prototype = Error.prototype;
module.exports = ParseError;
},{}],11:[function(require,module,exports){
var registry = {};
module.exports = function(name, callback) {
if (callback) {
registry[name] = callback;
} else if (typeof name === 'object') {
for (var method in name) {
registry[method] = name[method];
}
} else if (name) {
return registry[name];
}
return registry;
};
},{}],12:[function(require,module,exports){
module.exports = function(obj) {
return Array.prototype.slice.call(arguments, 1).filter(function(key) {
return typeof obj[key] !== 'undefined';
}).length > 0;
};
},{}],13:[function(require,module,exports){
var inferredProperties = {
array: [
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems'
],
integer: [
'exclusiveMaximum',
'exclusiveMinimum',
'maximum',
'minimum',
'multipleOf'
],
object: [
'additionalProperties',
'dependencies',
'maxProperties',
'minProperties',
'patternProperties',
'properties',
'required'
],
string: [
'maxLength',
'menlength',
'pattern'
]
};
var subschemaProperties = [
'additionalItems', 'items', 'additionalProperties', 'dependencies', 'patternProperties', 'properties'
];
inferredProperties.number = inferredProperties.integer;
function mayHaveType(obj, path, props) {
return Object.keys(obj).filter(function(prop) {
// 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)
if (props.indexOf(prop) > -1 && subschemaProperties.indexOf(path[path.length - 1]) === -1) {
return true;
}
}).length > 0;
}
module.exports = function(obj, path) {
for (var type in inferredProperties) {
if (mayHaveType(obj, path, inferredProperties[type])) {
return type;
}
}
};
},{}],14:[function(require,module,exports){
var merge;
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;
}
merge = module.exports = function(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;
};
},{}],15:[function(require,module,exports){
module.exports = {
array: require('../types/array'),
boolean: require('../types/boolean'),
integer: require('../types/integer'),
number: require('../types/number'),
null: require('../types/null'),
object: require('../types/object'),
string: require('../types/string')
};
},{"../types/array":2,"../types/boolean":3,"../types/integer":4,"../types/null":5,"../types/number":6,"../types/object":7,"../types/string":8}],16:[function(require,module,exports){
var random = module.exports = function(min, max, defMin, defMax) {
var hasPrecision = false;
if (typeof min === 'object') {
hasPrecision = min.hasPrecision;
max = min.max;
defMin = min.defMin;
defMax = min.defMax;
min = min.min;
}
defMin = typeof defMin === 'undefined' ? random.MIN_NUMBER : defMin;
defMax = typeof defMax === 'undefined' ? random.MAX_NUMBER : defMax;
min = typeof min === 'undefined' ? defMin : min;
max = typeof max === 'undefined' ? defMax : max;
if (max < min) {
max += min;
}
var number = Math.random() * (max - min) + min;
if (!hasPrecision) {
return parseInt(number, 10);
}
return number;
};
random.shuffle = function(obj) {
var copy = obj.slice(),
length = obj.length;
for (; length > 0;) {
var key = Math.floor(Math.random() * length),
tmp = copy[--length];
copy[length] = copy[key];
copy[key] = tmp;
}
return copy;
};
random.pick = function(obj) {
return obj[Math.floor(Math.random() * obj.length)];
};
random.MIN_NUMBER = -100;
random.MAX_NUMBER = 100;
},{}],17:[function(require,module,exports){
var random = require('./random');
var ParseError = require('./error');
var inferredType = require('./inferred');
var primitives = null;
function traverse(obj, path, resolve) {
resolve(obj);
var copy = {};
if (Array.isArray(obj)) {
copy = [];
}
if (Array.isArray(obj.enum)) {
return random.pick(obj.enum);
}
var type = obj.type;
if (Array.isArray(type)) {
type = random.pick(type);
} else if (typeof type === 'undefined') {
// Attempt to infer the type
type = inferredType(obj, path) || type;
}
if (typeof type === 'string') {
if (!primitives[type]) {
throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type']));
}
try {
return primitives[type](obj, path, resolve);
} catch (e) {
if (typeof e.path === 'undefined') {
throw new ParseError(e.message, path);
}
throw e;
}
}
for (var prop in obj) {
if (typeof obj[prop] === 'object' && prop !== 'definitions') {
copy[prop] = traverse(obj[prop], path.concat([prop]), resolve);
} else {
copy[prop] = obj[prop];
}
}
return copy;
}
module.exports = function() {
primitives = primitives || require('./primitives');
return traverse.apply(null, arguments);
};
},{"./error":10,"./inferred":13,"./primitives":15,"./random":16}],18:[function(require,module,exports){
var random = require('./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(' ');
module.exports = function(min, max) {
var words = random.shuffle(LIPSUM_WORDS),
length = random(min || 1, Math.min(LIPSUM_WORDS.length, max || min || 5));
return words.slice(0, length);
};
},{"./random":16}],19:[function(require,module,exports){
'use strict';
var $ = require('./util/uri-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":21,"./util/normalize-schema":22,"./util/resolve-schema":23,"./util/uri-helpers":24}],20:[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;
};
},{}],21:[function(require,module,exports){
'use strict';
var $ = require('./uri-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;
};
},{"./uri-helpers":24}],22:[function(require,module,exports){
'use strict';
var $ = require('./uri-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' && !(key === 'enum' || key === 'required')) {
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":20,"./uri-helpers":24}],23:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
var find = require('./find-reference');
var deepExtend = require('deep-extend');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
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' && !isKey(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":21,"./uri-helpers":24,"deep-extend":25}],24:[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];
}
module.exports = {
isURL: isURL,
parseURI: parseURI,
resolveURL: resolveURL,
getDocumentURI: getDocumentURI
};
},{}],25:[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;
}
},{}],26:[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;
},{}],27:[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;
},{}],28:[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;
},{}],29:[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;
},{}],30:[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;
},{}],31:[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;
},{}],32:[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;
},{}],33:[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;
},{}],34:[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;
},{}],35:[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":26,"./commerce":27,"./company":28,"./date":29,"./fake":30,"./finance":31,"./hacker":32,"./helpers":33,"./image":34,"./internet":36,"./lorem":145,"./name":146,"./phone_number":147,"./random":148}],36:[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":151,"../vendor/user-agent":152}],37:[function(require,module,exports){
module["exports"] = [
"#####",
"####",
"###"
];
},{}],38:[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}"
];
},{}],39:[function(require,module,exports){
module["exports"] = [
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port"
];
},{}],40:[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"
];
},{}],41:[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"
];
},{}],42:[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"
];
},{}],43:[function(require,module,exports){
module["exports"] = [
"Avon",
"Bedfordshire",
"Berkshire",
"Borders",
"Buckinghamshire",
"Cambridgeshire"
];
},{}],44:[function(require,module,exports){
module["exports"] = [
"United States of America"
];
},{}],45:[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":37,"./city":38,"./city_prefix":39,"./city_suffix":40,"./country":41,"./country_code":42,"./county":43,"./default_country":44,"./postcode":46,"./postcode_by_state":47,"./secondary_address":48,"./state":49,"./state_abbr":50,"./street_address":51,"./street_name":52,"./street_suffix":53,"./time_zone":54}],46:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-####"
];
},{}],47:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"dup":46}],48:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"Suite ###"
];
},{}],49:[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"
];
},{}],50:[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"
];
},{}],51:[function(require,module,exports){
module["exports"] = [
"#{building_number} #{street_name}"
];
},{}],52:[function(require,module,exports){
module["exports"] = [
"#{Name.first_name} #{street_suffix}",
"#{Name.last_name} #{street_suffix}"
];
},{}],53:[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"
];
},{}],54:[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"
];
},{}],55:[function(require,module,exports){
module["exports"] = [
"#{Name.name}",
"#{Company.name}"
];
},{}],56:[function(require,module,exports){
var app = {};
module['exports'] = app;
app.name = require("./name");
app.version = require("./version");
app.author = require("./author");
},{"./author":55,"./name":57,"./version":58}],57:[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"
];
},{}],58:[function(require,module,exports){
module["exports"] = [
"0.#.#",
"0.##",
"#.##",
"#.#",
"#.#.#"
];
},{}],59:[function(require,module,exports){
module["exports"] = [
"2011-10-12",
"2012-11-12",
"2015-11-11",
"2013-9-12"
];
},{}],60:[function(require,module,exports){
module["exports"] = [
"1234-2121-1221-1211",
"1212-1221-1121-1234",
"1211-1221-1234-2201",
"1228-1221-1221-1431"
];
},{}],61:[function(require,module,exports){
module["exports"] = [
"visa",
"mastercard",
"americanexpress",
"discover"
];
},{}],62:[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":59,"./credit_card_numbers":60,"./credit_card_types":61}],63:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####"
];
},{}],64:[function(require,module,exports){
var cell_phone = {};
module['exports'] = cell_phone;
cell_phone.formats = require("./formats");
},{"./formats":63}],65:[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"
];
},{}],66:[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"
];
},{}],67:[function(require,module,exports){
var commerce = {};
module['exports'] = commerce;
commerce.color = require("./color");
commerce.department = require("./department");
commerce.product_name = require("./product_name");
},{"./color":65,"./department":66,"./product_name":68}],68:[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"
]
};
},{}],69:[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"
];
},{}],70:[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"
];
},{}],71:[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"
];
},{}],72:[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"
];
},{}],73:[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"
];
},{}],74:[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":69,"./bs_adjective":70,"./bs_noun":71,"./bs_verb":72,"./descriptor":73,"./name":75,"./noun":76,"./suffix":77}],75:[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}"
];
},{}],76:[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"
];
},{}],77:[function(require,module,exports){
module["exports"] = [
"Inc",
"and Sons",
"LLC",
"Group"
];
},{}],78:[function(require,module,exports){
module["exports"] = [
"/34##-######-####L/",
"/37##-######-####L/"
];
},{}],79:[function(require,module,exports){
module["exports"] = [
"/30[0-5]#-######-###L/",
"/368#-######-###L/"
];
},{}],80:[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/"
];
},{}],81:[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":78,"./diners_club":79,"./discover":80,"./jcb":82,"./laser":83,"./maestro":84,"./mastercard":85,"./solo":86,"./switch":87,"./visa":88}],82:[function(require,module,exports){
module["exports"] = [
"/3528-####-####-###L/",
"/3529-####-####-###L/",
"/35[3-8]#-####-####-###L/"
];
},{}],83:[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/"
];
},{}],84:[function(require,module,exports){
module["exports"] = [
"/50#{9,16}L/",
"/5[6-8]#{9,16}L/",
"/56##{9,16}L/"
];
},{}],85:[function(require,module,exports){
module["exports"] = [
"/5[1-5]##-####-####-###L/",
"/6771-89##-####-###L/"
];
},{}],86:[function(require,module,exports){
module["exports"] = [
"/6767-####-####-###L/",
"/6767-####-####-####-#L/",
"/6767-####-####-####-##L/"
];
},{}],87:[function(require,module,exports){
module["exports"] = [
"/6759-####-####-###L/",
"/6759-####-####-####-#L/",
"/6759-####-####-####-##L/"
];
},{}],88:[function(require,module,exports){
module["exports"] = [
"/4###########L/",
"/4###-####-####-###L/"
];
},{}],89:[function(require,module,exports){
var date = {};
module["exports"] = date;
date.month = require("./month");
date.weekday = require("./weekday");
},{"./month":90,"./weekday":91}],90:[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"
]
};
},{}],91:[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"
]
};
},{}],92:[function(require,module,exports){
module["exports"] = [
"Checking",
"Savings",
"Money Market",
"Investment",
"Home Loan",
"Credit Card",
"Auto Loan",
"Personal Loan"
];
},{}],93:[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": ""
}
};
},{}],94:[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":92,"./currency":93,"./transaction_type":95}],95:[function(require,module,exports){
module["exports"] = [
"deposit",
"withdrawal",
"payment",
"invoice"
];
},{}],96:[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"
];
},{}],97:[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"
];
},{}],98:[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":96,"./adjective":97,"./ingverb":99,"./noun":100,"./verb":101}],99:[function(require,module,exports){
module["exports"] = [
"backing up",
"bypassing",
"hacking",
"overriding",
"compressing",
"copying",
"navigating",
"indexing",
"connecting",
"generating",
"quantifying",
"calculating",
"synthesizing",
"transmitting",
"programming",
"parsing"
];
},{}],100:[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"
];
},{}],101:[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"
];
},{}],102:[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":45,"./app":56,"./business":62,"./cell_phone":64,"./commerce":67,"./company":74,"./credit_card":81,"./date":89,"./finance":94,"./hacker":98,"./internet":106,"./lorem":107,"./name":111,"./phone_number":118,"./team":120}],103:[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"
];
},{}],104:[function(require,module,exports){
module["exports"] = [
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],105:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com"
];
},{}],106:[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":103,"./domain_suffix":104,"./free_email":105}],107:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
lorem.supplemental = require("./supplemental");
},{"./supplemental":108,"./words":109}],108:[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"
];
},{}],109:[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"
];
},{}],110:[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"
];
},{}],111:[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":110,"./last_name":112,"./name":113,"./prefix":114,"./suffix":115,"./title":116}],112:[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"
];
},{}],113:[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}"
];
},{}],114:[function(require,module,exports){
module["exports"] = [
"Mr.",
"Mrs.",
"Ms.",
"Miss",
"Dr."
];
},{}],115:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Sr.",
"I",
"II",
"III",
"IV",
"V",
"MD",
"DDS",
"PhD",
"DVM"
];
},{}],116:[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"
]
};
},{}],117:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-#### x###",
"(###) ###-#### x###",
"1-###-###-#### x###",
"###.###.#### x###",
"###-###-#### x####",
"(###) ###-#### x####",
"1-###-###-#### x####",
"###.###.#### x####",
"###-###-#### x#####",
"(###) ###-#### x#####",
"1-###-###-#### x#####",
"###.###.#### x#####"
];
},{}],118:[function(require,module,exports){
var phone_number = {};
module['exports'] = phone_number;
phone_number.formats = require("./formats");
},{"./formats":117}],119:[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"
];
},{}],120:[function(require,module,exports){
var team = {};
module['exports'] = team;
team.creature = require("./creature");
team.name = require("./name");
},{"./creature":119,"./name":121}],121:[function(require,module,exports){
module["exports"] = [
"#{Address.state} #{creature}"
];
},{}],122:[function(require,module,exports){
module["exports"] = [
"####",
"###",
"##"
];
},{}],123:[function(require,module,exports){
module["exports"] = [
"#{city_prefix}"
];
},{}],124:[function(require,module,exports){
module["exports"] = [
"Bondi",
"Burleigh Heads",
"Carlton",
"Fitzroy",
"Fremantle",
"Glenelg",
"Manly",
"Noosa",
"Stones Corner",
"St Kilda",
"Surry Hills",
"Yarra Valley"
];
},{}],125:[function(require,module,exports){
module["exports"] = [
"Australia"
];
},{}],126:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.street_root = require("./street_root");
address.street_name = require("./street_name");
address.city_prefix = require("./city_prefix");
address.city = require("./city");
address.state_abbr = require("./state_abbr");
address.region = require("./region");
address.state = require("./state");
address.postcode = require("./postcode");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.default_country = require("./default_country");
},{"./building_number":122,"./city":123,"./city_prefix":124,"./default_country":125,"./postcode":127,"./region":128,"./state":129,"./state_abbr":130,"./street_name":131,"./street_root":132,"./street_suffix":133}],127:[function(require,module,exports){
module["exports"] = [
"0###",
"2###",
"3###",
"4###",
"5###",
"6###",
"7###"
];
},{}],128:[function(require,module,exports){
module["exports"] = [
"South East Queensland",
"Wide Bay Burnett",
"Margaret River",
"Port Pirie",
"Gippsland",
"Elizabeth",
"Barossa"
];
},{}],129:[function(require,module,exports){
module["exports"] = [
"New South Wales",
"Queensland",
"Northern Territory",
"South Australia",
"Western Australia",
"Tasmania",
"Australian Capital Territory",
"Victoria"
];
},{}],130:[function(require,module,exports){
module["exports"] = [
"NSW",
"QLD",
"NT",
"SA",
"WA",
"TAS",
"ACT",
"VIC"
];
},{}],131:[function(require,module,exports){
module["exports"] = [
"#{street_root}"
];
},{}],132:[function(require,module,exports){
module["exports"] = [
"Ramsay Street",
"Bonnie Doon",
"Cavill Avenue",
"Queen Street"
];
},{}],133:[function(require,module,exports){
module["exports"] = [
"Avenue",
"Boulevard",
"Circle",
"Circuit",
"Court",
"Crescent",
"Crest",
"Drive",
"Estate Dr",
"Grove",
"Hill",
"Island",
"Junction",
"Knoll",
"Lane",
"Loop",
"Mall",
"Manor",
"Meadow",
"Mews",
"Parade",
"Parkway",
"Pass",
"Place",
"Plaza",
"Ridge",
"Road",
"Run",
"Square",
"Station St",
"Street",
"Summit",
"Terrace",
"Track",
"Trail",
"View Rd",
"Way"
];
},{}],134:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
},{"./suffix":135}],135:[function(require,module,exports){
module["exports"] = [
"Pty Ltd",
"and Sons",
"Corp",
"Group",
"Brothers",
"Partners"
];
},{}],136:[function(require,module,exports){
var en_au_ocker = {};
module['exports'] = en_au_ocker;
en_au_ocker.title = "Australia Ocker (English)";
en_au_ocker.name = require("./name");
en_au_ocker.company = require("./company");
en_au_ocker.internet = require("./internet");
en_au_ocker.address = require("./address");
en_au_ocker.phone_number = require("./phone_number");
},{"./address":126,"./company":134,"./internet":138,"./name":140,"./phone_number":144}],137:[function(require,module,exports){
module["exports"] = [
"com.au",
"com",
"net.au",
"net",
"org.au",
"org"
];
},{}],138:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.domain_suffix = require("./domain_suffix");
},{"./domain_suffix":137}],139:[function(require,module,exports){
module["exports"] = [
"Charlotte",
"Ava",
"Chloe",
"Emily",
"Olivia",
"Zoe",
"Lily",
"Sophie",
"Amelia",
"Sofia",
"Ella",
"Isabella",
"Ruby",
"Sienna",
"Mia+3",
"Grace",
"Emma",
"Ivy",
"Layla",
"Abigail",
"Isla",
"Hannah",
"Zara",
"Lucy",
"Evie",
"Annabelle",
"Madison",
"Alice",
"Georgia",
"Maya",
"Madeline",
"Audrey",
"Scarlett",
"Isabelle",
"Chelsea",
"Mila",
"Holly",
"Indiana",
"Poppy",
"Harper",
"Sarah",
"Alyssa",
"Jasmine",
"Imogen",
"Hayley",
"Pheobe",
"Eva",
"Evelyn",
"Mackenzie",
"Ayla",
"Oliver",
"Jack",
"Jackson",
"William",
"Ethan",
"Charlie",
"Lucas",
"Cooper",
"Lachlan",
"Noah",
"Liam",
"Alexander",
"Max",
"Isaac",
"Thomas",
"Xavier",
"Oscar",
"Benjamin",
"Aiden",
"Mason",
"Samuel",
"James",
"Levi",
"Riley",
"Harrison",
"Ryan",
"Henry",
"Jacob",
"Joshua",
"Leo",
"Zach",
"Harry",
"Hunter",
"Flynn",
"Archie",
"Tyler",
"Elijah",
"Hayden",
"Jayden",
"Blake",
"Archer",
"Ashton",
"Sebastian",
"Zachery",
"Lincoln",
"Mitchell",
"Luca",
"Nathan",
"Kai",
"Connor",
"Tom",
"Nigel",
"Matt",
"Sean"
];
},{}],140:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.ocker_first_name = require("./ocker_first_name");
},{"./first_name":139,"./last_name":141,"./ocker_first_name":142}],141:[function(require,module,exports){
module["exports"] = [
"Smith",
"Jones",
"Williams",
"Brown",
"Wilson",
"Taylor",
"Morton",
"White",
"Martin",
"Anderson",
"Thompson",
"Nguyen",
"Thomas",
"Walker",
"Harris",
"Lee",
"Ryan",
"Robinson",
"Kelly",
"King",
"Rausch",
"Ridge",
"Connolly",
"LeQuesne"
];
},{}],142:[function(require,module,exports){
module["exports"] = [
"Bazza",
"Bluey",
"Davo",
"Johno",
"Shano",
"Shazza"
];
},{}],143:[function(require,module,exports){
module["exports"] = [
"0# #### ####",
"+61 # #### ####",
"04## ### ###",
"+61 4## ### ###"
];
},{}],144:[function(require,module,exports){
arguments[4][118][0].apply(exports,arguments)
},{"./formats":143,"dup":118}],145:[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;
},{}],146:[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;
},{}],147:[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;
},{}],148:[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":150}],149:[function(require,module,exports){
var Faker = require('../lib');
var faker = new Faker({ locale: 'en_au_ocker', localeFallback: 'en' });
faker.locales['en_au_ocker'] = require('../lib/locales/en_au_ocker');
faker.locales['en'] = require('../lib/locales/en');
module['exports'] = faker;
},{"../lib":35,"../lib/locales/en":102,"../lib/locales/en_au_ocker":136}],150:[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);
}
},{}],151:[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));
},{}],152:[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]);
};
},{}],153:[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);
if (token.type === ret.types.RANGE) return new DRange(token.from, token.to);
if (token.type === ret.types.SET) {
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;
}
}
throw new Error('unexpandable token type: ' + token.type);
}
/**
* @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;
if (typeof regexp.max === 'number') {
this.max = regexp.max;
}
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;
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;
}
}
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:
if (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 expanded_set = expand.call(this, token);
if (!expanded_set.length) return '';
return String.fromCharCode(randSelect.call(this, expanded_set));
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":154,"ret":155}],154:[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;
},{}],155:[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) {
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":156,"./sets":157,"./types":158,"./util":159}],156:[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":158}],157:[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":158}],158:[function(require,module,exports){
module.exports = {
ROOT : 0
, GROUP : 1
, POSITION : 2
, SET : 3
, RANGE : 4
, REPETITION : 5
, REFERENCE : 6
, CHAR : 7
};
},{}],159:[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) {
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) :
eslsh ? SLSH[eslsh] : undefined;
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) {
var tokens = []
, regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g
, 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":157,"./types":158}],"json-schema-faker":[function(require,module,exports){
module.exports = require('../lib/jsf')
.extend('faker', function() {
try {
return require('faker/locale/en_au_ocker');
} catch (e) {
return null;
}
});
},{"../lib/jsf":1,"faker/locale/en_au_ocker":149}]},{},["json-schema-faker"])("json-schema-faker")
});
|
function pathinfo (path, options) {
// http://kevin.vanzonneveld.net
// + original by: Nate
// + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Timo
// % note 1: Inspired by actual PHP source: php5-5.2.6/ext/standard/string.c line #1559
// % note 1: The way the bitwise arguments are handled allows for greater flexibility
// % note 1: & compatability. We might even standardize this code and use a similar approach for
// % note 1: other bitwise PHP functions
// % note 2: php.js tries very hard to stay away from a core.js file with global dependencies, because we like
// % note 2: that you can just take a couple of functions and be on your way.
// % note 2: But by way we implemented this function, if you want you can still declare the PATHINFO_*
// % note 2: yourself, and then you can use: pathinfo('/www/index.html', PATHINFO_BASENAME | PATHINFO_EXTENSION);
// % note 2: which makes it fully compliant with PHP syntax.
// - depends on: dirname
// - depends on: basename
// * example 1: pathinfo('/www/htdocs/index.html', 1);
// * returns 1: '/www/htdocs'
// * example 2: pathinfo('/www/htdocs/index.html', 'PATHINFO_BASENAME');
// * returns 2: 'index.html'
// * example 3: pathinfo('/www/htdocs/index.html', 'PATHINFO_EXTENSION');
// * returns 3: 'html'
// * example 4: pathinfo('/www/htdocs/index.html', 'PATHINFO_FILENAME');
// * returns 4: 'index'
// * example 5: pathinfo('/www/htdocs/index.html', 2 | 4);
// * returns 5: {basename: 'index.html', extension: 'html'}
// * example 6: pathinfo('/www/htdocs/index.html', 'PATHINFO_ALL');
// * returns 6: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
// * example 7: pathinfo('/www/htdocs/index.html');
// * returns 7: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
// Working vars
var opt = '',
optName = '',
optTemp = 0,
tmp_arr = {},
cnt = 0,
i = 0;
var have_basename = false,
have_extension = false,
have_filename = false;
// Input defaulting & sanitation
if (!path) {
return false;
}
if (!options) {
options = 'PATHINFO_ALL';
}
// Initialize binary arguments. Both the string & integer (constant) input is
// allowed
var OPTS = {
'PATHINFO_DIRNAME': 1,
'PATHINFO_BASENAME': 2,
'PATHINFO_EXTENSION': 4,
'PATHINFO_FILENAME': 8,
'PATHINFO_ALL': 0
};
// PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate)
for (optName in OPTS) {
OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName];
}
if (typeof options !== 'number') { // Allow for a single string or an array of string flags
options = [].concat(options);
for (i = 0; i < options.length; i++) {
// Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
if (OPTS[options[i]]) {
optTemp = optTemp | OPTS[options[i]];
}
}
options = optTemp;
}
// Internal Functions
var __getExt = function (path) {
var str = path + '';
var dotP = str.lastIndexOf('.') + 1;
return !dotP ? false : dotP !== str.length ? str.substr(dotP) : '';
};
// Gather path infos
if (options & OPTS.PATHINFO_DIRNAME) {
var dirname = this.dirname(path);
tmp_arr.dirname = dirname === path ? '.' : dirname;
}
if (options & OPTS.PATHINFO_BASENAME) {
if (false === have_basename) {
have_basename = this.basename(path);
}
tmp_arr.basename = have_basename;
}
if (options & OPTS.PATHINFO_EXTENSION) {
if (false === have_basename) {
have_basename = this.basename(path);
}
if (false === have_extension) {
have_extension = __getExt(have_basename);
}
if (false !== have_extension) {
tmp_arr.extension = have_extension;
}
}
if (options & OPTS.PATHINFO_FILENAME) {
if (false === have_basename) {
have_basename = this.basename(path);
}
if (false === have_extension) {
have_extension = __getExt(have_basename);
}
if (false === have_filename) {
have_filename = have_basename.slice(0, have_basename.length - (have_extension ? have_extension.length + 1 : have_extension === false ? 0 : 1));
}
tmp_arr.filename = have_filename;
}
// If array contains only 1 element: return string
cnt = 0;
for (opt in tmp_arr) {
cnt++;
}
if (cnt == 1) {
return tmp_arr[opt];
}
// Return full-blown array
return tmp_arr;
}
|
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatable-paginator",function(e){e.Intl.add("datatable-paginator","",{first:"First",prev:"Previous",next:"Next",last:"Last",goToLabel:"Page:",goToAction:"Go",perPage:"Rows:",showAll:"Show All"})},"3.16.0");
|
/**
* Catalan translation
* @author Maria Consuelo Bravo <consolbravo@gmail.com>
* @version 2010-12-21
*/
(function($) {
elRTE.prototype.i18Messages.ca = {
'_translator' : 'Maria Consuelo Bravo <consolbravo@gmail.com>',
'_translation' : 'Catalan translation',
'Editor' : 'Editor',
'Source' : 'Codi font',
// Panel Name
'Copy/Pase' : 'Copia/Enganxa',
'Undo/Redo' : 'Desfés/Restaura',
'Text styles' : 'Estils de text',
'Colors' : 'Colors',
'Alignment' : 'Alineació',
'Indent/Outdent' : 'Augmenta/Redueix el sagnat',
'Text format' : 'Format de text',
'Lists' : 'Llistes',
'Misc elements' : 'Diversos',
'Links' : 'Enllaços',
'Images' : 'Imatges',
'Media' : 'Multimèdia',
'Tables' : 'Taules',
'File manager (elFinder)' : 'Gestor d\'arxius',
// button names
'Save' : 'Desa',
'Copy' : 'Copia',
'Cut' : 'Retalla',
'Paste' : 'Enganxa',
'Paste only text' : 'Enganxa només el text',
'Paste formatted text' : 'Enganxa el text formatat',
'Clean format' : 'Neteja el format',
'Undo last action' : 'Desfés l\'última acció',
'Redo previous action' : 'Restaura l\'última acció',
'Bold' : 'Negreta',
'Italic' : 'Cursiva',
'Underline' : 'Subratllat',
'Strikethrough' : 'Ratllat',
'Superscript' : 'Superíndex',
'Subscript' : 'Subíndex',
'Align left' : 'Alinea a l\'esquerra',
'Ailgn right' : 'Alinea a la dreta',
'Align center' : 'Centra',
'Align full' : 'Justifica',
'Font color' : 'Color del text',
'Background color' : 'Color de fons',
'Indent' : 'Augmenta el sagnat',
'Outdent' : 'Redueix el sagnat',
'Format' : 'Format',
'Font size' : 'Mida de la lletra',
'Font' : 'Font',
'Ordered list' : 'Llista ordenada',
'Unordered list' : 'Llista desordenada',
'Horizontal rule' : 'Línia horitzontal',
'Blockquote' : 'Cita',
'Block element (DIV)' : 'Elements de bloc (DIV)',
'Link' : 'Enllaç',
'Delete link' : 'Elimina l\'enllaç',
'Bookmark' : 'Marcador',
'Image' : 'Imatge',
'Table' : 'Taula',
'Delete table' : 'Elimina la taula',
'Insert row before' : 'Insereix fila abans',
'Insert row after' : 'Insereix fila després',
'Delete row' : 'Elimina la fila',
'Insert column before' : 'Insereix columna abans',
'Insert column after' : 'Insereix columna després',
'Delete column' : 'Elimina la columna',
'Merge table cells' : 'Fusiona les cel·les',
'Split table cell' : 'Divideix la cel·la',
'Toggle display document structure' : 'Pantalla d\'estructura del document',
'Table cell properties' : 'Propietats de la cel·la',
'Table properties' : 'Propietats de la taula',
'Toggle full screen mode' : 'Pantalla completa',
'Open file manager' : 'Obre el gestor d\'arxius',
'Non breakable space' : 'Espai indivisible',
'Stop element floating' : 'Atura l\'element flotant',
// dialogs
'Warning' : 'Advertència',
'Properies' : 'Propietats',
'Popup' : 'Finestra emergent',
'Advanced' : 'Avançat',
'Events' : 'Incidències',
'Width' : 'Amplada',
'Height' : 'Alçada',
'Left' : 'Esquerra',
'Center' : 'Centrat',
'Right' : 'Dreta',
'Border' : 'Vora',
'Background' : 'Fons',
'Css class' : 'Classe CSS',
'Css style' : 'Estil CSS',
'No' : 'No',
'Title' : 'Títol',
'Script direction' : 'Adreça de l\'script',
'Language' : 'Idioma',
'Charset' : 'Charset',
'Not set' : 'No establert',
'Left to right' : 'D\'esquerra a dreta',
'Right to left' : 'De dreta a esquerra',
'In this window' : 'En aquesta finestra (_self)',
'In new window (_blank)' : 'En una finestra nova (_blank)',
'In new parent window (_parent)' : 'En una finestra mare nova (_parent)',
'In top frame (_top)' : 'En un marc superior (_top)',
'URL' : 'URL',
'Open in' : 'Obre a',
// copy
'This operation is disabled in your browser on security reason. Use shortcut instead.' : 'Per raons de seguretat aquesta operació no està disponible en el seu navegador. Utilitzi una drecera de teclat.',
// format
'Heading 1' : 'Encapçalament 1',
'Heading 2' : ' Encapçalament 2',
'Heading 3' : ' Encapçalament 3',
'Heading 4' : ' Encapçalament 4',
'Heading 5' : ' Encapçalament 5',
'Heading 6' : ' Encapçalament 6',
'Paragraph' : 'Paràgraf',
'Address' : 'Adreça',
'Preformatted' : 'Preformatat',
// font size
'Small (8pt)' : 'Petit (8pt)',
'Small (10px)' : 'Petit (10px)',
'Small (12pt)' : 'Petit (12pt)',
'Normal (14pt)' : 'Normal (14pt)',
'Large (18pt)' : 'Gran (18pt)',
'Large (24pt)' : 'Gran (24pt)',
'Large (36pt)' : 'Gran (36pt)',
// bookmark
'Bookmark name' : 'Nom del marcador',
// link
'Link URL' : 'URL de l\'enllaç',
'Target' : 'Objectiu',
'Open link in popup window' : 'Obre l\'enllaç en una finestra emergent',
'Window name' : 'Nom de la finestra',
'Window size' : 'Mida de la finestra',
'Window position' : 'Posició de la finestra',
'Location bar' : 'Barra d\'adreces',
'Menu bar' : 'Barra de menús',
'Toolbar' : 'Barra d\'eines',
'Scrollbars' : 'Barres de desplaçament',
'Status bar' : 'Barra d\'estat',
'Resizable' : 'Redimensionable',
'Depedent' : 'Dependent (Netscape)',
'Add return false' : 'Afegeix (return false)',
'Target MIME type' : 'Destí de tipus MIME',
'Relationship page to target (rel)' : 'Relació de la pàgina amb l\'enllaç (rel)',
'Relationship target to page (rev)' : 'Relació de l\'enllaç amb la pàgina (rev)',
'Tab index' : 'Índex de tabulador',
'Access key' : 'Tecla d\'accés',
// image
'Size' : 'Mida',
'Preview' : 'Previsualització',
'Margins' : 'Marges',
'Alt text' : 'Text alternatiu',
'Image URL' : 'URL de la imatge',
// table
'Spacing' : 'Interlineat (Spacing)',
'Padding' : 'Emplenament (Padding)',
'Rows' : 'Files',
'Columns' : 'Columnes',
'Groups' : 'Grups',
'Cells' : 'Cel·les',
'Caption' : 'Llegenda',
'Inner borders' : 'Vores internes'
}
})(jQuery);
|
import*as React from"react";import createSvgIcon from"../../utils/createSvgIcon";export default createSvgIcon(React.createElement("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"}),"Person");
|
/*
* JXON framework - Copyleft 2011 by Mozilla Developer Network
*
* Revision #1 - September 5, 2014
*
* https://developer.mozilla.org/en-US/docs/JXON
*
* This framework is released under the GNU Public License, version 3 or later.
* http://www.gnu.org/licenses/gpl-3.0-standalone.html
*
* small modifications performed by the iD project:
* https://github.com/openstreetmap/iD/commits/18aa33ba97b52cacf454e95c65d154000e052a1f/js/lib/jxon.js
*
* small modifications performed by user @bugreport0
* https://github.com/tyrasd/JXON/pull/2/commits
*
* some additions and modifications by user @igord
* https://github.com/tyrasd/JXON/pull/5/commits
*
* adapted for nodejs and npm by Martin Raifer <tyr.asd@gmail.com>
*/
/*
* Modifications:
* - added config method that excepts objects with props:
* - valueKey (default: keyValue)
* - attrKey (default: keyAttributes)
* - attrPrefix (default: @)
* - lowerCaseTags (default: true)
* - trueIsEmpty (default: true)
* - autoDate (default: true)
* - turning tag and attributes to lower case is optional
* - optional turning boolean true to empty tag
* - auto Date parsing is optional
* - added parseXml method
*
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory(window));
} else if (typeof exports === 'object') {
if (window && window.DOMImplementation) {
// Browserify. hardcode usage of browser's own XMLDom implementation
// see https://github.com/tyrasd/jxon/issues/18
module.exports = factory(window);
} else {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('xmldom'));
}
} else {
// Browser globals (root is window)
root.JXON = factory(window);
}
}(this, function (xmlDom) {
return new (function () {
var
sValProp = "keyValue",
sAttrProp = "keyAttributes",
sAttrsPref = "@",
sLowCase = true,
sEmptyTrue = true,
sAutoDate = true,
sIgnorePrefixed = false,
sParseValues = true, /* you can customize these values */
aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;
function parseText (sValue) {
if (!sParseValues) return sValue;
if (rIsNull.test(sValue)) { return null; }
if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
if (isFinite(sValue)) { return parseFloat(sValue); }
if (sAutoDate && isFinite(Date.parse(sValue))) { return new Date(sValue); }
return sValue;
}
function EmptyTree () { }
EmptyTree.prototype.toString = function () { return "null"; };
EmptyTree.prototype.valueOf = function () { return null; };
function objectify (vValue) {
return vValue === null ? new EmptyTree() : vValue instanceof Object ? vValue : new vValue.constructor(vValue);
}
function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
var
nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
bAttributes = oParentNode.nodeType === oParentNode.ELEMENT_NODE && oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);
var
sProp, vContent, nLength = 0, sCollectedTxt = "",
vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ (sEmptyTrue ? true : '');
if (bChildren) {
for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) {
oNode = oParentNode.childNodes.item(nItem);
if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
else if (oNode.nodeType === 1 && !(sIgnorePrefixed && oNode.prefix)) { aCache.push(oNode); } /* nodeType is "Element" (1) */
}
}
var nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);
if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }
for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
sProp = aCache[nElId].nodeName;
if (sLowCase) sProp = sProp.toLowerCase();
vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
if (vResult.hasOwnProperty(sProp)) {
if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
vResult[sProp].push(vContent);
} else {
vResult[sProp] = vContent;
nLength++;
}
}
if (bAttributes) {
var
nAttrLen = oParentNode.attributes.length,
sAPrefix = bNesteAttr ? "" : sAttrsPref, oAttrParent = bNesteAttr ? {} : vResult;
for (var oAttrib, oAttribName, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
oAttrib = oParentNode.attributes.item(nAttrib);
oAttribName = oAttrib.name;
if (sLowCase) oAttribName = oAttribName.toLowerCase();
oAttrParent[sAPrefix + oAttribName] = parseText(oAttrib.value.trim());
}
if (bNesteAttr) {
if (bFreeze) { Object.freeze(oAttrParent); }
vResult[sAttrProp] = oAttrParent;
nLength -= nAttrLen - 1;
}
}
if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
vResult[sValProp] = vBuiltVal;
} else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
vResult = vBuiltVal;
}
if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }
aCache.length = nLevelStart;
return vResult;
}
function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
var vValue, oChild;
if (oParentObj.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */
if (oParentObj === oParentObj.valueOf()) { return; }
} else if (oParentObj.constructor === Date) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
}
for (var sName in oParentObj) {
vValue = oParentObj[sName];
if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */
// when it is _
if (sName === sValProp) {
if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
} else if (sName === sAttrProp) { /* verbosity level is 3 */
for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
} else if (sName.charAt(0) === sAttrsPref && sName !== sAttrsPref+'xmlns') {
oParentEl.setAttribute(sName.slice(1), vValue);
} else if (vValue.constructor === Array) {
for (var nItem = 0; nItem < vValue.length; nItem++) {
oChild = oXMLDoc.createElementNS(vValue[nItem][sAttrsPref+'xmlns'] || oParentEl.namespaceURI, sName);
loadObjTree(oXMLDoc, oChild, vValue[nItem]);
oParentEl.appendChild(oChild);
}
} else {
oChild = oXMLDoc.createElementNS((vValue || {})[sAttrsPref+'xmlns'] || oParentEl.namespaceURI, sName);
if (vValue instanceof Object) {
loadObjTree(oXMLDoc, oChild, vValue);
} else if (vValue !== null && vValue !== true) {
oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
} else if (!sEmptyTrue && vValue === true) {
oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
}
oParentEl.appendChild(oChild);
}
}
}
this.xmlToJs = this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);
};
this.jsToXml = this.unbuild = function (oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
var documentImplementation = xmlDom.document && xmlDom.document.implementation || new xmlDom.DOMImplementation();
var oNewDoc = documentImplementation.createDocument(sNamespaceURI || null, sQualifiedName || "", oDocumentType || null);
loadObjTree(oNewDoc, oNewDoc.documentElement || oNewDoc, oObjTree);
return oNewDoc;
};
this.config = function(o) {
if (typeof o === 'undefined') {
return {
valueKey: sValProp,
attrKey: sAttrProp,
attrPrefix: sAttrPref,
lowerCaseTags: sLowCase,
trueIsEmpty: sEmptyTrue,
autoDate: sAutoDate,
ignorePrefixNodes: sIgnorePrefixed,
parseValues: sParseValues
};
}
for (var k in o) {
switch(k) {
case 'valueKey':
sValProp = o.valueKey;
break;
case 'attrKey':
sAttrProp = o.attrKey;
break;
case 'attrPrefix':
sAttrsPref = o.attrPrefix;
break;
case 'lowerCaseTags':
sLowCase = o.lowerCaseTags;
break;
case 'trueIsEmpty':
sEmptyTrue = o.trueIsEmpty;
break;
case 'autoDate':
sAutoDate = o.autoDate;
break;
case 'ignorePrefixedNodes':
sIgnorePrefixed = o.ignorePrefixedNodes;
break;
case 'parseValues':
sParseValues = o.parseValues;
break;
default:
break;
}
}
};
this.stringToXml = function(xmlStr) {
return ( new xmlDom.DOMParser() ).parseFromString(xmlStr, 'application/xml');
};
this.xmlToString = function (xmlObj) {
if (typeof xmlObj.xml !== "undefined") {
return xmlObj.xml;
} else {
return (new xmlDom.XMLSerializer()).serializeToString(xmlObj);
}
};
this.stringToJs = function(str) {
var xmlObj = this.stringToXml(str);
return this.xmlToJs(xmlObj);
};
this.jsToString = this.stringify = function(oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
return this.xmlToString(
this.jsToXml(oObjTree, sNamespaceURI, sQualifiedName, oDocumentType)
);
};
})();
}));
|
/*
* angular-elastic v2.2.0
* (c) 2013 Monospaced http://monospaced.com
* License: MIT
*/
angular.module('monospaced.elastic', [])
.constant('msdElasticConfig', {
append: ''
})
.directive('msdElastic', ['$timeout', '$window', 'msdElasticConfig', function($timeout, $window, config) {
'use strict';
return {
require: 'ngModel',
restrict: 'A, C',
link: function(scope, element, attrs, ngModel){
// cache a reference to the DOM element
var ta = element[0],
$ta = element;
// ensure the element is a textarea, and browser is capable
if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) {
return;
}
// set these properties before measuring dimensions
$ta.css({
'overflow': 'hidden',
'overflow-y': 'hidden',
'word-wrap': 'break-word'
});
// force text reflow
var text = ta.value;
ta.value = '';
ta.value = text;
var appendText = attrs.msdElastic || config.append,
append = appendText === '\\n' ? '\n' : appendText,
$win = angular.element($window),
mirrorStyle = 'position: absolute; top: -999px; right: auto; bottom: auto; left: 0 ;' +
'overflow: hidden; -webkit-box-sizing: content-box;' +
'-moz-box-sizing: content-box; box-sizing: content-box;' +
'min-height: 0 !important; height: 0 !important; padding: 0;' +
'word-wrap: break-word; border: 0;',
$mirror = angular.element('<textarea tabindex="-1" ' +
'style="' + mirrorStyle + '"/>').data('elastic', true),
mirror = $mirror[0],
taStyle = getComputedStyle(ta),
resize = taStyle.getPropertyValue('resize'),
borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' ||
taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' ||
taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box',
boxOuter = !borderBox ? {width: 0, height: 0} : {
width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) +
parseInt(taStyle.getPropertyValue('padding-right'), 10) +
parseInt(taStyle.getPropertyValue('padding-left'), 10) +
parseInt(taStyle.getPropertyValue('border-left-width'), 10),
height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) +
parseInt(taStyle.getPropertyValue('padding-top'), 10) +
parseInt(taStyle.getPropertyValue('padding-bottom'), 10) +
parseInt(taStyle.getPropertyValue('border-bottom-width'), 10)
},
minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10),
heightValue = parseInt(taStyle.getPropertyValue('height'), 10),
minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height,
maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10),
mirrored,
active,
copyStyle = ['font-family',
'font-size',
'font-weight',
'font-style',
'letter-spacing',
'line-height',
'text-transform',
'word-spacing',
'text-indent'];
// exit if elastic already applied (or is the mirror element)
if ($ta.data('elastic')) {
return;
}
// Opera returns max-height of -1 if not set
maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4;
// append mirror to the DOM
if (mirror.parentNode !== document.body) {
angular.element(document.body).append(mirror);
}
// set resize and apply elastic
$ta.css({
'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal'
}).data('elastic', true);
/*
* methods
*/
function initMirror(){
mirrored = ta;
// copy the essential styles from the textarea to the mirror
taStyle = getComputedStyle(ta);
angular.forEach(copyStyle, function(val){
mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';';
});
mirror.setAttribute('style', mirrorStyle);
}
function adjust() {
var taHeight,
mirrorHeight,
width,
overflow;
if (mirrored !== ta) {
initMirror();
}
// active flag prevents actions in function from calling adjust again
if (!active) {
active = true;
mirror.value = ta.value + append; // optional whitespace to improve animation
mirror.style.overflowY = ta.style.overflowY;
taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10);
// update mirror width in case the textarea width has changed
width = parseInt(getComputedStyle(ta).getPropertyValue('width'), 10) - boxOuter.width;
mirror.style.width = width + 'px';
mirrorHeight = mirror.scrollHeight;
if (mirrorHeight > maxHeight) {
mirrorHeight = maxHeight;
overflow = 'scroll';
} else if (mirrorHeight < minHeight) {
mirrorHeight = minHeight;
}
mirrorHeight += boxOuter.height;
ta.style.overflowY = overflow || 'hidden';
if (taHeight !== mirrorHeight) {
ta.style.height = mirrorHeight + 'px';
}
// small delay to prevent an infinite loop
$timeout(function(){
active = false;
}, 1);
}
}
function forceAdjust(){
active = false;
adjust();
}
/*
* initialise
*/
// listen
if ('onpropertychange' in ta && 'oninput' in ta) {
// IE9
ta['oninput'] = ta.onkeyup = adjust;
} else {
ta['oninput'] = adjust;
}
$win.bind('resize', forceAdjust);
scope.$watch(function(){
return ngModel.$modelValue;
}, function(newValue){
forceAdjust();
});
/*
* destroy
*/
scope.$on('$destroy', function(){
$mirror.remove();
$win.unbind('resize', forceAdjust);
});
}
};
}]);
|
/*
Highcharts JS v2.2.1 (2012-03-15)
(c) 2009-2011 Torstein H?nsi
License: www.highcharts.com/license
*/
(function(){function L(a,b){var c;a||(a={});for(c in b)a[c]=b[c];return a}function za(){for(var a=0,b=arguments,c=b.length,d={};a<c;a++)d[b[a++]]=b[a];return d}function S(a,b){return parseInt(a,b||10)}function Ab(a){return typeof a==="string"}function mb(a){return typeof a==="object"}function Fb(a){return Object.prototype.toString.call(a)==="[object Array]"}function Bb(a){return typeof a==="number"}function nb(a){return oa.log(a)/oa.LN10}function cb(a){return oa.pow(10,a)}function Gb(a,b){for(var c=
a.length;c--;)if(a[c]===b){a.splice(c,1);break}}function s(a){return a!==X&&a!==null}function A(a,b,c){var d,e;if(Ab(b))s(c)?a.setAttribute(b,c):a&&a.getAttribute&&(e=a.getAttribute(b));else if(s(b)&&mb(b))for(d in b)a.setAttribute(d,b[d]);return e}function Hb(a){return Fb(a)?a:[a]}function p(){var a=arguments,b,c,d=a.length;for(b=0;b<d;b++)if(c=a[b],typeof c!=="undefined"&&c!==null)return c}function P(a,b){if(Qb&&b&&b.opacity!==X)b.filter="alpha(opacity="+b.opacity*100+")";L(a.style,b)}function Aa(a,
b,c,d,e){a=x.createElement(a);b&&L(a,b);e&&P(a,{padding:0,border:Ma,margin:0});c&&P(a,c);d&&d.appendChild(a);return a}function pa(a,b){var c=function(){};c.prototype=new a;L(c.prototype,b);return c}function dc(a,b,c,d){var e=Ea.lang,f=isNaN(b=Ba(b))?2:b,b=c===void 0?e.decimalPoint:c,d=d===void 0?e.thousandsSep:d,e=a<0?"-":"",c=String(S(a=Ba(+a||0).toFixed(f))),g=c.length>3?c.length%3:0;return e+(g?c.substr(0,g)+d:"")+c.substr(g).replace(/(\d{3})(?=\d)/g,"$1"+d)+(f?b+Ba(a-c).toFixed(f).slice(2):"")}
function Na(a,b){return Array((b||2)+1-String(a).length).join(0)+a}function ec(a,b,c,d){var e,c=p(c,1);e=a/c;b||(b=[1,2,2.5,5,10],d&&d.allowDecimals===!1&&(c===1?b=[1,2,5,10]:c<=0.1&&(b=[1/c])));for(d=0;d<b.length;d++)if(a=b[d],e<=(b[d]+(b[d+1]||b[d]))/2)break;a*=c;return a}function Kc(a,b){var c=b||[[Rb,[1,2,5,10,20,25,50,100,200,500]],[ob,[1,2,5,10,15,30]],[pb,[1,2,5,10,15,30]],[va,[1,2,3,4,6,8,12]],[Ca,[1,2]],[Ya,[1,2]],[Da,[1,2,3,4,6]],[Za,null]],d=c[c.length-1],e=E[d[0]],f=d[1],g;for(g=0;g<c.length;g++)if(d=
c[g],e=E[d[0]],f=d[1],c[g+1]&&a<=(e*f[f.length-1]+E[c[g+1][0]])/2)break;e===E[Za]&&a<5*e&&(f=[1,2,5]);e===E[Za]&&a<5*e&&(f=[1,2,5]);c=ec(a/e,f);return{unitRange:e,count:c,unitName:d[0]}}function Lc(a,b,c,d){var e=[],f={},g=Ea.global.useUTC,h,i=new Date(b),b=a.unitRange,k=a.count;b>=E[ob]&&(i.setMilliseconds(0),i.setSeconds(b>=E[pb]?0:k*Ta(i.getSeconds()/k)));if(b>=E[pb])i[pc](b>=E[va]?0:k*Ta(i[fc]()/k));if(b>=E[va])i[qc](b>=E[Ca]?0:k*Ta(i[gc]()/k));if(b>=E[Ca])i[hc](b>=E[Da]?1:k*Ta(i[db]()/k));b>=
E[Da]&&(i[rc](b>=E[Za]?0:k*Ta(i[qb]()/k)),h=i[rb]());b>=E[Za]&&(h-=h%k,i[sc](h));if(b===E[Ya])i[hc](i[db]()-i[ic]()+p(d,1));d=1;h=i[rb]();for(var j=i.getTime(),l=i[qb](),i=i[db]();j<c;)e.push(j),b===E[Za]?j=sb(h+d*k,0):b===E[Da]?j=sb(h,l+d*k):!g&&(b===E[Ca]||b===E[Ya])?j=sb(h,l,i+d*k*(b===E[Ca]?1:7)):(j+=b*k,b<=E[va]&&j%E[Ca]===0&&(f[j]=Ca)),d++;e.push(j);e.info=L(a,{higherRanks:f,totalRange:b*k});return e}function tc(){this.symbol=this.color=0}function uc(a,b,c,d,e,f,g,h,i){var k=g.x,g=g.y,i=k+c+
(i?h:-a-h),j=g-b+d+15,l;i<7&&(i=c+k+h);i+a>c+e&&(i-=i+a-(c+e),j=g-b+d-h,l=!0);j<d+5?(j=d+5,l&&g>=j&&g<=j+b&&(j=g+d+h)):j+b>d+f&&(j=d+f-b-h);return{x:i,y:j}}function Mc(a,b){var c=a.length,d,e;for(e=0;e<c;e++)a[e].ss_i=e;a.sort(function(a,c){d=b(a,c);return d===0?a.ss_i-c.ss_i:d});for(e=0;e<c;e++)delete a[e].ss_i}function Sb(a){for(var b=a.length,c=a[0];b--;)a[b]<c&&(c=a[b]);return c}function Ib(a){for(var b=a.length,c=a[0];b--;)a[b]>c&&(c=a[b]);return c}function Jb(a){for(var b in a)a[b]&&a[b].destroy&&
a[b].destroy(),delete a[b]}function Tb(a){tb||(tb=Aa(Ra));a&&tb.appendChild(a);tb.innerHTML=""}function jc(a,b){var c="Highcharts error #"+a+": www.highcharts.com/errors/"+a;if(b)throw c;else ca.console&&console.log(c)}function Cb(a){return parseFloat(a.toPrecision(14))}function Kb(a,b){Ub=p(a,b.animation)}function vc(){var a=Ea.global.useUTC,b=a?"getUTC":"get",c=a?"setUTC":"set";sb=a?Date.UTC:function(a,b,c,g,h,i){return(new Date(a,b,p(c,1),p(g,0),p(h,0),p(i,0))).getTime()};fc=b+"Minutes";gc=b+"Hours";
ic=b+"Day";db=b+"Date";qb=b+"Month";rb=b+"FullYear";pc=c+"Minutes";qc=c+"Hours";hc=c+"Date";rc=c+"Month";sc=c+"FullYear"}function Sa(){}function wc(a,b){function c(a){function b(a,c){this.pos=a;this.type=c||"";this.isNew=!0;c||this.addLabel()}function c(a){if(a)this.options=a,this.id=a.id;return this}function d(a,b,c,e){this.isNegative=b;this.options=a;this.x=c;this.stack=e;this.alignOptions={align:a.align||(U?b?"left":"right":"center"),verticalAlign:a.verticalAlign||(U?"middle":b?"bottom":"top"),
y:p(a.y,U?4:b?14:-6),x:p(a.x,U?b?-6:6:0)};this.textAlign=a.textAlign||(U?b?"right":"left":"center")}function e(){var a=[],b=[],c;C=M=null;o(B.series,function(e){if(e.visible||!q.ignoreHiddenSeries){var f=e.options,g,h,i,j,k,m,l,n,Y,ea=f.threshold,B,o=[],xc=0;if(R&&ea<=0)ea=f.threshold=null;if(t)f=e.xData,f.length&&(C=Ua(p(C,f[0]),Sb(f)),M=W(p(M,f[0]),Ib(f)));else{var y,r,G,v=e.cropped,Z=e.xAxis.getExtremes(),V=!!e.modifyValue;g=f.stacking;Ha=g==="percent";if(g)k=f.stack,j=e.type+p(k,""),m="-"+j,e.stackKey=
j,h=a[j]||[],a[j]=h,i=b[m]||[],b[m]=i;Ha&&(C=0,M=99);f=e.processedXData;l=e.processedYData;B=l.length;for(c=0;c<B;c++)if(n=f[c],Y=l[c],Y!==null&&Y!==X&&(g?(r=(y=Y<ea)?i:h,G=y?m:j,Y=r[n]=s(r[n])?r[n]+Y:Y,qa[G]||(qa[G]={}),qa[G][n]||(qa[G][n]=new d(u.stackLabels,y,n,k)),qa[G][n].setTotal(Y)):V&&(Y=e.modifyValue(Y)),v||(f[c+1]||n)>=Z.min&&(f[c-1]||n)<=Z.max))if(n=Y.length)for(;n--;)Y[n]!==null&&(o[xc++]=Y[n]);else o[xc++]=Y;!Ha&&o.length&&(C=Ua(p(C,o[0]),Sb(o)),M=W(p(M,o[0]),Ib(o)));s(ea)&&(C>=ea?(C=
ea,Ma=!0):M<ea&&(M=ea,Na=!0))}}})}function f(a,b,c){for(var d,b=Cb(Ta(b/a)*a),c=Cb(Yb(c/a)*a),e=[];b<=c;){e.push(b);b=Cb(b+a);if(b===d)break;d=b}return e}function g(a,b,c,d){var e=[];if(!d)B._minorAutoInterval=null;if(a>=0.5)a=z(a),e=f(a,b,c);else if(a>=0.08){var h=Ta(b),i,j,k,n,m,l;for(i=a>0.3?[1,2,4]:a>0.15?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];h<c+1&&!l;h++){k=i.length;for(j=0;j<k&&!l;j++)n=nb(cb(h)*i[j]),n>b&&e.push(m),m>c&&(l=!0),m=n}}else if(b=cb(b),c=cb(c),a=u[d?"minorTickInterval":"tickInterval"],
a=p(a==="auto"?null:a,B._minorAutoInterval,(c-b)*(u.tickPixelInterval/(d?5:1))/((d?D/N.length:D)||1)),a=ec(a,null,oa.pow(10,Ta(oa.log(a)/oa.LN10))),e=Vb(f(a,b,c),nb),!d)B._minorAutoInterval=a/5;d||(Oa=a);return e}function h(){var a=[],b,c;if(R){c=N.length;for(b=1;b<c;b++)a=a.concat(g(Ga,N[b-1],N[b],!0))}else for(b=F+(N[0]-F)%Ga;b<=H;b+=Ga)a.push(b);return a}function i(){var a,b=M-C>=fb,c,d,e,f,g,h;t&&fb===X&&!R&&(s(u.min)||s(u.max)?fb=null:(o(B.series,function(a){f=a.xData;for(d=g=a.xIncrement?1:
f.length-1;d>0;d--)if(e=f[d]-f[d-1],c===X||e<c)c=e}),fb=Ua(c*5,M-C)));H-F<fb&&(a=(fb-H+F)/2,a=[F-a,p(u.min,F-a)],b&&(a[2]=C),F=Ib(a),h=[F+fb,p(u.max,F+fb)],b&&(h[2]=M),H=Sb(h),H-F<fb&&(a[0]=H-fb,a[1]=p(u.min,H-fb),F=Ib(a)))}function j(a){var b,c=u.tickInterval,d=u.tickPixelInterval;da?(na=m[t?"xAxis":"yAxis"][u.linkedTo],b=na.getExtremes(),F=p(b.min,b.dataMin),H=p(b.max,b.dataMax),u.type!==na.options.type&&jc(11,1)):(F=p(ba,u.min,C),H=p(ca,u.max,M));R&&(!a&&Ua(F,C)<=0&&jc(10,1),F=nb(F),H=nb(H));ja&&
(ba=F=W(F,H-ja),ca=H,a&&(ja=null));i();if(!Va&&!Ha&&!da&&s(F)&&s(H)){b=H-F||1;if(!s(u.min)&&!s(ba)&&Ea&&(C<0||!Ma))F-=b*Ea;if(!s(u.max)&&!s(ca)&&Ja&&(M>0||!Na))H+=b*Ja}Oa=F===H||F===void 0||H===void 0?1:da&&!c&&d===na.options.tickPixelInterval?na.tickInterval:p(c,Va?1:(H-F)*d/(D||1));t&&!a&&o(B.series,function(a){a.processData(F!==ma||H!==za)});ib();B.beforeSetTickPositions&&B.beforeSetTickPositions();B.postProcessTickInterval&&(Oa=B.postProcessTickInterval(Oa));!V&&!R&&(Wa=oa.pow(10,Ta(oa.log(Oa)/
oa.LN10)),s(u.tickInterval)||(Oa=ec(Oa,null,Wa,u)));B.tickInterval=Oa;Ga=u.minorTickInterval==="auto"&&Oa?Oa/5:u.minorTickInterval;(N=u.tickPositions||Xa&&Xa.apply(B,[F,H]))||(N=V?(B.getNonLinearTimeTicks||Lc)(Kc(Oa,u.units),F,H,u.startOfWeek,B.ordinalPositions,B.closestPointRange,!0):R?g(Oa,F,H):f(Oa,F,H));if(!da&&(a=N[0],c=N[N.length-1],u.startOnTick?F=a:F>a&&N.shift(),u.endOnTick?H=c:H<c&&N.pop(),gb||(gb={x:0,y:0}),!V&&N.length>gb[w]&&u.alignTicks!==!1))gb[w]=N.length}function k(a){a=(new c(a)).render();
ta.push(a);return a}function l(){var a=u.title,d=u.stackLabels,e=u.alternateGridColor,f=u.lineWidth,g,i,j=m.hasRendered&&s(ma)&&!isNaN(ma),n=(g=B.series.length&&s(F)&&s(H))||p(u.showEmpty,!0),Y,q;if(g||da)if(Ga&&!Va&&o(h(),function(a){va[a]||(va[a]=new b(a,"minor"));j&&va[a].isNew&&va[a].render(null,!0);va[a].isActive=!0;va[a].render()}),o(N.slice(1).concat([N[0]]),function(a,c){c=c===N.length-1?0:c+1;if(!da||a>=F&&a<=H)Pa[a]||(Pa[a]=new b(a)),j&&Pa[a].isNew&&Pa[a].render(c,!0),Pa[a].isActive=!0,
Pa[a].render(c)}),e&&o(N,function(a,b){if(b%2===0&&a<H)Da[a]||(Da[a]=new c),Y=a,q=N[b+1]!==X?N[b+1]:H,Da[a].options={from:R?cb(Y):Y,to:R?cb(q):q,color:e},Da[a].render(),Da[a].isActive=!0}),!B._addedPlotLB)o((u.plotLines||[]).concat(u.plotBands||[]),function(a){k(a)}),B._addedPlotLB=!0;o([Pa,va,Da],function(a){for(var b in a)a[b].isActive?a[b].isActive=!1:(a[b].destroy(),delete a[b])});f&&(g=x+(y?A:0)+T,i=ra-Lb-(y?hb:0)+T,g=I.crispLine([wa,G?x:g,G?i:E,fa,G?sa-Zb:g,G?i:ra-Lb],f),$?$.animate({d:g}):
$=I.path(g).attr({stroke:u.lineColor,"stroke-width":f,zIndex:7}).add(),$[n?"show":"hide"]());if(v&&n)n=G?x:E,f=S(a.style.fontSize||12),n={low:n+(G?0:D),middle:n+D/2,high:n+(G?D:0)}[a.align],f=(G?E+hb:x)+(G?1:-1)*(y?-1:1)*Ya+(r===2?f:0),v[v.isNew?"attr":"animate"]({x:G?n:f+(y?A:0)+T+(a.x||0),y:G?f-(y?hb:0)+T:n+(a.y||0)}),v.isNew=!1;if(d&&d.enabled){var t,yc,d=B.stackTotalGroup;if(!d)B.stackTotalGroup=d=I.g("stack-labels").attr({visibility:eb,zIndex:6}).translate(O,J).add();for(t in qa)for(yc in a=
qa[t],a)a[yc].render(d)}B.isDirty=!1}function n(a){for(var b=ta.length;b--;)ta[b].id===a&&ta[b].destroy()}var t=a.isX,y=a.opposite,G=U?!t:t,r=G?y?0:2:y?1:3,qa={},u=K(t?$b:kc,[Nc,Oc,zc,Pc][r],a),B=this,v,Z=u.type,V=Z==="datetime",R=Z==="logarithmic",T=u.offset||0,w=t?"x":"y",D=0,ua,ia,bb,jb,x,E,A,hb,Lb,Zb,Mb,ib,P,Q,bc,$,C,M,fb=u.minRange||u.maxZoom,ja=u.range,ba,ca,Aa,Ca,H=null,F=null,ma,za,Ea=u.minPadding,Ja=u.maxPadding,Ka=0,da=s(u.linkedTo),na,Ma,Na,Ha,Z=u.events,Sa,ta=[],Oa,Ga,Wa,N,Xa=u.tickPositioner,
Pa={},va={},Da={},Fa,La,Ya,Va=u.categories,db=u.labels.formatter||function(){var a=this.value,b=this.dateTimeLabelFormat;return b?ac(b,a):Oa%1E6===0?a/1E6+"M":Oa%1E3===0?a/1E3+"k":!Va&&a>=1E3?dc(a,0):a},Ra=G&&u.labels.staggerLines,ya=u.reversed,Ia=Va&&u.tickmarkPlacement==="between"?0.5:0;b.prototype={addLabel:function(){var a=this.pos,b=u.labels,c=Va&&G&&Va.length&&!b.step&&!b.staggerLines&&!b.rotation&&ka/Va.length||!G&&ka/2,d=a===N[0],e=a===N[N.length-1],f=Va&&s(Va[a])?Va[a]:a,g=this.label,h=N.info,
i;V&&h&&(i=u.dateTimeLabelFormats[h.higherRanks[a]||h.unitName]);this.isFirst=d;this.isLast=e;a=db.call({axis:B,chart:m,isFirst:d,isLast:e,dateTimeLabelFormat:i,value:R?Cb(cb(f)):f});c=c&&{width:W(1,z(c-2*(b.padding||10)))+ga};c=L(c,b.style);s(g)?g&&g.attr({text:a}).css(c):this.label=s(a)&&b.enabled?I.text(a,0,0,b.useHTML).attr({align:b.align,rotation:b.rotation}).css(c).add(Q):null},getLabelSize:function(){var a=this.label;return a?(this.labelBBox=a.getBBox())[G?"height":"width"]:0},getLabelSides:function(){var a=
u.labels,b=this.labelBBox.width,a=b*{left:0,center:0.5,right:1}[a.align]-a.x;return[-a,b-a]},handleOverflow:function(a){var b=!0,c=this.isFirst,d=this.isLast,e=this.label,f=e.x;if(c||d){var g=this.getLabelSides(),h=g[0],g=g[1],i=m.plotLeft,j=i+B.len,k=(a=Pa[N[a+(c?1:-1)]])&&a.label.x+a.getLabelSides()[c?0:1];c&&!ya||d&&ya?f+h<i&&(f=i-h,a&&f+g>k&&(b=!1)):f+g>j&&(f=j-g,a&&f+h<k&&(b=!1));e.x=f}return b},render:function(a,b){var c=this.type,d=this.label,e=this.pos,f=u.labels,g=this.gridLine,h=c?c+"Grid":
"grid",i=c?c+"Tick":"tick",j=u[h+"LineWidth"],k=u[h+"LineColor"],n=u[h+"LineDashStyle"],m=u[i+"Length"],h=u[i+"Width"]||0,l=u[i+"Color"],Y=u[i+"Position"],i=this.mark,q=f.step,ea=b&&Za||ra,qa=!0,o;o=G?Mb(e+Ia,null,null,b)+bb:x+T+(y?(b&&$a||sa)-Zb-x:0);ea=G?ea-Lb+T-(y?hb:0):ea-Mb(e+Ia,null,null,b)-bb;if(j){e=P(e+Ia,j,b);if(g===X){g={stroke:k,"stroke-width":j};if(n)g.dashstyle=n;if(!c)g.zIndex=1;this.gridLine=g=j?I.path(e).attr(g).add(bc):null}!b&&g&&e&&g.animate({d:e})}if(h)Y==="inside"&&(m=-m),y&&
(m=-m),c=I.crispLine([wa,o,ea,fa,o+(G?0:-m),ea+(G?m:0)],h),i?i.animate({d:c}):this.mark=I.path(c).attr({stroke:l,"stroke-width":h}).add(Q);if(d&&!isNaN(o))o=o+f.x-(Ia&&G?Ia*ia*(ya?-1:1):0),ea=ea+f.y-(Ia&&!G?Ia*ia*(ya?1:-1):0),s(f.y)||(ea+=S(d.styles.lineHeight)*0.9-d.getBBox().height/2),Ra&&(ea+=a/(q||1)%Ra*16),d.x=o,d.y=ea,this.isFirst&&!p(u.showFirstLabel,1)||this.isLast&&!p(u.showLastLabel,1)?qa=!1:!Ra&&G&&f.overflow==="justify"&&!this.handleOverflow(a)&&(qa=!1),q&&a%q&&(qa=!1),qa?(d[this.isNew?
"attr":"animate"]({x:d.x,y:d.y}),d.show(),this.isNew=!1):d.hide()},destroy:function(){Jb(this)}};c.prototype={render:function(){var a=this,b=(B.pointRange||0)/2,c=a.options,d=c.label,e=a.label,f=c.width,g=c.to,h=c.from,i=c.value,j,k=c.dashStyle,n=a.svgElem,m=[],l,Y,u=c.color;Y=c.zIndex;var ea=c.events;R&&(h=nb(h),g=nb(g),i=nb(i));if(f){if(m=P(i,f),b={stroke:u,"stroke-width":f},k)b.dashstyle=k}else if(s(h)&&s(g))h=W(h,F-b),g=Ua(g,H+b),j=P(g),(m=P(h))&&j?m.push(j[4],j[5],j[1],j[2]):m=null,b={fill:u};
else return;if(s(Y))b.zIndex=Y;if(n)m?n.animate({d:m},null,n.onGetPath):(n.hide(),n.onGetPath=function(){n.show()});else if(m&&m.length&&(a.svgElem=n=I.path(m).attr(b).add(),ea))for(l in k=function(b){n.on(b,function(c){ea[b].apply(a,[c])})},ea)k(l);if(d&&s(d.text)&&m&&m.length&&A>0&&hb>0){d=K({align:G&&j&&"center",x:G?!j&&4:10,verticalAlign:!G&&j&&"middle",y:G?j?16:10:j?6:-4,rotation:G&&!j&&90},d);if(!e)a.label=e=I.text(d.text,0,0).attr({align:d.textAlign||d.align,rotation:d.rotation,zIndex:Y}).css(d.style).add();
j=[m[1],m[4],p(m[6],m[1])];m=[m[2],m[5],p(m[7],m[2])];l=Sb(j);Y=Sb(m);e.align(d,!1,{x:l,y:Y,width:Ib(j)-l,height:Ib(m)-Y});e.show()}else e&&e.hide();return a},destroy:function(){Jb(this);Gb(ta,this)}};d.prototype={destroy:function(){Jb(this)},setTotal:function(a){this.cum=this.total=a},render:function(a){var b=this.options.formatter.call(this);this.label?this.label.attr({text:b,visibility:ab}):this.label=m.renderer.text(b,0,0).css(this.options.style).attr({align:this.textAlign,rotation:this.options.rotation,
visibility:ab}).add(a)},setOffset:function(a,b){var c=this.isNegative,d=B.translate(this.total,0,0,0,1),e=B.translate(0),e=Ba(d-e),f=m.xAxis[0].translate(this.x)+a,g=m.plotHeight,c={x:U?c?d:d-e:f,y:U?g-f-b:c?g-d-e:g-d,width:U?e:b,height:U?b:e};this.label&&this.label.align(this.alignOptions,null,c).attr({visibility:eb})}};Mb=function(a,b,c,d,e){var f=1,g=0,h=d?jb:ia,d=d?ma:F,e=u.ordinal||R&&e;h||(h=ia);c&&(f*=-1,g=D);ya&&(f*=-1,g-=f*D);b?(ya&&(a=D-a),a=a/h+d,e&&(a=B.lin2val(a))):(e&&(a=B.val2lin(a)),
a=f*(a-d)*h+g+f*Ka);return a};P=function(a,b,c){var d,e,f,a=Mb(a,null,null,c),g=c&&Za||ra,h=c&&$a||sa,i,c=e=z(a+bb);d=f=z(g-a-bb);if(isNaN(a))i=!0;else if(G){if(d=E,f=g-Lb,c<x||c>x+A)i=!0}else if(c=x,e=h-Zb,d<E||d>E+hb)i=!0;return i?null:I.crispLine([wa,c,d,fa,e,f],b||0)};ib=function(){var a=H-F,b=0,c,d;if(t)da?b=na.pointRange:o(B.series,function(a){b=W(b,a.pointRange);d=a.closestPointRange;!a.noSharedTooltip&&s(d)&&(c=s(c)?Ua(c,d):d)}),B.pointRange=b,B.closestPointRange=c;jb=ia;B.translationSlope=
ia=D/(a+b||1);bb=G?x:Lb;Ka=ia*(b/2)};xa.push(B);m[t?"xAxis":"yAxis"].push(B);U&&t&&ya===X&&(ya=!0);L(B,{addPlotBand:k,addPlotLine:k,adjustTickAmount:function(){if(gb&&gb[w]&&!V&&!Va&&!da&&u.alignTicks!==!1){var a=Fa,b=N.length;Fa=gb[w];if(b<Fa){for(;N.length<Fa;)N.push(Cb(N[N.length-1]+Oa));ia*=(b-1)/(Fa-1);H=N[N.length-1]}if(s(a)&&Fa!==a)B.isDirty=!0}},categories:Va,getExtremes:function(){return{min:R?Cb(cb(F)):F,max:R?Cb(cb(H)):H,dataMin:C,dataMax:M,userMin:ba,userMax:ca}},getPlotLinePath:P,getThreshold:function(a){var b=
R?cb(F):F,c=R?cb(H):H;b>a||a===null?a=b:c<a&&(a=c);return Mb(a,0,1,0,1)},isXAxis:t,options:u,plotLinesAndBands:ta,getOffset:function(){var a=B.series.length&&s(F)&&s(H),c=a||p(u.showEmpty,!0),d=0,e,f=0,g=u.title,h=u.labels,i=[-1,1,1,-1][r],j;Q||(Q=I.g("axis").attr({zIndex:7}).add(),bc=I.g("grid").attr({zIndex:u.gridZIndex||1}).add());La=0;if(a||da)o(N,function(a){Pa[a]?Pa[a].addLabel():Pa[a]=new b(a)}),o(N,function(a){if(r===0||r===2||{1:"left",3:"right"}[r]===h.align)La=W(Pa[a].getLabelSize(),La)}),
Ra&&(La+=(Ra-1)*16);else for(j in Pa)Pa[j].destroy(),delete Pa[j];if(g&&g.text){if(!v)v=B.axisTitle=I.text(g.text,0,0,g.useHTML).attr({zIndex:7,rotation:g.rotation||0,align:g.textAlign||{low:"left",middle:"center",high:"right"}[g.align]}).css(g.style).add(),v.isNew=!0;if(c)d=v.getBBox()[G?"height":"width"],f=p(g.margin,G?5:10),e=g.offset;v[c?"show":"hide"]()}T=i*p(u.offset,pa[r]);Ya=p(e,La+f+(r!==2&&La&&i*u.labels[G?"y":"x"]));pa[r]=W(pa[r],Ya+d+i*T)},render:l,setAxisSize:function(){var a=u.offsetLeft||
0,b=u.offsetRight||0;x=p(u.left,O+a);E=p(u.top,J);A=p(u.width,ka-a+b);hb=p(u.height,la);Lb=ra-hb-E;Zb=sa-A-x;D=G?A:hb;B.left=x;B.top=E;B.len=D},setAxisTranslation:ib,setCategories:function(b,c){B.categories=a.categories=Va=b;o(B.series,function(a){a.translate();a.setTooltipPoints(!0)});B.isDirty=!0;p(c,!0)&&m.redraw()},setExtremes:function(a,b,c,d,e){c=p(c,!0);e=L(e,{min:a,max:b});aa(B,"setExtremes",e,function(){ba=a;ca=b;B.isDirtyExtremes=!0;c&&m.redraw(d)})},setScale:function(){var a,b,c,d;ma=F;
za=H;ua=D;D=G?A:hb;d=D!==ua;o(B.series,function(a){if(a.isDirtyData||a.isDirty||a.xAxis.isDirty)c=!0});if(d||c||da||ba!==Aa||ca!==Ca){e();j();Aa=ba;Ca=ca;if(!t)for(a in qa)for(b in qa[a])qa[a][b].cum=qa[a][b].total;if(!B.isDirty)B.isDirty=d||F!==ma||H!==za}},setTickPositions:j,translate:Mb,redraw:function(){ub.resetTracker&&ub.resetTracker();l();o(ta,function(a){a.render()});o(B.series,function(a){a.isDirty=!0})},removePlotBand:n,removePlotLine:n,reversed:ya,setTitle:function(a,b){u.title=K(u.title,
a);v=v.destroy();B.isDirty=!0;p(b,!0)&&m.redraw()},series:[],stacks:qa,destroy:function(){var a;Qa(B);for(a in qa)Jb(qa[a]),qa[a]=null;if(B.stackTotalGroup)B.stackTotalGroup=B.stackTotalGroup.destroy();o([Pa,va,Da,ta],function(a){Jb(a)});o([$,Q,bc,v],function(a){a&&a.destroy()});$=Q=bc=v=null}});for(Sa in Z)ha(B,Sa,Z[Sa]);if(R)B.val2lin=nb,B.lin2val=cb}function d(a){function b(){var c=this.points||Hb(this),d=c[0].series,e;e=[d.tooltipHeaderFormatter(c[0].key)];o(c,function(a){d=a.series;e.push(d.tooltipFormatter&&
d.tooltipFormatter(a)||a.point.tooltipFormatter(d.tooltipOptions.pointFormat))});e.push(a.footerFormat||"");return e.join("")}function c(a,b){l=n?a:(2*l+a)/3;q=n?b:(q+b)/2;t.attr({x:l,y:q});lb=Ba(a-l)>1||Ba(b-q)>1?function(){c(a,b)}:null}function d(){if(!n){var a=m.hoverPoints;t.hide();a&&o(a,function(a){a.setState()});m.hoverPoints=null;n=!0}}var e,f=a.borderWidth,g=a.crosshairs,h=[],i=a.style,j=a.shared,k=S(i.padding),n=!0,l=0,q=0;i.padding=0;var t=I.label("",0,0,null,null,null,a.useHTML).attr({padding:k,
fill:a.backgroundColor,"stroke-width":f,r:a.borderRadius,zIndex:8}).css(i).hide().add();Fa||t.shadow(a.shadow);return{shared:j,refresh:function(f){var i,k,l,q,r={},y=[];l=f.tooltipPos;i=a.formatter||b;var r=m.hoverPoints,v;j&&(!f.series||!f.series.noSharedTooltip)?(q=0,r&&o(r,function(a){a.setState()}),m.hoverPoints=f,o(f,function(a){a.setState(ta);q+=a.plotY;y.push(a.getLabelConfig())}),k=f[0].plotX,q=z(q)/f.length,r={x:f[0].category},r.points=y,f=f[0]):r=f.getLabelConfig();r=i.call(r);e=f.series;
k=p(k,f.plotX);q=p(q,f.plotY);i=z(l?l[0]:U?ka-q:k);k=z(l?l[1]:U?la-k:q);l=j||!e.isCartesian||e.tooltipOutsidePlot||Db(i,k);r===!1||!l?d():(n&&(t.show(),n=!1),t.attr({text:r}),v=a.borderColor||f.color||e.color||"#606060",t.attr({stroke:v}),l=uc(t.width,t.height,O,J,ka,la,{x:i,y:k},p(a.distance,12),U),c(z(l.x),z(l.y)));if(g){g=Hb(g);var R;l=g.length;for(var Z;l--;)if(R=f.series[l?"yAxis":"xAxis"],g[l]&&R)if(R=R.getPlotLinePath(l?p(f.stackY,f.y):f.x,1),h[l])h[l].attr({d:R,visibility:eb});else{Z={"stroke-width":g[l].width||
1,stroke:g[l].color||"#C0C0C0",zIndex:g[l].zIndex||2};if(g[l].dashStyle)Z.dashstyle=g[l].dashStyle;h[l]=I.path(R).attr(Z).add()}}aa(m,"tooltipRefresh",{text:r,x:i+O,y:k+J,borderColor:v})},hide:d,hideCrosshairs:function(){o(h,function(a){a&&a.hide()})},destroy:function(){o(h,function(a){a&&a.destroy()});t&&(t=t.destroy())}}}function e(a){function b(a){var c,d,e,a=a||ca.event;if(!a.target)a.target=a.srcElement;if(a.originalEvent)a=a.originalEvent;if(a.event)a=a.event;c=a.touches?a.touches.item(0):a;
ya=Ac(D);d=ya.left;e=ya.top;Qb?(d=a.x,c=a.y):(d=c.pageX-d,c=c.pageY-e);return L(a,{chartX:z(d),chartY:z(c)})}function c(a){var b={xAxis:[],yAxis:[]};o(xa,function(c){var d=c.translate,e=c.isXAxis;b[e?"xAxis":"yAxis"].push({axis:c,value:d((U?!e:e)?a.chartX-O:la-a.chartY+J,!0)})});return b}function e(){var a=m.hoverSeries,b=m.hoverPoint;if(b)b.onMouseOut();if(a)a.onMouseOut();vb&&(vb.hide(),vb.hideCrosshairs());ob=null}function f(){if(n){var a={xAxis:[],yAxis:[]},b=n.getBBox(),c=b.x-O,d=b.y-J;k&&(o(xa,
function(e){if(e.options.zoomEnabled!==!1){var f=e.translate,g=e.isXAxis,h=U?!g:g,i=f(h?c:la-d-b.height,!0,0,0,1),f=f(h?c+b.width:la-d,!0,0,0,1);a[g?"xAxis":"yAxis"].push({axis:e,min:Ua(i,f),max:W(i,f)})}}),aa(m,"selection",a,zb));n=n.destroy()}P(D,{cursor:"auto"});m.mouseIsDown=Da=k=!1;Qa(x,Ga?"touchend":"mouseup",f)}function g(a){var b=s(a.pageX)?a.pageX:a.page.x,a=s(a.pageX)?a.pageY:a.page.y;ya&&!Db(b-ya.left-O,a-ya.top-J)&&e()}function h(){e();ya=null}var i,j,k,n,l=Fa?"":q.zoomType,t=/x/.test(l),
r=/y/.test(l),y=t&&!U||r&&U,p=r&&!U||t&&U;if(!db)m.trackerGroup=db=I.g("tracker").attr({zIndex:9}).add();if(a.enabled)m.tooltip=vb=d(a),Bb=setInterval(function(){lb&&lb()},32);(function(){D.onmousedown=function(a){a=b(a);!Ga&&a.preventDefault&&a.preventDefault();m.mouseIsDown=Da=!0;m.mouseDownX=i=a.chartX;j=a.chartY;ha(x,Ga?"touchend":"mouseup",f)};var d=function(c){if(!c||!(c.touches&&c.touches.length>1)){c=b(c);if(!Ga)c.returnValue=!1;var d=c.chartX,e=c.chartY,f=!Db(d-O,e-J);Ga&&c.type==="touchstart"&&
(A(c.target,"isTracker")?m.runTrackerClick||c.preventDefault():!kb&&!f&&c.preventDefault());f&&(d<O?d=O:d>O+ka&&(d=O+ka),e<J?e=J:e>J+la&&(e=J+la));if(Da&&c.type!=="touchstart"){if(k=Math.sqrt(Math.pow(i-d,2)+Math.pow(j-e,2)),k>10){var g=Db(i-O,j-J);if(Nb&&(t||r)&&g)n||(n=I.rect(O,J,y?1:ka,p?1:la,0).attr({fill:q.selectionMarkerFill||"rgba(69,114,167,0.25)",zIndex:7}).add());n&&y&&(c=d-i,n.attr({width:Ba(c),x:(c>0?0:c)+i}));n&&p&&(e-=j,n.attr({height:Ba(e),y:(e>0?0:e)+j}));g&&!n&&q.panning&&m.pan(d)}}else if(!f){var h,
d=m.hoverPoint,e=m.hoverSeries,l,o,g=sa,R=U?c.chartY:c.chartX-O;if(vb&&a.shared&&(!e||!e.noSharedTooltip)){h=[];l=Q.length;for(o=0;o<l;o++)if(Q[o].visible&&Q[o].options.enableMouseTracking!==!1&&!Q[o].noSharedTooltip&&Q[o].tooltipPoints.length)c=Q[o].tooltipPoints[R],c._dist=Ba(R-c.plotX),g=Ua(g,c._dist),h.push(c);for(l=h.length;l--;)h[l]._dist>g&&h.splice(l,1);if(h.length&&h[0].plotX!==ob)vb.refresh(h),ob=h[0].plotX}if(e&&e.tracker&&(c=e.tooltipPoints[R])&&c!==d)c.onMouseOver()}return f||!Nb}};D.onmousemove=
d;ha(D,"mouseleave",h);ha(x,"mousemove",g);D.ontouchstart=function(a){if(t||r)D.onmousedown(a);d(a)};D.ontouchmove=d;D.ontouchend=function(){k&&e()};D.onclick=function(a){var d=m.hoverPoint,a=b(a);a.cancelBubble=!0;if(!k)if(d&&(A(a.target,"isTracker")||A(a.target.parentNode,"isTracker"))){var e=d.plotX,f=d.plotY;L(d,{pageX:ya.left+O+(U?ka-f:e),pageY:ya.top+J+(U?la-e:f)});aa(d.series,"click",L(a,{point:d}));d.firePointEvent("click",a)}else L(a,c(a)),Db(a.chartX-O,a.chartY-J)&&aa(m,"click",a);k=!1}})();
L(this,{zoomX:t,zoomY:r,resetTracker:e,normalizeMouseEvent:b,destroy:function(){if(m.trackerGroup)m.trackerGroup=db=m.trackerGroup.destroy();Qa(D,"mouseleave",h);Qa(x,"mousemove",g);D.onclick=D.onmousedown=D.onmousemove=D.ontouchstart=D.ontouchend=D.ontouchmove=null}})}function f(a){var b=a.type||q.type||q.defaultSeriesType,c=Ha[b],d=m.hasRendered;if(d)if(U&&b==="column")c=Ha.bar;else if(!U&&b==="bar")c=Ha.column;b=new c;b.init(m,a);!d&&b.inverted&&(U=!0);if(b.isCartesian)Nb=b.isCartesian;Q.push(b);
return b}function g(){q.alignTicks!==!1&&o(xa,function(a){a.adjustTickAmount()});gb=null}function h(a){var b=m.isDirtyLegend,c,d=m.isDirtyBox,e=Q.length,f=e,h=m.clipRect;for(Kb(a,m);f--;)if(a=Q[f],a.isDirty&&a.options.stacking){c=!0;break}if(c)for(f=e;f--;)if(a=Q[f],a.options.stacking)a.isDirty=!0;o(Q,function(a){a.isDirty&&a.options.legendType==="point"&&(b=!0)});if(b&&Xa.renderLegend)Xa.renderLegend(),m.isDirtyLegend=!1;Nb&&(La||(gb=null,o(xa,function(a){a.setScale()})),g(),Wb(),o(xa,function(a){if(a.isDirtyExtremes)a.isDirtyExtremes=
!1,aa(a,"afterSetExtremes",a.getExtremes());if(a.isDirty||d)a.redraw(),d=!0}));d&&(qb(),h&&(Ob(h),h.animate({width:m.plotSizeX,height:m.plotSizeY+1})));o(Q,function(a){a.isDirty&&a.visible&&(!a.isCartesian||a.xAxis)&&a.redraw()});ub&&ub.resetTracker&&ub.resetTracker();I.draw();aa(m,"redraw")}function i(){var a=v.xAxis||{},b=v.yAxis||{},a=Hb(a);o(a,function(a,b){a.index=b;a.isX=!0});b=Hb(b);o(b,function(a,b){a.index=b});a=a.concat(b);o(a,function(a){new c(a)});g()}function k(){var a=Ea.lang,b=q.resetZoomButton,
c=b.theme,d=c.states,e=b.relativeTo==="chart"?null:{x:O,y:J,width:ka,height:la};m.resetZoomButton=I.button(a.resetZoom,null,null,Fb,c,d&&d.hover).attr({align:b.position.align,title:a.resetZoomTitle}).add().align(b.position,!1,e)}function j(a,b){$=K(v.title,a);ja=K(v.subtitle,b);o([["title",a,$],["subtitle",b,ja]],function(a){var b=a[0],c=m[b],d=a[1],a=a[2];c&&d&&(c=c.destroy());a&&a.text&&!c&&(m[b]=I.text(a.text,0,0,a.useHTML).attr({align:a.align,"class":Ia+b,zIndex:a.zIndex||4}).css(a.style).add().align(a,
!1,ib))})}function l(){Ja=q.renderTo;na=Ia+lc++;Ab(Ja)&&(Ja=x.getElementById(Ja));Ja||jc(13,!0);Ja.innerHTML="";Ja.offsetWidth||(C=Ja.cloneNode(0),P(C,{position:wb,top:"-9999px",display:""}),x.body.appendChild(C));za=(C||Ja).offsetWidth;Ca=(C||Ja).offsetHeight;m.chartWidth=sa=q.width||za||600;m.chartHeight=ra=q.height||(Ca>19?Ca:400);m.container=D=Aa(Ra,{className:Ia+"container"+(q.className?" "+q.className:""),id:na},L({position:mc,overflow:ab,width:sa+ga,height:ra+ga,textAlign:"left",lineHeight:"normal"},
q.style),C||Ja);m.renderer=I=q.forExport?new Eb(D,sa,ra,!0):new Xb(D,sa,ra);Fa&&I.create(m,D,sa,ra);var a,b;Bc&&D.getBoundingClientRect&&(a=function(){P(D,{left:0,top:0});b=D.getBoundingClientRect();P(D,{left:-(b.left-S(b.left))+ga,top:-(b.top-S(b.top))+ga})},a(),ha(ca,"resize",a),ha(m,"destroy",function(){Qa(ca,"resize",a)}))}function n(){function a(c){var d=q.width||Ja.offsetWidth,e=q.height||Ja.offsetHeight,c=c?c.target:ca;if(d&&e&&(c===ca||c===x)){if(d!==za||e!==Ca)clearTimeout(b),b=setTimeout(function(){tb(d,
e,!1)},100);za=d;Ca=e}}var b;ha(ca,"resize",a);ha(m,"destroy",function(){Qa(ca,"resize",a)})}function t(){m&&aa(m,"endResize",null,function(){La-=1})}function r(){for(var a=U||q.inverted||q.type==="bar"||q.defaultSeriesType==="bar",b=v.series,c=b&&b.length;!a&&c--;)b[c].type==="bar"&&(a=!0);m.inverted=U=a}function Z(){var a=v.labels,b=v.credits,c;j();Xa=m.legend=new Rb;o(xa,function(a){a.setScale()});Wb();o(xa,function(a){a.setTickPositions(!0)});g();Wb();qb();Nb&&o(xa,function(a){a.render()});if(!m.seriesGroup)m.seriesGroup=
I.g("series-group").attr({zIndex:3}).add();o(Q,function(a){a.translate();a.setTooltipPoints();a.render()});a.items&&o(a.items,function(){var b=L(a.style,this.style),c=S(b.left)+O,d=S(b.top)+J+12;delete b.left;delete b.top;I.text(this.html,c,d).attr({zIndex:2}).css(b).add()});if(b.enabled&&!m.credits)c=b.href,m.credits=I.text(b.text,0,0).on("click",function(){if(c)location.href=c}).attr({align:b.position.align,zIndex:8}).css(b.style).add().align(b.position);m.hasRendered=!0}function V(){if(!Pb&&ca==
ca.top&&x.readyState!=="complete"||Fa&&!ca.canvg)Fa?Cc.push(V,v.global.canvasToolsURL):x.attachEvent("onreadystatechange",function(){x.detachEvent("onreadystatechange",V);x.readyState==="complete"&&V()});else{l();aa(m,"init");if(Highcharts.RangeSelector&&v.rangeSelector.enabled)m.rangeSelector=new Highcharts.RangeSelector(m);rb();sb();r();i();o(v.series||[],function(a){f(a)});if(Highcharts.Scroller&&(v.navigator.enabled||v.scrollbar.enabled))m.scroller=new Highcharts.Scroller(m);m.render=Z;m.tracker=
ub=new e(v.tooltip);Z();I.draw();b&&b.apply(m,[m]);o(m.callbacks,function(a){a.apply(m,[m])});C&&(Ja.appendChild(D),Tb(C));aa(m,"load")}}var v,y=a.series;a.series=null;v=K(Ea,a);v.series=a.series=y;var q=v.chart,y=q.margin,y=mb(y)?y:[y,y,y,y],T=p(q.marginTop,y[0]),w=p(q.marginRight,y[1]),E=p(q.marginBottom,y[2]),bb=p(q.marginLeft,y[3]),ia=q.spacingTop,ua=q.spacingRight,R=q.spacingBottom,jb=q.spacingLeft,ib,$,ja,J,ba,M,O,pa,Ja,C,D,na,za,Ca,sa,ra,$a,Za,ma,Na,Sa,da,m=this,kb=(y=q.events)&&!!y.click,
va,Db,vb,Da,xb,pb,Ya,la,ka,ub,db,Xa,Wa,yb,ya,Nb=q.showAxes,La=0,xa=[],gb,Q=[],U,I,lb,Bb,ob,qb,Wb,rb,sb,tb,zb,Fb,Rb=function(){function a(b,c){var d=b.legendItem,e=b.legendLine,g=b.legendSymbol,h=q.color,i=c?f.itemStyle.color:h,h=c?b.color:h;d&&d.css({fill:i});e&&e.attr({stroke:h});g&&g.attr({stroke:h,fill:h})}function b(a){var c=a.legendItem,d=a.legendLine,e=a._legendItemPos,f=e[0],e=e[1],g=a.legendSymbol,a=a.checkbox;c&&c.attr({x:r?f:Wa-f,y:e});d&&d.translate(r?f:Wa-f,e-4);g&&(c=f+g.xOff,g.attr({x:r?
c:Wa-c,y:e+g.yOff}));if(a)a.x=f,a.y=e}function c(){o(j,function(a){var b=a.checkbox,c=A.alignAttr;b&&P(b,{left:c.translateX+a.legendItemWidth+b.x-40+ga,top:c.translateY+b.y-11+ga})})}function d(b){var c,e,j,k,m=b.legendItem;k=b.series||b;var o=k.options,v=o&&o.borderWidth||0;if(!m){k=/^(bar|pie|area|column)$/.test(k.type);b.legendItem=m=I.text(f.labelFormatter.call(b),0,0,f.useHTML).css(b.visible?n:q).on("mouseover",function(){b.setState(ta);m.css(l)}).on("mouseout",function(){m.css(b.visible?n:q);
b.setState()}).on("click",function(){var a=function(){b.setVisible()};b.firePointEvent?b.firePointEvent("legendItemClick",null,a):aa(b,"legendItemClick",null,a)}).attr({align:r?"left":"right",zIndex:2}).add(A);if(!k&&o&&o.lineWidth){var u={"stroke-width":o.lineWidth,zIndex:2};if(o.dashStyle)u.dashstyle=o.dashStyle;b.legendLine=I.path([wa,(-h-i)*(r?1:-1),0,fa,-i*(r?1:-1),0]).attr(u).add(A)}if(k)j=I.rect(c=-h-i,e=-11,h,12,2).attr({zIndex:3}).add(A),r||(c+=h);else if(o&&o.marker&&o.marker.enabled)j=
o.marker.radius,j=I.symbol(b.symbol,c=-h/2-i-j,e=-4-j,2*j,2*j).attr(b.pointAttr[Ka]).attr({zIndex:3}).add(A),r||(c+=h/2);if(j)j.xOff=c+v%2/2,j.yOff=e+v%2/2;b.legendSymbol=j;a(b,b.visible);if(o&&o.showCheckbox)b.checkbox=Aa("input",{type:"checkbox",checked:b.selected,defaultChecked:b.selected},f.itemCheckboxStyle,D),ha(b.checkbox,"click",function(a){aa(b,"checkboxClick",{checked:a.target.checked},function(){b.select()})})}c=m.getBBox();e=b.legendItemWidth=f.itemWidth||h+i+c.width+t;w=c.height;if(g&&
s-V+e>(J||sa-2*t-V))s=V,z+=y+w+p;!g&&z+f.y+w>ra-ia-R&&(z=T,s+=Z,Z=0);Z=W(Z,e);x=W(x,z+p);b._legendItemPos=[s,z];g?s+=e:z+=y+w+p;C=J||W(s-V+(g?0:e),C)}function e(){s=V;z=T;x=C=0;A||(A=I.g("legend").attr({zIndex:7}).add());j=[];o(M,function(a){var b=a.options;b.showInLegend&&(j=j.concat(a.legendItems||(b.legendType==="point"?a.data:a)))});Mc(j,function(a,b){return(a.options.legendIndex||0)-(b.options.legendIndex||0)});jb&&j.reverse();o(j,d);Wa=J||C;yb=x-v+w;if(E||bb){Wa+=2*t;yb+=2*t;if(ua){if(Wa>0&&
yb>0)ua[ua.isNew?"attr":"animate"](ua.crisp(null,null,null,Wa,yb)),ua.isNew=!1}else ua=I.rect(0,0,Wa,yb,f.borderRadius,E||0).attr({stroke:f.borderColor,"stroke-width":E||0,fill:bb||Ma}).add(A).shadow(f.shadow),ua.isNew=!0;ua[j.length?"show":"hide"]()}o(j,b);for(var a=["left","right","top","bottom"],g,h=4;h--;)g=a[h],k[g]&&k[g]!=="auto"&&(f[h<2?"align":"verticalAlign"]=g,f[h<2?"x":"y"]=S(k[g])*(h%2?-1:1));j.length&&A.align(L(f,{width:Wa,height:yb}),!0,ib);La||c()}var f=m.options.legend;if(f.enabled){var g=
f.layout==="horizontal",h=f.symbolWidth,i=f.symbolPadding,j,k=f.style,n=f.itemStyle,l=f.itemHoverStyle,q=K(n,f.itemHiddenStyle),t=f.padding||S(k.padding),r=!f.rtl,y=f.itemMarginTop||0,p=f.itemMarginBottom||0,v=18,Z=0,V=4+t+h+i,T=t+y+v-5,s,z,x,w=0,ua,E=f.borderWidth,bb=f.backgroundColor,A,C,J=f.width,M=m.series,jb=f.reversed;e();ha(m,"endResize",c);return{colorizeItem:a,destroyItem:function(a){var b=a.checkbox;o(["legendItem","legendLine","legendSymbol"],function(b){a[b]&&a[b].destroy()});b&&Tb(a.checkbox)},
renderLegend:e,destroy:function(){ua&&(ua=ua.destroy());A&&(A=A.destroy())}}}};Db=function(a,b){return a>=0&&a<=ka&&b>=0&&b<=la};Fb=function(){var a=m.resetZoomButton;aa(m,"selection",{resetSelection:!0},zb);if(a)m.resetZoomButton=a.destroy()};zb=function(a){var b;m.resetZoomEnabled!==!1&&!m.resetZoomButton&&k();!a||a.resetSelection?o(xa,function(a){a.options.zoomEnabled!==!1&&(a.setExtremes(null,null,!1),b=!0)}):o(a.xAxis.concat(a.yAxis),function(a){var c=a.axis;if(m.tracker[c.isXAxis?"zoomX":"zoomY"])c.setExtremes(a.min,
a.max,!1),b=!0});b&&h(p(q.animation,m.pointCount<100))};m.pan=function(a){var b=m.xAxis[0],c=m.mouseDownX,d=b.pointRange/2,e=b.getExtremes(),f=b.translate(c-a,!0)+d,c=b.translate(c+ka-a,!0)-d;(d=m.hoverPoints)&&o(d,function(a){a.setState()});f>Ua(e.dataMin,e.min)&&c<W(e.dataMax,e.max)&&b.setExtremes(f,c,!0,!1);m.mouseDownX=a;P(D,{cursor:"move"})};Wb=function(){var a=v.legend,b=p(a.margin,10),c=a.x,d=a.y,e=a.align,f=a.verticalAlign,g;rb();if((m.title||m.subtitle)&&!s(T))(g=W(m.title&&!$.floating&&
!$.verticalAlign&&$.y||0,m.subtitle&&!ja.floating&&!ja.verticalAlign&&ja.y||0))&&(J=W(J,g+p($.margin,15)+ia));a.enabled&&!a.floating&&(e==="right"?s(w)||(ba=W(ba,Wa-c+b+ua)):e==="left"?s(bb)||(O=W(O,Wa+c+b+jb)):f==="top"?s(T)||(J=W(J,yb+d+b+ia)):f==="bottom"&&(s(E)||(M=W(M,yb-d+b+R))));m.extraBottomMargin&&(M+=m.extraBottomMargin);m.extraTopMargin&&(J+=m.extraTopMargin);Nb&&o(xa,function(a){a.getOffset()});s(bb)||(O+=pa[3]);s(T)||(J+=pa[0]);s(E)||(M+=pa[2]);s(w)||(ba+=pa[1]);sb()};tb=function(a,b,
c){var d=m.title,e=m.subtitle;La+=1;Kb(c,m);Za=ra;$a=sa;if(s(a))m.chartWidth=sa=z(a);if(s(b))m.chartHeight=ra=z(b);P(D,{width:sa+ga,height:ra+ga});I.setSize(sa,ra,c);ka=sa-O-ba;la=ra-J-M;gb=null;o(xa,function(a){a.isDirty=!0;a.setScale()});o(Q,function(a){a.isDirty=!0});m.isDirtyLegend=!0;m.isDirtyBox=!0;Wb();d&&d.align(null,null,ib);e&&e.align(null,null,ib);h(c);Za=null;aa(m,"resize");Ub===!1?t():setTimeout(t,Ub&&Ub.duration||500)};sb=function(){m.plotLeft=O=z(O);m.plotTop=J=z(J);m.plotWidth=ka=
z(sa-O-ba);m.plotHeight=la=z(ra-J-M);m.plotSizeX=U?la:ka;m.plotSizeY=U?ka:la;ib={x:jb,y:ia,width:sa-jb-ua,height:ra-ia-R};o(xa,function(a){a.setAxisSize();a.setAxisTranslation()})};rb=function(){J=p(T,ia);ba=p(w,ua);M=p(E,R);O=p(bb,jb);pa=[0,0,0,0]};qb=function(){var a=q.borderWidth||0,b=q.backgroundColor,c=q.plotBackgroundColor,d=q.plotBackgroundImage,e,f={x:O,y:J,width:ka,height:la};e=a+(q.shadow?8:0);if(a||b)ma?ma.animate(ma.crisp(null,null,null,sa-e,ra-e)):ma=I.rect(e/2,e/2,sa-e,ra-e,q.borderRadius,
a).attr({stroke:q.borderColor,"stroke-width":a,fill:b||Ma}).add().shadow(q.shadow);c&&(Na?Na.animate(f):Na=I.rect(O,J,ka,la,0).attr({fill:c}).add().shadow(q.plotShadow));d&&(Sa?Sa.animate(f):Sa=I.image(d,O,J,ka,la).add());q.plotBorderWidth&&(da?da.animate(da.crisp(null,O,J,ka,la)):da=I.rect(O,J,ka,la,0,q.plotBorderWidth).attr({stroke:q.plotBorderColor,"stroke-width":q.plotBorderWidth,zIndex:4}).add());m.isDirtyBox=!1};q.reflow!==!1&&ha(m,"load",n);if(y)for(va in y)ha(m,va,y[va]);m.options=v;m.series=
Q;m.xAxis=[];m.yAxis=[];m.addSeries=function(a,b,c){var d;a&&(Kb(c,m),b=p(b,!0),aa(m,"addSeries",{options:a},function(){d=f(a);d.isDirty=!0;m.isDirtyLegend=!0;b&&m.redraw()}));return d};m.animation=Fa?!1:p(q.animation,!0);m.Axis=c;m.destroy=function(){var a,b=D&&D.parentNode;if(m!==null){aa(m,"destroy");Qa(m);for(a=xa.length;a--;)xa[a]=xa[a].destroy();for(a=Q.length;a--;)Q[a]=Q[a].destroy();o("title,subtitle,seriesGroup,clipRect,credits,tracker,scroller,rangeSelector".split(","),function(a){var b=
m[a];b&&(m[a]=b.destroy())});o([ma,da,Na,Xa,vb,I,ub],function(a){a&&a.destroy&&a.destroy()});ma=da=Na=Xa=vb=I=ub=null;if(D)D.innerHTML="",Qa(D),b&&Tb(D),D=null;clearInterval(Bb);for(a in m)delete m[a];v=m=null}};m.get=function(a){var b,c,d;for(b=0;b<xa.length;b++)if(xa[b].options.id===a)return xa[b];for(b=0;b<Q.length;b++)if(Q[b].options.id===a)return Q[b];for(b=0;b<Q.length;b++){d=Q[b].points||[];for(c=0;c<d.length;c++)if(d[c].id===a)return d[c]}return null};m.getSelectedPoints=function(){var a=
[];o(Q,function(b){a=a.concat(nc(b.points,function(a){return a.selected}))});return a};m.getSelectedSeries=function(){return nc(Q,function(a){return a.selected})};m.hideLoading=function(){xb&&cc(xb,{opacity:0},{duration:v.loading.hideDuration||100,complete:function(){P(xb,{display:Ma})}});Ya=!1};m.initSeries=f;m.isInsidePlot=Db;m.redraw=h;m.setSize=tb;m.setTitle=j;m.showLoading=function(a){var b=v.loading;xb||(xb=Aa(Ra,{className:Ia+"loading"},L(b.style,{left:O+ga,top:J+ga,width:ka+ga,height:la+ga,
zIndex:10,display:Ma}),D),pb=Aa("span",null,b.labelStyle,xb));pb.innerHTML=a||v.lang.loading;Ya||(P(xb,{opacity:0,display:""}),cc(xb,{opacity:b.style.opacity},{duration:b.showDuration||0}),Ya=!0)};m.pointCount=0;m.counters=new tc;V()}var X,x=document,ca=window,oa=Math,z=oa.round,Ta=oa.floor,Yb=oa.ceil,W=oa.max,Ua=oa.min,Ba=oa.abs,ja=oa.cos,C=oa.sin,da=oa.PI,Dc=da*2/360,kb=navigator.userAgent,Qb=/msie/i.test(kb)&&!ca.opera,Xa=x.documentMode===8,Ec=/AppleWebKit/.test(kb),Bc=/Firefox/.test(kb),Pb=!!x.createElementNS&&
!!x.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,Qc=Bc&&parseInt(kb.split("Firefox/")[1],10)<4,Fa=!Pb&&!Qb&&!!x.createElement("canvas").getContext,Xb,Ga=x.documentElement.ontouchstart!==X,Fc={},lc=0,tb,Ea,ac,Ub,La,E,Ra="div",wb="absolute",mc="relative",ab="hidden",Ia="highcharts-",eb="visible",ga="px",Ma="none",wa="M",fa="L",Gc="rgba(192,192,192,"+(Pb?1.0E-6:0.0020)+")",Ka="",ta="hover",Rb="millisecond",ob="second",pb="minute",va="hour",Ca="day",Ya="week",Da="month",Za="year",
sb,fc,gc,ic,db,qb,rb,pc,qc,hc,rc,sc,w=ca.HighchartsAdapter,na=w||{},Hc=na.getScript,o=na.each,nc=na.grep,Ac=na.offset,Vb=na.map,K=na.merge,ha=na.addEvent,Qa=na.removeEvent,aa=na.fireEvent,cc=na.animate,Ob=na.stop,Ha={};ca.Highcharts={};ac=function(a,b,c){if(!s(b)||isNaN(b))return"Invalid date";var a=p(a,"%Y-%m-%d %H:%M:%S"),d=new Date(b),e,f=d[gc](),g=d[ic](),h=d[db](),i=d[qb](),k=d[rb](),j=Ea.lang,l=j.weekdays,b={a:l[g].substr(0,3),A:l[g],d:Na(h),e:h,b:j.shortMonths[i],B:j.months[i],m:Na(i+1),y:k.toString().substr(2,
2),Y:k,H:Na(f),I:Na(f%12||12),l:f%12||12,M:Na(d[fc]()),p:f<12?"AM":"PM",P:f<12?"am":"pm",S:Na(d.getSeconds()),L:Na(z(b%1E3),3)};for(e in b)a=a.replace("%"+e,b[e]);return c?a.substr(0,1).toUpperCase()+a.substr(1):a};tc.prototype={wrapColor:function(a){if(this.color>=a)this.color=0},wrapSymbol:function(a){if(this.symbol>=a)this.symbol=0}};E=za(Rb,1,ob,1E3,pb,6E4,va,36E5,Ca,864E5,Ya,6048E5,Da,2592E6,Za,31556952E3);La={init:function(a,b,c){var b=b||"",d=a.shift,e=b.indexOf("C")>-1,f=e?7:3,g,b=b.split(" "),
c=[].concat(c),h,i,k=function(a){for(g=a.length;g--;)a[g]===wa&&a.splice(g+1,0,a[g+1],a[g+2],a[g+1],a[g+2])};e&&(k(b),k(c));a.isArea&&(h=b.splice(b.length-6,6),i=c.splice(c.length-6,6));d===1&&(c=[].concat(c).splice(0,f).concat(c));a.shift=0;if(b.length)for(a=c.length;b.length<a;)d=[].concat(b).splice(b.length-f,f),e&&(d[f-6]=d[f-2],d[f-5]=d[f-1]),b=b.concat(d);h&&(b=b.concat(h),c=c.concat(i));return[b,c]},step:function(a,b,c,d){var e=[],f=a.length;if(c===1)e=d;else if(f===b.length&&c<1)for(;f--;)d=
parseFloat(a[f]),e[f]=isNaN(d)?a[f]:c*parseFloat(b[f]-d)+d;else e=b;return e}};w&&w.init&&w.init(La);if(!w&&ca.jQuery){var ba=jQuery,Hc=ba.getScript,o=function(a,b){for(var c=0,d=a.length;c<d;c++)if(b.call(a[c],a[c],c,a)===!1)return c},nc=ba.grep,Vb=function(a,b){for(var c=[],d=0,e=a.length;d<e;d++)c[d]=b.call(a[d],a[d],d,a);return c},K=function(){var a=arguments;return ba.extend(!0,null,a[0],a[1],a[2],a[3])},Ac=function(a){return ba(a).offset()},ha=function(a,b,c){ba(a).bind(b,c)},Qa=function(a,
b,c){var d=x.removeEventListener?"removeEventListener":"detachEvent";x[d]&&!a[d]&&(a[d]=function(){});ba(a).unbind(b,c)},aa=function(a,b,c,d){var e=ba.Event(b),f="detached"+b,g;L(e,c);a[b]&&(a[f]=a[b],a[b]=null);o(["preventDefault","stopPropagation"],function(a){var b=e[a];e[a]=function(){try{b.call(e)}catch(c){a==="preventDefault"&&(g=!0)}}});ba(a).trigger(e);a[f]&&(a[b]=a[f],a[f]=null);d&&!e.isDefaultPrevented()&&!g&&d(e)},cc=function(a,b,c){var d=ba(a);if(b.d)a.toD=b.d,b.d=1;d.stop();d.animate(b,
c)},Ob=function(a){ba(a).stop()};ba.extend(ba.easing,{easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c}});var Ic=jQuery.fx,Jc=Ic.step;o(["cur","_default","width","height"],function(a,b){var c=b?Jc:Ic.prototype,d=c[a],e;d&&(c[a]=function(a){a=b?a:this;e=a.elem;return e.attr?e.attr(a.prop,a.now):d.apply(this,arguments)})});Jc.d=function(a){var b=a.elem;if(!a.started){var c=La.init(b,b.d,b.toD);a.start=c[0];a.end=c[1];a.started=!0}b.attr("d",La.step(a.start,a.end,a.pos,b.toD))}}w={enabled:!0,
align:"center",x:0,y:15,style:{color:"#666",fontSize:"11px",lineHeight:"14px"}};Ea={colors:"#4572A7,#AA4643,#89A54E,#80699B,#3D96AE,#DB843D,#92A8CD,#A47D7C,#B5CA92".split(","),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
decimalPoint:".",resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:","},global:{useUTC:!0,canvasToolsURL:"http://code.highcharts.com/2.2.1/modules/canvas-tools.js"},chart:{borderColor:"#4572A7",borderRadius:5,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacingTop:10,spacingRight:10,spacingBottom:15,spacingLeft:10,style:{fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif',fontSize:"12px"},backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0",
resetZoomButton:{theme:{zIndex:20},position:{align:"right",x:-10,y:10}}},title:{text:"Chart title",align:"center",y:15,style:{color:"#3E576F",fontSize:"16px"}},subtitle:{text:"",align:"center",y:30,style:{color:"#6D869F"}},plotOptions:{line:{allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},lineWidth:2,shadow:!0,marker:{enabled:!0,lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:K(w,
{enabled:!1,y:-6,formatter:function(){return this.y}}),cropThreshold:300,pointRange:0,showInLegend:!0,states:{hover:{marker:{}},select:{marker:{}}},stickyTracking:!0}},labels:{style:{position:wb,color:"#3E576F"}},legend:{enabled:!0,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderWidth:1,borderColor:"#909090",borderRadius:5,shadow:!1,style:{padding:"5px"},itemStyle:{cursor:"pointer",color:"#3E576F"},itemHoverStyle:{color:"#000000"},itemHiddenStyle:{color:"#C0C0C0"},
itemCheckboxStyle:{position:wb,width:"13px",height:"13px"},symbolWidth:16,symbolPadding:5,verticalAlign:"bottom",x:0,y:0},loading:{labelStyle:{fontWeight:"bold",position:mc,top:"1em"},style:{position:wb,backgroundColor:"white",opacity:0.5,textAlign:"center"}},tooltip:{enabled:!0,backgroundColor:"rgba(255, 255, 255, .85)",borderWidth:2,borderRadius:5,headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
shadow:!0,shared:Fa,snap:Ga?25:10,style:{color:"#333333",fontSize:"12px",padding:"5px",whiteSpace:"nowrap"}},credits:{enabled:!0,text:"Highcharts.com",href:"http://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#909090",fontSize:"10px"}}};var $b={dateTimeLabelFormats:za(Rb,"%H:%M:%S.%L",ob,"%H:%M:%S",pb,"%H:%M",va,"%H:%M",Ca,"%e. %b",Ya,"%e. %b",Da,"%b '%y",Za,"%Y"),endOnTick:!1,gridLineColor:"#C0C0C0",labels:w,lineColor:"#C0D0E0",lineWidth:1,
max:null,min:null,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0",minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickColor:"#C0D0E0",tickLength:5,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#6D869F",fontWeight:"bold"}},type:"linear"},kc=K($b,{endOnTick:!0,gridLineWidth:1,tickPixelInterval:72,showLastLabel:!0,labels:{align:"right",x:-8,
y:3},lineWidth:0,maxPadding:0.05,minPadding:0.05,startOnTick:!0,tickWidth:0,title:{rotation:270,text:"Y-values"},stackLabels:{enabled:!1,formatter:function(){return this.total},style:w.style}}),Pc={labels:{align:"right",x:-8,y:null},title:{rotation:270}},Oc={labels:{align:"left",x:8,y:null},title:{rotation:90}},zc={labels:{align:"center",x:0,y:14,overflow:"justify"},title:{rotation:0}},Nc=K(zc,{labels:{y:-5,overflow:"justify"}}),M=Ea.plotOptions,w=M.line;M.spline=K(w);M.scatter=K(w,{lineWidth:0,states:{hover:{lineWidth:0}},
tooltip:{headerFormat:'<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"}});M.area=K(w,{threshold:0});M.areaspline=K(M.area);M.column=K(w,{borderColor:"#FFFFFF",borderWidth:1,borderRadius:0,groupPadding:0.2,marker:null,pointPadding:0.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{brightness:0.1,shadow:!1},select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}},dataLabels:{y:null,verticalAlign:null},
threshold:0});M.bar=K(M.column,{dataLabels:{align:"left",x:5,y:null,verticalAlign:"middle"}});M.pie=K(w,{borderColor:"#FFFFFF",borderWidth:1,center:["50%","50%"],colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return this.point.name},y:5},legendType:"point",marker:null,size:"75%",showInLegend:!1,slicedOffset:10,states:{hover:{brightness:0.1,shadow:!1}}});vc();var ma=function(a){var b=[],c;(function(a){(c=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(a))?
b=[S(c[1]),S(c[2]),S(c[3]),parseFloat(c[4],10)]:(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(a))&&(b=[S(c[1],16),S(c[2],16),S(c[3],16),1])})(a);return{get:function(c){return b&&!isNaN(b[0])?c==="rgb"?"rgb("+b[0]+","+b[1]+","+b[2]+")":c==="a"?b[3]:"rgba("+b.join(",")+")":a},brighten:function(a){if(Bb(a)&&a!==0){var c;for(c=0;c<3;c++)b[c]+=S(a*255),b[c]<0&&(b[c]=0),b[c]>255&&(b[c]=255)}return this},setOpacity:function(a){b[3]=a;return this}}};Sa.prototype={init:function(a,b){this.element=
b==="span"?Aa(b):x.createElementNS("http://www.w3.org/2000/svg",b);this.renderer=a;this.attrSetters={}},animate:function(a,b,c){b=p(b,Ub,!0);Ob(this);if(b){b=K(b);if(c)b.complete=c;cc(this,a,b)}else this.attr(a),c&&c()},attr:function(a,b){var c,d,e,f,g=this.element,h=g.nodeName,i=this.renderer,k,j=this.attrSetters,l=this.shadows,n,o=this;Ab(a)&&s(b)&&(c=a,a={},a[c]=b);if(Ab(a))c=a,h==="circle"?c={x:"cx",y:"cy"}[c]||c:c==="strokeWidth"&&(c="stroke-width"),o=A(g,c)||this[c]||0,c!=="d"&&c!=="visibility"&&
(o=parseFloat(o));else for(c in a)if(k=!1,d=a[c],e=j[c]&&j[c](d,c),e!==!1){e!==X&&(d=e);if(c==="d")d&&d.join&&(d=d.join(" ")),/(NaN| {2}|^$)/.test(d)&&(d="M 0 0"),this.d=d;else if(c==="x"&&h==="text"){for(e=0;e<g.childNodes.length;e++)f=g.childNodes[e],A(f,"x")===A(g,"x")&&A(f,"x",d);this.rotation&&A(g,"transform","rotate("+this.rotation+" "+d+" "+S(a.y||A(g,"y"))+")")}else if(c==="fill")d=i.color(d,g,c);else if(h==="circle"&&(c==="x"||c==="y"))c={x:"cx",y:"cy"}[c]||c;else if(h==="rect"&&c==="r")A(g,
{rx:d,ry:d}),k=!0;else if(c==="translateX"||c==="translateY"||c==="rotation"||c==="verticalAlign")this[c]=d,this.updateTransform(),k=!0;else if(c==="stroke")d=i.color(d,g,c);else if(c==="dashstyle")if(c="stroke-dasharray",d=d&&d.toLowerCase(),d==="solid")d=Ma;else{if(d){d=d.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");
for(e=d.length;e--;)d[e]=S(d[e])*a["stroke-width"];d=d.join(",")}}else c==="isTracker"?this[c]=d:c==="width"?d=S(d):c==="align"?(c="text-anchor",d={left:"start",center:"middle",right:"end"}[d]):c==="title"&&(e=x.createElementNS("http://www.w3.org/2000/svg","title"),e.appendChild(x.createTextNode(d)),g.appendChild(e));c==="strokeWidth"&&(c="stroke-width");Ec&&c==="stroke-width"&&d===0&&(d=1.0E-6);this.symbolName&&/^(x|y|r|start|end|innerR|anchorX|anchorY)/.test(c)&&(n||(this.symbolAttr(a),n=!0),k=
!0);if(l&&/^(width|height|visibility|x|y|d|transform)$/.test(c))for(e=l.length;e--;)A(l[e],c,d);if((c==="width"||c==="height")&&h==="rect"&&d<0)d=0;c==="text"?(this.textStr=d,this.added&&i.buildText(this)):k||A(g,c,d)}if(Ec&&/Chrome\/(18|19)/.test(kb)&&h==="text"&&(a.x!==X||a.y!==X))c=g.parentNode,d=g.nextSibling,c&&(c.removeChild(g),d?c.insertBefore(g,d):c.appendChild(g));return o},symbolAttr:function(a){var b=this;o("x,y,r,start,end,width,height,innerR,anchorX,anchorY".split(","),function(c){b[c]=
p(a[c],b[c])});b.attr({d:b.renderer.symbols[b.symbolName](b.x,b.y,b.width,b.height,b)})},clip:function(a){return this.attr("clip-path","url("+this.renderer.url+"#"+a.id+")")},crisp:function(a,b,c,d,e){var f,g={},h={},i,a=a||this.strokeWidth||this.attr&&this.attr("stroke-width")||0;i=z(a)%2/2;h.x=Ta(b||this.x||0)+i;h.y=Ta(c||this.y||0)+i;h.width=Ta((d||this.width||0)-2*i);h.height=Ta((e||this.height||0)-2*i);h.strokeWidth=a;for(f in h)this[f]!==h[f]&&(this[f]=g[f]=h[f]);return g},css:function(a){var b=
this.element,b=a&&a.width&&b.nodeName==="text",c,d="",e=function(a,b){return"-"+b.toLowerCase()};if(a&&a.color)a.fill=a.color;this.styles=a=L(this.styles,a);if(Qb&&!Pb)b&&delete a.width,P(this.element,a);else{for(c in a)d+=c.replace(/([A-Z])/g,e)+":"+a[c]+";";this.attr({style:d})}b&&this.added&&this.renderer.buildText(this);return this},on:function(a,b){var c=b;Ga&&a==="click"&&(a="touchstart",c=function(a){a.preventDefault();b()});this.element["on"+a]=c;return this},translate:function(a,b){return this.attr({translateX:a,
translateY:b})},invert:function(){this.inverted=!0;this.updateTransform();return this},htmlCss:function(a){var b=this.element;if(b=a&&b.tagName==="SPAN"&&a.width)delete a.width,this.textWidth=b,this.updateTransform();this.styles=L(this.styles,a);P(this.element,a);return this},htmlGetBBox:function(a){var b=this.element,c=this.bBox;if(!c||a){if(b.nodeName==="text")b.style.position=wb;c=this.bBox={x:b.offsetLeft,y:b.offsetTop,width:b.offsetWidth,height:b.offsetHeight}}return c},htmlUpdateTransform:function(){if(this.added){var a=
this.renderer,b=this.element,c=this.translateX||0,d=this.translateY||0,e=this.x||0,f=this.y||0,g=this.textAlign||"left",h={left:0,center:0.5,right:1}[g],i=g&&g!=="left",k=this.shadows;if(c||d)P(b,{marginLeft:c,marginTop:d}),k&&o(k,function(a){P(a,{marginLeft:c+1,marginTop:d+1})});this.inverted&&o(b.childNodes,function(c){a.invertChild(c,b)});if(b.tagName==="SPAN"){var j,l,k=this.rotation,n;j=0;var t=1,r=0,Z;n=S(this.textWidth);var V=this.xCorr||0,v=this.yCorr||0,y=[k,g,b.innerHTML,this.textWidth].join(",");
if(y!==this.cTT)s(k)&&(j=k*Dc,t=ja(j),r=C(j),P(b,{filter:k?["progid:DXImageTransform.Microsoft.Matrix(M11=",t,", M12=",-r,", M21=",r,", M22=",t,", sizingMethod='auto expand')"].join(""):Ma})),j=p(this.elemWidth,b.offsetWidth),l=p(this.elemHeight,b.offsetHeight),j>n&&(P(b,{width:n+ga,display:"block",whiteSpace:"normal"}),j=n),n=a.fontMetrics(b.style.fontSize).b,V=t<0&&-j,v=r<0&&-l,Z=t*r<0,V+=r*n*(Z?1-h:h),v-=t*n*(k?Z?h:1-h:1),i&&(V-=j*h*(t<0?-1:1),k&&(v-=l*h*(r<0?-1:1)),P(b,{textAlign:g})),this.xCorr=
V,this.yCorr=v;P(b,{left:e+V+ga,top:f+v+ga});this.cTT=y}}else this.alignOnAdd=!0},updateTransform:function(){var a=this.translateX||0,b=this.translateY||0,c=this.inverted,d=this.rotation,e=[];c&&(a+=this.attr("width"),b+=this.attr("height"));(a||b)&&e.push("translate("+a+","+b+")");c?e.push("rotate(90) scale(-1,1)"):d&&e.push("rotate("+d+" "+this.x+" "+this.y+")");e.length&&A(this.element,"transform",e.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,
b,c){a?(this.alignOptions=a,this.alignByTranslate=b,c||this.renderer.alignedObjects.push(this)):(a=this.alignOptions,b=this.alignByTranslate);var c=p(c,this.renderer),d=a.align,e=a.verticalAlign,f=(c.x||0)+(a.x||0),g=(c.y||0)+(a.y||0),h={};/^(right|center)$/.test(d)&&(f+=(c.width-(a.width||0))/{right:1,center:2}[d]);h[b?"translateX":"x"]=z(f);/^(bottom|middle)$/.test(e)&&(g+=(c.height-(a.height||0))/({bottom:1,middle:2}[e]||1));h[b?"translateY":"y"]=z(g);this[this.placed?"animate":"attr"](h);this.placed=
!0;this.alignAttr=h;return this},getBBox:function(a){var b,c,d=this.rotation;c=this.element;var e=d*Dc;if(c.namespaceURI==="http://www.w3.org/2000/svg"){try{b=c.getBBox?L({},c.getBBox()):{width:c.offsetWidth,height:c.offsetHeight}}catch(f){}if(!b||b.width<0)b={width:0,height:0};a=b.width;c=b.height;if(d)b.width=Ba(c*C(e))+Ba(a*ja(e)),b.height=Ba(c*ja(e))+Ba(a*C(e))}else b=this.htmlGetBBox(a);return b},show:function(){return this.attr({visibility:eb})},hide:function(){return this.attr({visibility:ab})},
add:function(a){var b=this.renderer,c=a||b,d=c.element||b.box,e=d.childNodes,f=this.element,g=A(f,"zIndex"),h;this.parentInverted=a&&a.inverted;this.textStr!==void 0&&b.buildText(this);if(g)c.handleZ=!0,g=S(g);if(c.handleZ)for(c=0;c<e.length;c++)if(a=e[c],b=A(a,"zIndex"),a!==f&&(S(b)>g||!s(g)&&s(b))){d.insertBefore(f,a);h=!0;break}h||d.appendChild(f);this.added=!0;aa(this,"add");return this},safeRemoveChild:function(a){var b=a.parentNode;b&&b.removeChild(a)},destroy:function(){var a=this,b=a.element||
{},c=a.shadows,d=a.box,e,f;b.onclick=b.onmouseout=b.onmouseover=b.onmousemove=null;Ob(a);if(a.clipPath)a.clipPath=a.clipPath.destroy();if(a.stops){for(f=0;f<a.stops.length;f++)a.stops[f]=a.stops[f].destroy();a.stops=null}a.safeRemoveChild(b);c&&o(c,function(b){a.safeRemoveChild(b)});d&&d.destroy();Gb(a.renderer.alignedObjects,a);for(e in a)delete a[e];return null},empty:function(){for(var a=this.element,b=a.childNodes,c=b.length;c--;)a.removeChild(b[c])},shadow:function(a,b){var c=[],d,e,f=this.element,
g=this.parentInverted?"(-1,-1)":"(1,1)";if(a){for(d=1;d<=3;d++)e=f.cloneNode(0),A(e,{isShadow:"true",stroke:"rgb(0, 0, 0)","stroke-opacity":0.05*d,"stroke-width":7-2*d,transform:"translate"+g,fill:Ma}),b?b.element.appendChild(e):f.parentNode.insertBefore(e,f),c.push(e);this.shadows=c}return this}};var Eb=function(){this.init.apply(this,arguments)};Eb.prototype={Element:Sa,init:function(a,b,c,d){var e=location,f;f=this.createElement("svg").attr({xmlns:"http://www.w3.org/2000/svg",version:"1.1"});a.appendChild(f.element);
this.isSVG=!0;this.box=f.element;this.boxWrapper=f;this.alignedObjects=[];this.url=Qb?"":e.href.replace(/#.*?$/,"").replace(/([\('\)])/g,"\\$1");this.defs=this.createElement("defs").add();this.forExport=d;this.gradients={};this.setSize(b,c,!1)},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();Jb(this.gradients||{});this.gradients=null;if(a)this.defs=a.destroy();return this.alignedObjects=null},createElement:function(a){var b=new this.Element;b.init(this,a);
return b},draw:function(){},buildText:function(a){for(var b=a.element,c=p(a.textStr,"").toString().replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,"</span>").split(/<br.*?>/g),d=b.childNodes,e=/style="([^"]+)"/,f=/href="([^"]+)"/,g=A(b,"x"),h=a.styles,i=h&&S(h.width),k=h&&h.lineHeight,j,h=d.length;h--;)b.removeChild(d[h]);i&&!a.added&&this.box.appendChild(b);c[c.length-1]===""&&
c.pop();o(c,function(c,d){var h,r=0,p,c=c.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");h=c.split("|||");o(h,function(c){if(c!==""||h.length===1){var l={},o=x.createElementNS("http://www.w3.org/2000/svg","tspan");e.test(c)&&A(o,"style",c.match(e)[1].replace(/(;| |^)color([ :])/,"$1fill$2"));f.test(c)&&(A(o,"onclick",'location.href="'+c.match(f)[1]+'"'),P(o,{cursor:"pointer"}));c=(c.replace(/<(.|\n)*?>/g,"")||" ").replace(/</g,"<").replace(/>/g,">");o.appendChild(x.createTextNode(c));
r?l.dx=3:l.x=g;if(!r){if(d){!Pb&&a.renderer.forExport&&P(o,{display:"block"});p=ca.getComputedStyle&&S(ca.getComputedStyle(j,null).getPropertyValue("line-height"));if(!p||isNaN(p))p=k||j.offsetHeight||18;A(o,"dy",p)}j=o}A(o,l);b.appendChild(o);r++;if(i)for(var c=c.replace(/-/g,"- ").split(" "),q,T=[];c.length||T.length;)q=a.getBBox().width,l=q>i,!l||c.length===1?(c=T,T=[],c.length&&(o=x.createElementNS("http://www.w3.org/2000/svg","tspan"),A(o,{dy:k||16,x:g}),b.appendChild(o),q>i&&(i=q))):(o.removeChild(o.firstChild),
T.unshift(c.pop())),c.length&&o.appendChild(x.createTextNode(c.join(" ").replace(/- /g,"-")))}})})},button:function(a,b,c,d,e,f,g){var h=this.label(a,b,c),i=0,k,j,l,n,o,a={x1:0,y1:0,x2:0,y2:1},e=K(za("stroke-width",1,"stroke","#999","fill",za("linearGradient",a,"stops",[[0,"#FFF"],[1,"#DDD"]]),"r",3,"padding",3,"style",za("color","black")),e);l=e.style;delete e.style;f=K(e,za("stroke","#68A","fill",za("linearGradient",a,"stops",[[0,"#FFF"],[1,"#ACF"]])),f);n=f.style;delete f.style;g=K(e,za("stroke",
"#68A","fill",za("linearGradient",a,"stops",[[0,"#9BD"],[1,"#CDF"]])),g);o=g.style;delete g.style;ha(h.element,"mouseenter",function(){h.attr(f).css(n)});ha(h.element,"mouseleave",function(){k=[e,f,g][i];j=[l,n,o][i];h.attr(k).css(j)});h.setState=function(a){(i=a)?a===2&&h.attr(g).css(o):h.attr(e).css(l)};return h.on("click",function(){d.call(h)}).attr(e).css(L({cursor:"default"},l))},crispLine:function(a,b){a[1]===a[4]&&(a[1]=a[4]=z(a[1])+b%2/2);a[2]===a[5]&&(a[2]=a[5]=z(a[2])+b%2/2);return a},path:function(a){return this.createElement("path").attr({d:a,
fill:Ma})},circle:function(a,b,c){a=mb(a)?a:{x:a,y:b,r:c};return this.createElement("circle").attr(a)},arc:function(a,b,c,d,e,f){if(mb(a))b=a.y,c=a.r,d=a.innerR,e=a.start,f=a.end,a=a.x;return this.symbol("arc",a||0,b||0,c||0,c||0,{innerR:d||0,start:e||0,end:f||0})},rect:function(a,b,c,d,e,f){if(mb(a))b=a.y,c=a.width,d=a.height,e=a.r,f=a.strokeWidth,a=a.x;e=this.createElement("rect").attr({rx:e,ry:e,fill:Ma});return e.attr(e.crisp(f,a,b,W(c,0),W(d,0)))},setSize:function(a,b,c){var d=this.alignedObjects,
e=d.length;this.width=a;this.height=b;for(this.boxWrapper[p(c,!0)?"animate":"attr"]({width:a,height:b});e--;)d[e].align()},g:function(a){var b=this.createElement("g");return s(a)?b.attr({"class":Ia+a}):b},image:function(a,b,c,d,e){var f={preserveAspectRatio:Ma};arguments.length>1&&L(f,{x:b,y:c,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS?f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):f.element.setAttribute("hc-svg-href",a);return f},symbol:function(a,
b,c,d,e,f){var g,h=this.symbols[a],h=h&&h(z(b),z(c),d,e,f),i=/^url\((.*?)\)$/,k;if(h)g=this.path(h),L(g,{symbolName:a,x:b,y:c,width:d,height:e}),f&&L(g,f);else if(i.test(a)){var j=function(a,b){a.attr({width:b[0],height:b[1]}).translate(-z(b[0]/2),-z(b[1]/2))};k=a.match(i)[1];a=Fc[k];g=this.image(k).attr({x:b,y:c});a?j(g,a):(g.attr({width:0,height:0}),Aa("img",{onload:function(){j(g,Fc[k]=[this.width,this.height])},src:k}))}return g},symbols:{circle:function(a,b,c,d){var e=0.166*c;return[wa,a+c/2,
b,"C",a+c+e,b,a+c+e,b+d,a+c/2,b+d,"C",a-e,b+d,a-e,b,a+c/2,b,"Z"]},square:function(a,b,c,d){return[wa,a,b,fa,a+c,b,a+c,b+d,a,b+d,"Z"]},triangle:function(a,b,c,d){return[wa,a+c/2,b,fa,a+c,b+d,a,b+d,"Z"]},"triangle-down":function(a,b,c,d){return[wa,a,b,fa,a+c,b,a+c/2,b+d,"Z"]},diamond:function(a,b,c,d){return[wa,a+c/2,b,fa,a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]},arc:function(a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end-1.0E-6,d=e.innerR,h=ja(f),i=C(f),k=ja(g),g=C(g),e=e.end-f<da?0:1;return[wa,a+c*h,b+c*i,
"A",c,c,0,e,1,a+c*k,b+c*g,fa,a+d*k,b+d*g,"A",d,d,0,e,0,a+d*h,b+d*i,"Z"]}},clipRect:function(a,b,c,d){var e=Ia+lc++,f=this.createElement("clipPath").attr({id:e}).add(this.defs),a=this.rect(a,b,c,d,0).add(f);a.id=e;a.clipPath=f;return a},color:function(a,b,c){var d,e=/^rgba/;if(a&&a.linearGradient){var f=this,g=a.linearGradient,b=!Fb(g),c=f.gradients,h,i=g.x1||g[0]||0,k=g.y1||g[1]||0,j=g.x2||g[2]||0,l=g.y2||g[3]||0,n,t,r=[b,i,k,j,l,a.stops.join(",")].join(",");c[r]?g=A(c[r].element,"id"):(g=Ia+lc++,
h=f.createElement("linearGradient").attr(L({id:g,x1:i,y1:k,x2:j,y2:l},b?null:{gradientUnits:"userSpaceOnUse"})).add(f.defs),h.stops=[],o(a.stops,function(a){e.test(a[1])?(d=ma(a[1]),n=d.get("rgb"),t=d.get("a")):(n=a[1],t=1);a=f.createElement("stop").attr({offset:a[0],"stop-color":n,"stop-opacity":t}).add(h);h.stops.push(a)}),c[r]=h);return"url("+this.url+"#"+g+")"}else return e.test(a)?(d=ma(a),A(b,c+"-opacity",d.get("a")),d.get("rgb")):(b.removeAttribute(c+"-opacity"),a)},text:function(a,b,c,d){var e=
Ea.chart.style;if(d&&!this.forExport)return this.html(a,b,c);b=z(p(b,0));c=z(p(c,0));a=this.createElement("text").attr({x:b,y:c,text:a}).css({fontFamily:e.fontFamily,fontSize:e.fontSize});a.x=b;a.y=c;return a},html:function(a,b,c){var d=Ea.chart.style,e=this.createElement("span"),f=e.attrSetters,g=e.element,h=e.renderer;f.text=function(a){g.innerHTML=a;return!1};f.x=f.y=f.align=function(a,b){b==="align"&&(b="textAlign");e[b]=a;e.htmlUpdateTransform();return!1};e.attr({text:a,x:z(b),y:z(c)}).css({position:wb,
whiteSpace:"nowrap",fontFamily:d.fontFamily,fontSize:d.fontSize});e.css=e.htmlCss;if(h.isSVG)e.add=function(a){var b,c,d=h.box.parentNode;if(a){if(b=a.div,!b)b=a.div=Aa(Ra,{className:A(a.element,"class")},{position:wb,left:a.attr("translateX")+ga,top:a.attr("translateY")+ga},d),c=b.style,L(a.attrSetters,{translateX:function(a){c.left=a+ga},translateY:function(a){c.top=a+ga},visibility:function(a,b){c[b]=a}})}else b=d;b.appendChild(g);e.added=!0;e.alignOnAdd&&e.htmlUpdateTransform();return e};return e},
fontMetrics:function(a){var a=S(a||11),a=a<24?a+4:z(a*1.2),b=z(a*0.8);return{h:a,b:b}},label:function(a,b,c,d,e,f,g,h){function i(){var a=n.styles,a=a&&a.textAlign,b=v,c;c=h?0:ia;if(s(y)&&(a==="center"||a==="right"))b+={center:0.5,right:1}[a]*(y-p.width);(b!==t.x||c!==t.y)&&t.attr({x:b,y:c});t.x=b;t.y=c}function k(a,b){r?r.attr(a,b):x[a]=b}function j(){n.attr({text:a,x:b,y:c,anchorX:e,anchorY:f})}var l=this,n=l.g(),t=l.text("",0,0,g).attr({zIndex:1}).add(n),r,p,V="left",v=3,y,q,T,A,w=0,x={},ia,g=
n.attrSetters;ha(n,"add",j);g.width=function(a){y=a;return!1};g.height=function(a){q=a;return!1};g.padding=function(a){s(a)&&a!==v&&(v=a,i());return!1};g.align=function(a){V=a;return!1};g.text=function(a,b){t.attr(b,a);var c;c=t.element.style;p=(y===void 0||q===void 0||n.styles.textAlign)&&t.getBBox(!0);n.width=(y||p.width)+2*v;n.height=(q||p.height)+2*v;ia=v+l.fontMetrics(c&&c.fontSize).b;if(!r)c=h?-ia:0,n.box=r=d?l.symbol(d,0,c,n.width,n.height):l.rect(0,c,n.width,n.height,0,x["stroke-width"]),
r.add(n);r.attr(K({width:n.width,height:n.height},x));x=null;i();return!1};g["stroke-width"]=function(a,b){w=a%2/2;k(b,a);return!1};g.stroke=g.fill=g.r=function(a,b){k(b,a);return!1};g.anchorX=function(a,b){e=a;k(b,a+w-T);return!1};g.anchorY=function(a,b){f=a;k(b,a-A);return!1};g.x=function(a){a-={left:0,center:0.5,right:1}[V]*((y||p.width)+v);T=n.x=z(a);n.attr("translateX",T);return!1};g.y=function(a){A=n.y=z(a);n.attr("translateY",a);return!1};var ua=n.css;return L(n,{css:function(a){if(a){var b=
{},a=K({},a);o("fontSize,fontWeight,fontFamily,color,lineHeight,width".split(","),function(c){a[c]!==X&&(b[c]=a[c],delete a[c])});t.css(b)}return ua.call(n,a)},getBBox:function(){return r.getBBox()},shadow:function(a){r.shadow(a);return n},destroy:function(){Qa(n,"add",j);Qa(n.element,"mouseenter");Qa(n.element,"mouseleave");t&&(t=t.destroy());Sa.prototype.destroy.call(n)}})}};Xb=Eb;var $a;if(!Pb&&!Fa)$a={init:function(a,b){var c=["<",b,' filled="f" stroked="f"'],d=["position: ",wb,";"];(b==="shape"||
b===Ra)&&d.push("left:0;top:0;width:10px;height:10px;");Xa&&d.push("visibility: ",b===Ra?ab:eb);c.push(' style="',d.join(""),'"/>');if(b)c=b===Ra||b==="span"||b==="img"?c.join(""):a.prepVML(c),this.element=Aa(c);this.renderer=a;this.attrSetters={}},add:function(a){var b=this.renderer,c=this.element,d=b.box,d=a?a.element||a:d;a&&a.inverted&&b.invertChild(c,d);Xa&&d.gVis===ab&&P(c,{visibility:ab});d.appendChild(c);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform();aa(this,
"add");return this},toggleChildren:function(a,b){for(var c=a.childNodes,d=c.length;d--;)P(c[d],{visibility:b}),c[d].nodeName==="DIV"&&this.toggleChildren(c[d],b)},updateTransform:Sa.prototype.htmlUpdateTransform,attr:function(a,b){var c,d,e,f=this.element||{},g=f.style,h=f.nodeName,i=this.renderer,k=this.symbolName,j,l=this.shadows,n,o=this.attrSetters,r=this;Ab(a)&&s(b)&&(c=a,a={},a[c]=b);if(Ab(a))c=a,r=c==="strokeWidth"||c==="stroke-width"?this.strokeweight:this[c];else for(c in a)if(d=a[c],n=!1,
e=o[c]&&o[c](d,c),e!==!1&&d!==null){e!==X&&(d=e);if(k&&/^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(c))j||(this.symbolAttr(a),j=!0),n=!0;else if(c==="d"){d=d||[];this.d=d.join(" ");e=d.length;for(n=[];e--;)n[e]=Bb(d[e])?z(d[e]*10)-5:d[e]==="Z"?"x":d[e];d=n.join(" ")||"x";f.path=d;if(l)for(e=l.length;e--;)l[e].path=d;n=!0}else if(c==="zIndex"||c==="visibility"){if(Xa&&c==="visibility"&&h==="DIV")f.gVis=d,this.toggleChildren(f,d),d===eb&&(d=null);d&&(g[c]=d);n=!0}else if(c==="width"||
c==="height")d=W(0,d),this[c]=d,this.updateClipping?(this[c]=d,this.updateClipping()):g[c]=d,n=!0;else if(c==="x"||c==="y")this[c]=d,g[{x:"left",y:"top"}[c]]=d;else if(c==="class")f.className=d;else if(c==="stroke")d=i.color(d,f,c),c="strokecolor";else if(c==="stroke-width"||c==="strokeWidth")f.stroked=d?!0:!1,c="strokeweight",this[c]=d,Bb(d)&&(d+=ga);else if(c==="dashstyle")(f.getElementsByTagName("stroke")[0]||Aa(i.prepVML(["<stroke/>"]),null,null,f))[c]=d||"solid",this.dashstyle=d,n=!0;else if(c===
"fill")h==="SPAN"?g.color=d:(f.filled=d!==Ma?!0:!1,d=i.color(d,f,c),c="fillcolor");else if(c==="translateX"||c==="translateY"||c==="rotation")this[c]=d,this.updateTransform(),n=!0;else if(c==="text")this.bBox=null,f.innerHTML=d,n=!0;if(l&&c==="visibility")for(e=l.length;e--;)l[e].style[c]=d;n||(Xa?f[c]=d:A(f,c,d))}return r},clip:function(a){var b=this,c=a.members;c.push(b);b.destroyClip=function(){Gb(c,b)};return b.css(a.getCSS(b.inverted))},css:Sa.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&
Tb(a)},destroy:function(){this.destroyClip&&this.destroyClip();return Sa.prototype.destroy.apply(this)},empty:function(){for(var a=this.element.childNodes,b=a.length,c;b--;)c=a[b],c.parentNode.removeChild(c)},on:function(a,b){this.element["on"+a]=function(){var a=ca.event;a.target=a.srcElement;b(a)};return this},shadow:function(a,b){var c=[],d,e=this.element,f=this.renderer,g,h=e.style,i,k=e.path;k&&typeof k.value!=="string"&&(k="x");if(a){for(d=1;d<=3;d++)i=['<shape isShadow="true" strokeweight="',
7-2*d,'" filled="false" path="',k,'" coordsize="100,100" style="',e.style.cssText,'" />'],g=Aa(f.prepVML(i),null,{left:S(h.left)+1,top:S(h.top)+1}),i=['<stroke color="black" opacity="',0.05*d,'"/>'],Aa(f.prepVML(i),null,null,g),b?b.element.appendChild(g):e.parentNode.insertBefore(g,e),c.push(g);this.shadows=c}return this}},$a=pa(Sa,$a),w={Element:$a,isIE8:kb.indexOf("MSIE 8.0")>-1,init:function(a,b,c){var d,e;this.alignedObjects=[];d=this.createElement(Ra);e=d.element;e.style.position=mc;a.appendChild(d.element);
this.box=e;this.boxWrapper=d;this.setSize(b,c,!1);if(!x.namespaces.hcv)x.namespaces.add("hcv","urn:schemas-microsoft-com:vml"),x.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "},clipRect:function(a,b,c,d){var e=this.createElement();return L(e,{members:[],left:a,top:b,width:c,height:d,getCSS:function(a){var b=this.top,c=this.left,d=c+this.width,e=b+this.height,b={clip:"rect("+z(a?c:b)+"px,"+z(a?e:d)+"px,"+z(a?d:e)+
"px,"+z(a?b:c)+"px)"};!a&&Xa&&L(b,{width:d+ga,height:e+ga});return b},updateClipping:function(){o(e.members,function(a){a.css(e.getCSS(a.inverted))})}})},color:function(a,b,c){var d,e=/^rgba/;if(a&&a.linearGradient){var f,g,h=a.linearGradient,i=h.x1||h[0]||0,k=h.y1||h[1]||0,j=h.x2||h[2]||0,h=h.y2||h[3]||0,l,n,p,r;o(a.stops,function(a,b){e.test(a[1])?(d=ma(a[1]),f=d.get("rgb"),g=d.get("a")):(f=a[1],g=1);b?(p=f,r=g):(l=f,n=g)});if(c==="fill")a=90-oa.atan((h-k)/(j-i))*180/da,a=['<fill colors="0% ',l,
",100% ",p,'" angle="',a,'" opacity="',r,'" o:opacity2="',n,'" type="gradient" focus="100%" method="sigma" />'],Aa(this.prepVML(a),null,null,b);else return f}else if(e.test(a)&&b.tagName!=="IMG")return d=ma(a),a=["<",c,' opacity="',d.get("a"),'"/>'],Aa(this.prepVML(a),null,null,b),d.get("rgb");else{b=b.getElementsByTagName(c);if(b.length)b[0].opacity=1;return a}},prepVML:function(a){var b=this.isIE8,a=a.join("");b?(a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />'),a=a.indexOf('style="')===
-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'):a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')):a=a.replace("<","<hcv:");return a},text:Eb.prototype.html,path:function(a){return this.createElement("shape").attr({coordsize:"100 100",d:a})},circle:function(a,b,c){return this.symbol("circle").attr({x:a-c,y:b-c,width:2*c,height:2*c})},g:function(a){var b;a&&(b={className:Ia+a,"class":Ia+a});return this.createElement(Ra).attr(b)},image:function(a,
b,c,d,e){var f=this.createElement("img").attr({src:a});arguments.length>1&&f.css({left:b,top:c,width:d,height:e});return f},rect:function(a,b,c,d,e,f){if(mb(a))b=a.y,c=a.width,d=a.height,f=a.strokeWidth,a=a.x;var g=this.symbol("rect");g.r=e;return g.attr(g.crisp(f,a,b,W(c,0),W(d,0)))},invertChild:function(a,b){var c=b.style;P(a,{flip:"x",left:S(c.width)-10,top:S(c.height)-10,rotation:-90})},symbols:{arc:function(a,b,c,d,e){var f=e.start,g=e.end,c=e.r||c||d,d=ja(f),h=C(f),i=ja(g),k=C(g),e=e.innerR,
j=0.08/c,l=e&&0.25/e||0;if(g-f===0)return["x"];else 2*da-g+f<j?i=-j:g-f<l&&(i=ja(f+l));return["wa",a-c,b-c,a+c,b+c,a+c*d,b+c*h,a+c*i,b+c*k,"at",a-e,b-e,a+e,b+e,a+e*i,b+e*k,a+e*d,b+e*h,"x","e"]},circle:function(a,b,c,d){return["wa",a,b,a+c,b+d,a+c,b+d/2,a+c,b+d/2,"e"]},rect:function(a,b,c,d,e){if(!s(e))return[];var f=a+c,g=b+d,c=Ua(e.r||0,c,d);return[wa,a+c,b,fa,f-c,b,"wa",f-2*c,b,f,b+2*c,f-c,b,f,b+c,fa,f,g-c,"wa",f-2*c,g-2*c,f,g,f,g-c,f-c,g,fa,a+c,g,"wa",a,g-2*c,a+2*c,g,a+c,g,a,g-c,fa,a,b+c,"wa",
a,b,a+2*c,b+2*c,a,b+c,a+c,b,"x","e"]}}},$a=function(){this.init.apply(this,arguments)},$a.prototype=K(Eb.prototype,w),Xb=$a;var oc,Cc;Fa&&(oc=function(){},Cc=function(){function a(){var a=b.length,d;for(d=0;d<a;d++)b[d]();b=[]}var b=[];return{push:function(c,d){b.length===0&&Hc(d,a);b.push(c)}}}());Xb=$a||oc||Eb;wc.prototype.callbacks=[];var lb=function(){};lb.prototype={init:function(a,b,c){var d=a.chart.counters;this.series=a;this.applyOptions(b,c);this.pointAttr={};if(a.options.colorByPoint){b=
a.chart.options.colors;if(!this.options)this.options={};this.color=this.options.color=this.color||b[d.color++];d.wrapColor(b.length)}a.chart.pointCount++;return this},applyOptions:function(a,b){var c=this.series,d=typeof a;this.config=a;if(d==="number"||a===null)this.y=a;else if(typeof a[0]==="number")this.x=a[0],this.y=a[1];else if(d==="object"&&typeof a.length!=="number"){if(L(this,a),this.options=a,a.dataLabels)c._hasPointLabels=!0}else if(typeof a[0]==="string")this.name=a[0],this.y=a[1];if(this.x===
X)this.x=b===X?c.autoIncrement():b},destroy:function(){var a=this.series,b=a.chart.hoverPoints,c;a.chart.pointCount--;b&&(this.setState(),Gb(b,this));if(this===a.chart.hoverPoint)this.onMouseOut();a.chart.hoverPoints=null;if(this.graphic||this.dataLabel)Qa(this),this.destroyElements();this.legendItem&&this.series.chart.legend.destroyItem(this);for(c in this)this[c]=null},destroyElements:function(){for(var a="graphic,tracker,dataLabel,group,connector,shadowGroup".split(","),b,c=6;c--;)b=a[c],this[b]&&
(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},select:function(a,b){var c=this,d=c.series.chart,a=p(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=a;c.setState(a&&"select");b||o(d.getSelectedPoints(),function(a){if(a.selected&&a!==c)a.selected=!1,a.setState(Ka),a.firePointEvent("unselect")})})},
onMouseOver:function(){var a=this.series,b=a.chart,c=b.tooltip,d=b.hoverPoint;if(d&&d!==this)d.onMouseOut();this.firePointEvent("mouseOver");c&&(!c.shared||a.noSharedTooltip)&&c.refresh(this);this.setState(ta);b.hoverPoint=this},onMouseOut:function(){this.firePointEvent("mouseOut");this.setState();this.series.chart.hoverPoint=null},tooltipFormatter:function(a){var b=this.series,c=b.tooltipOptions,d=String(this.y).split("."),d=d[1]?d[1].length:0,e=a.match(/\{(series|point)\.[a-zA-Z]+\}/g),f=/[{\.}]/,
g,h,i,k;for(k in e)h=e[k],Ab(h)&&h!==a&&(i=(" "+h).split(f),g={point:this,series:b}[i[1]],i=i[2],g=g===this&&(i==="y"||i==="open"||i==="high"||i==="low"||i==="close")?(c.valuePrefix||c.yPrefix||"")+dc(this[i],p(c.valueDecimals,c.yDecimals,d))+(c.valueSuffix||c.ySuffix||""):g[i],a=a.replace(h,g));return a},update:function(a,b,c){var d=this,e=d.series,f=d.graphic,g,h=e.data,i=h.length,k=e.chart,b=p(b,!0);d.firePointEvent("update",{options:a},function(){d.applyOptions(a);mb(a)&&(e.getAttribs(),f&&f.attr(d.pointAttr[e.state]));
for(g=0;g<i;g++)if(h[g]===d){e.xData[g]=d.x;e.yData[g]=d.y;e.options.data[g]=a;break}e.isDirty=!0;e.isDirtyData=!0;b&&k.redraw(c)})},remove:function(a,b){var c=this,d=c.series,e=d.chart,f,g=d.data,h=g.length;Kb(b,e);a=p(a,!0);c.firePointEvent("remove",null,function(){for(f=0;f<h;f++)if(g[f]===c){g.splice(f,1);d.options.data.splice(f,1);d.xData.splice(f,1);d.yData.splice(f,1);break}c.destroy();d.isDirty=!0;d.isDirtyData=!0;a&&e.redraw()})},firePointEvent:function(a,b,c){var d=this,e=this.series.options;
(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();a==="click"&&e.allowPointSelect&&(c=function(a){d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});aa(this,a,b,c)},importEvents:function(){if(!this.hasImportedEvents){var a=K(this.series.options.point,this.options).events,b;this.events=a;for(b in a)ha(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a){var b=this.plotX,c=this.plotY,d=this.series,e=d.options.states,f=M[d.type].marker&&d.options.marker,
g=f&&!f.enabled,h=f&&f.states[a],i=h&&h.enabled===!1,k=d.stateMarkerGraphic,j=d.chart,l=this.pointAttr,a=a||Ka;if(!(a===this.state||this.selected&&a!=="select"||e[a]&&e[a].enabled===!1||a&&(i||g&&!h.enabled))){if(this.graphic)e=f&&this.graphic.symbolName&&l[a].r,this.graphic.attr(K(l[a],e?{x:b-e,y:c-e,width:2*e,height:2*e}:{}));else{if(a){if(!k)e=f.radius,d.stateMarkerGraphic=k=j.renderer.symbol(d.symbol,-e,-e,2*e,2*e).attr(l[a]).add(d.group);k.translate(b,c)}if(k)k[a?"show":"hide"]()}this.state=
a}}};var $=function(){};$.prototype={isCartesian:!0,type:"line",pointClass:lb,sorted:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},init:function(a,b){var c,d;d=a.series.length;this.chart=a;this.options=b=this.setOptions(b);this.bindAxes();L(this,{index:d,name:b.name||"Series "+(d+1),state:Ka,pointAttr:{},visible:b.visible!==!1,selected:b.selected===!0});if(Fa)b.animation=!1;d=b.events;for(c in d)ha(this,c,d[c]);if(d&&d.click||b.point&&b.point.events&&
b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;this.getColor();this.getSymbol();this.setData(b.data,!1)},bindAxes:function(){var a=this,b=a.options,c=a.chart,d;a.isCartesian&&o(["xAxis","yAxis"],function(e){o(c[e],function(c){d=c.options;if(b[e]===d.index||b[e]===X&&d.index===0)c.series.push(a),a[e]=c,c.isDirty=!0})})},autoIncrement:function(){var a=this.options,b=this.xIncrement,b=p(b,a.pointStart,0);this.pointInterval=p(this.pointInterval,a.pointInterval,1);this.xIncrement=b+this.pointInterval;
return b},getSegments:function(){var a=-1,b=[],c,d=this.points,e=d.length;if(e)if(this.options.connectNulls){for(c=e;c--;)d[c].y===null&&d.splice(c,1);d.length&&(b=[d])}else o(d,function(c,g){c.y===null?(g>a+1&&b.push(d.slice(a+1,g)),a=g):g===e-1&&b.push(d.slice(a+1,g+1))});this.segments=b},setOptions:function(a){var b=this.chart.options,c=b.plotOptions,d=a.data;a.data=null;c=K(c[this.type],c.series,a);c.data=a.data=d;this.tooltipOptions=K(b.tooltip,c.tooltip);return c},getColor:function(){var a=
this.chart.options.colors,b=this.chart.counters;this.color=this.options.color||a[b.color++]||"#0000ff";b.wrapColor(a.length)},getSymbol:function(){var a=this.options.marker,b=this.chart,c=b.options.symbols,b=b.counters;this.symbol=a.symbol||c[b.symbol++];if(/^url/.test(this.symbol))a.radius=0;b.wrapSymbol(c.length)},addPoint:function(a,b,c,d){var e=this.data,f=this.graph,g=this.area,h=this.chart,i=this.xData,k=this.yData,j=f&&f.shift||0,l=this.options.data;Kb(d,h);if(f&&c)f.shift=j+1;if(g){if(c)g.shift=
j+1;g.isArea=!0}b=p(b,!0);d={series:this};this.pointClass.prototype.applyOptions.apply(d,[a]);i.push(d.x);k.push(this.valueCount===4?[d.open,d.high,d.low,d.close]:d.y);l.push(a);c&&(e[0]?e[0].remove(!1):(e.shift(),i.shift(),k.shift(),l.shift()));this.getAttribs();this.isDirtyData=this.isDirty=!0;b&&h.redraw()},setData:function(a,b){var c=this.points,d=this.options,e=this.initialColor,f=this.chart,g=null;this.xIncrement=null;this.pointRange=this.xAxis&&this.xAxis.categories&&1||d.pointRange;if(s(e))f.counters.color=
e;var h=[],i=[],k=a?a.length:[],j=this.valueCount===4;if(k>(d.turboThreshold||1E3)){for(e=0;g===null&&e<k;)g=a[e],e++;if(Bb(g)){g=p(d.pointStart,0);d=p(d.pointInterval,1);for(e=0;e<k;e++)h[e]=g,i[e]=a[e],g+=d;this.xIncrement=g}else if(Fb(g))if(j)for(e=0;e<k;e++)d=a[e],h[e]=d[0],i[e]=d.slice(1,5);else for(e=0;e<k;e++)d=a[e],h[e]=d[0],i[e]=d[1]}else for(e=0;e<k;e++)d={series:this},this.pointClass.prototype.applyOptions.apply(d,[a[e]]),h[e]=d.x,i[e]=j?[d.open,d.high,d.low,d.close]:d.y;this.data=[];this.options.data=
a;this.xData=h;this.yData=i;for(e=c&&c.length||0;e--;)c[e]&&c[e].destroy&&c[e].destroy();this.isDirty=this.isDirtyData=f.isDirtyBox=!0;p(b,!0)&&f.redraw(!1)},remove:function(a,b){var c=this,d=c.chart,a=p(a,!0);if(!c.isRemoving)c.isRemoving=!0,aa(c,"remove",null,function(){c.destroy();d.isDirtyLegend=d.isDirtyBox=!0;a&&d.redraw(b)});c.isRemoving=!1},processData:function(a){var b=this.xData,c=this.yData,d=b.length,e=0,f=d,g,h,i=this.xAxis,k=this.options,j=k.cropThreshold,l=this.isCartesian;if(l&&!this.isDirty&&
!i.isDirty&&!this.yAxis.isDirty&&!a)return!1;if(l&&this.sorted&&(!j||d>j||this.forceCrop))if(a=i.getExtremes(),i=a.min,j=a.max,b[d-1]<i||b[0]>j)b=[],c=[];else if(b[0]<i||b[d-1]>j){for(a=0;a<d;a++)if(b[a]>=i){e=W(0,a-1);break}for(;a<d;a++)if(b[a]>j){f=a+1;break}b=b.slice(e,f);c=c.slice(e,f);g=!0}for(a=b.length-1;a>0;a--)if(d=b[a]-b[a-1],d>0&&(h===X||d<h))h=d;this.cropped=g;this.cropStart=e;this.processedXData=b;this.processedYData=c;if(k.pointRange===null)this.pointRange=h||1;this.closestPointRange=
h},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,e=this.processedYData,f=this.pointClass,g=d.length,h=this.cropStart||0,i,k=this.hasGroupedData,j,l=[],n;if(!b&&!k)b=[],b.length=a.length,b=this.data=b;for(n=0;n<g;n++)i=h+n,k?l[n]=(new f).init(this,[d[n]].concat(Hb(e[n]))):(b[i]?j=b[i]:b[i]=j=(new f).init(this,a[i],d[n]),l[n]=j);if(b&&(g!==(c=b.length)||k))for(n=0;n<c;n++)n===h&&!k&&(n+=g),b[n]&&b[n].destroyElements();this.data=b;this.points=l},translate:function(){this.processedXData||
this.processData();this.generatePoints();for(var a=this.chart,b=this.options,c=b.stacking,d=this.xAxis,e=d.categories,f=this.yAxis,g=this.points,h=g.length,i=!!this.modifyValue,k,j=f.series,l=j.length;l--;)if(j[l].visible){l===this.index&&(k=!0);break}for(l=0;l<h;l++){var j=g[l],n=j.x,o=j.y,r=j.low,p=f.stacks[(o<b.threshold?"-":"")+this.stackKey];j.plotX=z(d.translate(n,0,0,0,1)*10)/10;if(c&&this.visible&&p&&p[n]){r=p[n];n=r.total;r.cum=r=r.cum-o;o=r+o;if(k)r=b.threshold;c==="percent"&&(r=n?r*100/
n:0,o=n?o*100/n:0);j.percentage=n?j.y*100/n:0;j.stackTotal=n;j.stackY=o}j.yBottom=s(r)?f.translate(r,0,1,0,1):null;i&&(o=this.modifyValue(o,j));j.plotY=typeof o==="number"?z(f.translate(o,0,1,0,1)*10)/10:X;j.clientX=a.inverted?a.plotHeight-j.plotX:j.plotX;j.category=e&&e[j.x]!==X?e[j.x]:j.x}this.getSegments()},setTooltipPoints:function(a){var b=this.chart,c=b.inverted,d=[],b=z((c?b.plotTop:b.plotLeft)+b.plotSizeX),e,f;e=this.xAxis;var g,h,i=[];if(this.options.enableMouseTracking!==!1){if(a)this.tooltipPoints=
null;o(this.segments||this.points,function(a){d=d.concat(a)});e&&e.reversed&&(d=d.reverse());a=d.length;for(h=0;h<a;h++){g=d[h];e=d[h-1]?d[h-1]._high+1:0;for(f=g._high=d[h+1]?Ta((g.plotX+(d[h+1]?d[h+1].plotX:b))/2):b;e<=f;)i[c?b-e++:e++]=g}this.tooltipPoints=i}},tooltipHeaderFormatter:function(a){var b=this.tooltipOptions,c=b.xDateFormat||"%A, %b %e, %Y",d=this.xAxis;return b.headerFormat.replace("{point.key}",d&&d.options.type==="datetime"?ac(c,a):a).replace("{series.name}",this.name).replace("{series.color}",
this.color)},onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(Ga||!a.mouseIsDown){if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&aa(this,"mouseOver");this.setState(ta);a.hoverSeries=this}},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;if(d)d.onMouseOut();this&&a.events.mouseOut&&aa(this,"mouseOut");c&&!a.stickyTracking&&!c.shared&&c.hide();this.setState();b.hoverSeries=null},animate:function(a){var b=this.chart,c=this.clipRect,d=this.options.animation;
d&&!mb(d)&&(d={});if(a){if(!c.isAnimating)c.attr("width",0),c.isAnimating=!0}else c.animate({width:b.plotSizeX},d),this.animate=null},drawPoints:function(){var a,b=this.points,c=this.chart,d,e,f,g,h,i,k,j;if(this.options.marker.enabled)for(f=b.length;f--;)if(g=b[f],d=g.plotX,e=g.plotY,j=g.graphic,e!==X&&!isNaN(e))if(a=g.pointAttr[g.selected?"select":Ka],h=a.r,i=p(g.marker&&g.marker.symbol,this.symbol),k=i.indexOf("url")===0,j)j.animate(L({x:d-h,y:e-h},j.symbolName?{width:2*h,height:2*h}:{}));else if(h>
0||k)g.graphic=c.renderer.symbol(i,d-h,e-h,2*h,2*h).attr(a).add(this.group)},convertAttribs:function(a,b,c,d){var e=this.pointAttrToOptions,f,g,h={},a=a||{},b=b||{},c=c||{},d=d||{};for(f in e)g=e[f],h[f]=p(a[g],b[f],c[f],d[f]);return h},getAttribs:function(){var a=this,b=M[a.type].marker?a.options.marker:a.options,c=b.states,d=c[ta],e,f=a.color,g={stroke:f,fill:f},h=a.points,i=[],k,j=a.pointAttrToOptions,l;a.options.marker?(d.radius=d.radius||b.radius+2,d.lineWidth=d.lineWidth||b.lineWidth+1):d.color=
d.color||ma(d.color||f).brighten(d.brightness).get();i[Ka]=a.convertAttribs(b,g);o([ta,"select"],function(b){i[b]=a.convertAttribs(c[b],i[Ka])});a.pointAttr=i;for(f=h.length;f--;){g=h[f];if((b=g.options&&g.options.marker||g.options)&&b.enabled===!1)b.radius=0;e=!1;if(g.options)for(l in j)s(b[j[l]])&&(e=!0);if(e){k=[];c=b.states||{};e=c[ta]=c[ta]||{};if(!a.options.marker)e.color=ma(e.color||g.options.color).brighten(e.brightness||d.brightness).get();k[Ka]=a.convertAttribs(b,i[Ka]);k[ta]=a.convertAttribs(c[ta],
i[ta],k[Ka]);k.select=a.convertAttribs(c.select,i.select,k[Ka])}else k=i;g.pointAttr=k}},destroy:function(){var a=this,b=a.chart,c=a.clipRect,d=/AppleWebKit\/533/.test(kb),e,f,g=a.data||[],h,i,k;aa(a,"destroy");Qa(a);o(["xAxis","yAxis"],function(b){if(k=a[b])Gb(k.series,a),k.isDirty=!0});a.legendItem&&a.chart.legend.destroyItem(a);for(f=g.length;f--;)(h=g[f])&&h.destroy&&h.destroy();a.points=null;if(c&&c!==b.clipRect)a.clipRect=c.destroy();o(["area","graph","dataLabelsGroup","group","tracker"],function(b){a[b]&&
(e=d&&b==="group"?"hide":"destroy",a[b][e]())});if(b.hoverSeries===a)b.hoverSeries=null;Gb(b.series,a);for(i in a)delete a[i]},drawDataLabels:function(){var a=this,b=a.options,c=b.dataLabels;if(c.enabled||a._hasPointLabels){var d,e,f=a.points,g,h,i,k=a.dataLabelsGroup,j=a.chart,l=a.xAxis,l=l?l.left:j.plotLeft,n=a.yAxis,n=n?n.top:j.plotTop,t=j.renderer,r=j.inverted,Z=a.type,V=b.stacking,v=Z==="column"||Z==="bar",y=c.verticalAlign===null,q=c.y===null,T=t.fontMetrics(c.style.fontSize),A=T.h,x=T.b,w,
ia;v&&(T={top:x,middle:x-A/2,bottom:-A+x},V?(y&&(c=K(c,{verticalAlign:"middle"})),q&&(c=K(c,{y:T[c.verticalAlign]}))):y?c=K(c,{verticalAlign:"top"}):q&&(c=K(c,{y:T[c.verticalAlign]})));k?k.translate(l,n):k=a.dataLabelsGroup=t.g("data-labels").attr({visibility:a.visible?eb:ab,zIndex:6}).translate(l,n).add();h=c;o(f,function(f){w=f.dataLabel;c=h;(g=f.options)&&g.dataLabels&&(c=K(c,g.dataLabels));if(ia=c.enabled){var l=f.barX&&f.barX+f.barW/2||p(f.plotX,-999),n=p(f.plotY,-999),o=c.y===null?f.y>=b.threshold?
-A+x:x:c.y;d=(r?j.plotWidth-n:l)+c.x;e=z((r?j.plotHeight-l:n)+o)}if(w&&a.isCartesian&&(!j.isInsidePlot(d,e)||!ia))f.dataLabel=w.destroy();else if(ia){l=c.align;i=c.formatter.call(f.getLabelConfig(),c);Z==="column"&&(d+={left:-1,right:1}[l]*f.barW/2||0);!V&&r&&f.y<0&&(l="right",d-=10);c.style.color=p(c.color,c.style.color,a.color,"black");if(w)w.attr({text:i}).animate({x:d,y:e});else if(s(i))w=f.dataLabel=t[c.rotation?"text":"label"](i,d,e,null,null,null,c.useHTML,!0).attr({align:l,fill:c.backgroundColor,
stroke:c.borderColor,"stroke-width":c.borderWidth,r:c.borderRadius,rotation:c.rotation,padding:c.padding,zIndex:1}).css(c.style).add(k).shadow(c.shadow);if(v&&b.stacking&&w)l=f.barX,n=f.barY,o=f.barW,f=f.barH,w.align(c,null,{x:r?j.plotWidth-n-f:l,y:r?j.plotHeight-l-o:n,width:r?f:o,height:r?o:f})}})}},drawGraph:function(){var a=this,b=a.options,c=a.graph,d=[],e,f=a.area,g=a.group,h=b.lineColor||a.color,i=b.lineWidth,k=b.dashStyle,j,l=a.chart.renderer,n=a.yAxis.getThreshold(b.threshold),t=/^area/.test(a.type),
r=[],s=[];o(a.segments,function(c){j=[];o(c,function(d,e){a.getPointSpline?j.push.apply(j,a.getPointSpline(c,d,e)):(j.push(e?fa:wa),e&&b.step&&j.push(d.plotX,c[e-1].plotY),j.push(d.plotX,d.plotY))});c.length>1?d=d.concat(j):r.push(c[0]);if(t){var e=[],f,g=j.length;for(f=0;f<g;f++)e.push(j[f]);g===3&&e.push(fa,j[1],j[2]);if(b.stacking&&a.type!=="areaspline")for(f=c.length-1;f>=0;f--)f<c.length-1&&b.step&&e.push(c[f+1].plotX,c[f].yBottom),e.push(c[f].plotX,c[f].yBottom);else e.push(fa,c[c.length-1].plotX,
n,fa,c[0].plotX,n);s=s.concat(e)}});a.graphPath=d;a.singlePoints=r;if(t)e=p(b.fillColor,ma(a.color).setOpacity(b.fillOpacity||0.75).get()),f?f.animate({d:s}):a.area=a.chart.renderer.path(s).attr({fill:e}).add(g);if(c)Ob(c),c.animate({d:d});else if(i){c={stroke:h,"stroke-width":i};if(k)c.dashstyle=k;a.graph=l.path(d).attr(c).add(g).shadow(b.shadow)}},invertGroups:function(){function a(){var a={width:b.yAxis.len,height:b.xAxis.len};c.attr(a).invert();d&&d.attr(a).invert()}var b=this,c=b.group,d=b.trackerGroup,
e=b.chart;ha(e,"resize",a);ha(b,"destroy",function(){Qa(e,"resize",a)});a();b.invertGroups=a},render:function(){var a=this,b=a.chart,c,d=a.options,e=d.clip!==!1,f=d.animation,g=f&&a.animate,f=g?f&&f.duration||500:0,h=a.clipRect,i=b.renderer;if(!h&&(h=a.clipRect=!b.hasRendered&&b.clipRect?b.clipRect:i.clipRect(0,0,b.plotSizeX,b.plotSizeY+1),!b.clipRect))b.clipRect=h;if(!a.group)c=a.group=i.g("series"),c.attr({visibility:a.visible?eb:ab,zIndex:d.zIndex}).translate(a.xAxis.left,a.yAxis.top).add(b.seriesGroup);
a.drawDataLabels();g&&a.animate(!0);a.getAttribs();a.drawGraph&&a.drawGraph();a.drawPoints();a.options.enableMouseTracking!==!1&&a.drawTracker();b.inverted&&a.invertGroups();e&&!a.hasRendered&&(c.clip(h),a.trackerGroup&&a.trackerGroup.clip(b.clipRect));g&&a.animate();setTimeout(function(){h.isAnimating=!1;if((c=a.group)&&h!==b.clipRect&&h.renderer){if(e)c.clip(a.clipRect=b.clipRect);h.destroy()}},f);a.isDirty=a.isDirtyData=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirtyData,
c=this.group;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:this.xAxis.left,translateY:this.yAxis.top}));this.translate();this.setTooltipPoints(!0);this.render();b&&aa(this,"updatedData")},setState:function(a){var b=this.options,c=this.graph,d=b.states,b=b.lineWidth,a=a||Ka;if(this.state!==a)this.state=a,d[a]&&d[a].enabled===!1||(a&&(b=d[a].lineWidth||b+1),c&&!c.dashstyle&&c.attr({"stroke-width":b},a?0:500))},setVisible:function(a,b){var c=this.chart,d=this.legendItem,
e=this.group,f=this.tracker,g=this.dataLabelsGroup,h,i=this.points,k=c.options.chart.ignoreHiddenSeries;h=this.visible;h=(this.visible=a=a===X?!h:a)?"show":"hide";if(e)e[h]();if(f)f[h]();else if(i)for(e=i.length;e--;)if(f=i[e],f.tracker)f.tracker[h]();if(g)g[h]();d&&c.legend.colorizeItem(this,a);this.isDirty=!0;this.options.stacking&&o(c.series,function(a){if(a.options.stacking&&a.visible)a.isDirty=!0});if(k)c.isDirtyBox=!0;b!==!1&&c.redraw();aa(this,h)},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},
select:function(a){this.selected=a=a===X?!this.selected:a;if(this.checkbox)this.checkbox.checked=a;aa(this,a?"select":"unselect")},drawTrackerGroup:function(){var a=this.trackerGroup,b=this.chart;if(this.isCartesian){if(!a)this.trackerGroup=a=b.renderer.g().attr({zIndex:this.options.zIndex||1}).add(b.trackerGroup);a.translate(this.xAxis.left,this.yAxis.top)}return a},drawTracker:function(){var a=this,b=a.options,c=[].concat(a.graphPath),d=c.length,e=a.chart,f=e.renderer,g=e.options.tooltip.snap,h=
a.tracker,i=b.cursor,i=i&&{cursor:i},k=a.singlePoints,j=a.drawTrackerGroup(),l;if(d)for(l=d+1;l--;)c[l]===wa&&c.splice(l+1,0,c[l+1]-g,c[l+2],fa),(l&&c[l]===wa||l===d)&&c.splice(l,0,fa,c[l-2]+g,c[l-1]);for(l=0;l<k.length;l++)d=k[l],c.push(wa,d.plotX-g,d.plotY,fa,d.plotX+g,d.plotY);h?h.attr({d:c}):a.tracker=f.path(c).attr({isTracker:!0,stroke:Gc,fill:Ma,"stroke-linejoin":"bevel","stroke-width":b.lineWidth+2*g,visibility:a.visible?eb:ab}).on(Ga?"touchstart":"mouseover",function(){if(e.hoverSeries!==
a)a.onMouseOver()}).on("mouseout",function(){if(!b.stickyTracking)a.onMouseOut()}).css(i).add(j)}};w=pa($);Ha.line=w;w=pa($,{type:"area"});Ha.area=w;w=pa($,{type:"spline",getPointSpline:function(a,b,c){var d=b.plotX,e=b.plotY,f=a[c-1],g=a[c+1],h,i,k,j;if(c&&c<a.length-1){a=f.plotY;k=g.plotX;var g=g.plotY,l;h=(1.5*d+f.plotX)/2.5;i=(1.5*e+a)/2.5;k=(1.5*d+k)/2.5;j=(1.5*e+g)/2.5;l=(j-i)*(k-d)/(k-h)+e-j;i+=l;j+=l;i>a&&i>e?(i=W(a,e),j=2*e-i):i<a&&i<e&&(i=Ua(a,e),j=2*e-i);j>g&&j>e?(j=W(g,e),i=2*e-j):j<g&&
j<e&&(j=Ua(g,e),i=2*e-j);b.rightContX=k;b.rightContY=j}c?(b=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,h||d,i||e,d,e],f.rightContX=f.rightContY=null):b=[wa,d,e];return b}});Ha.spline=w;w=pa(w,{type:"areaspline"});Ha.areaspline=w;var zb=pa($,{type:"column",tooltipOutsidePlot:!0,pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color",r:"borderRadius"},init:function(){$.prototype.init.apply(this,arguments);var a=this,b=a.chart;b.hasRendered&&o(b.series,function(b){if(b.type===
a.type)b.isDirty=!0})},translate:function(){var a=this,b=a.chart,c=a.options,d=c.stacking,e=c.borderWidth,f=0,g=a.xAxis,h=g.reversed,i={},k,j;$.prototype.translate.apply(a);o(b.series,function(b){if(b.type===a.type&&b.visible&&a.options.group===b.options.group)b.options.stacking?(k=b.stackKey,i[k]===X&&(i[k]=f++),j=i[k]):j=f++,b.columnIndex=j});var b=a.points,g=Ba(g.translationSlope)*(g.ordinalSlope||g.closestPointRange||1),l=g*c.groupPadding,n=(g-2*l)/f,t=c.pointWidth,r=s(t)?(n-t)/2:n*c.pointPadding,
w=Yb(W(p(t,n-2*r),1+2*e)),x=r+(l+((h?f-a.columnIndex:a.columnIndex)||0)*n-g/2)*(h?-1:1),v=a.yAxis.getThreshold(c.threshold),y=p(c.minPointLength,5);o(b,function(b){var f=b.plotY,g=p(b.yBottom,v),h=b.plotX+x,i=Yb(Ua(f,g)),j=Yb(W(f,g)-i),k=a.yAxis.stacks[(b.y<0?"-":"")+a.stackKey];d&&a.visible&&k&&k[b.x]&&k[b.x].setOffset(x,w);Ba(j)<y&&y&&(j=y,i=Ba(i-v)>y?g-y:v-(f<=v?y:0));L(b,{barX:h,barY:i,barW:w,barH:j});b.shapeType="rect";f={x:h,y:i,width:w,height:j,r:c.borderRadius,strokeWidth:e};e%2&&(f.y-=1,
f.height+=1);b.shapeArgs=f;b.trackerArgs=Ba(j)<3&&K(b.shapeArgs,{height:6,y:i-3})})},getSymbol:function(){},drawGraph:function(){},drawPoints:function(){var a=this,b=a.options,c=a.chart.renderer,d,e;o(a.points,function(f){var g=f.plotY;if(g!==X&&!isNaN(g)&&f.y!==null)d=f.graphic,e=f.shapeArgs,d?(Ob(d),d.animate(c.Element.prototype.crisp.apply({},[e.strokeWidth,e.x,e.y,e.width,e.height]))):f.graphic=d=c[f.shapeType](e).attr(f.pointAttr[f.selected?"select":Ka]).add(a.group).shadow(b.shadow)})},drawTracker:function(){var a=
this,b=a.chart,c=b.renderer,d,e,f=+new Date,g=a.options,h=g.cursor,i=h&&{cursor:h},k=a.drawTrackerGroup(),j;o(a.points,function(h){e=h.tracker;d=h.trackerArgs||h.shapeArgs;delete d.strokeWidth;if(h.y!==null)e?e.attr(d):h.tracker=c[h.shapeType](d).attr({isTracker:f,fill:Gc,visibility:a.visible?eb:ab}).on(Ga?"touchstart":"mouseover",function(c){j=c.relatedTarget||c.fromElement;if(b.hoverSeries!==a&&A(j,"isTracker")!==f)a.onMouseOver();h.onMouseOver()}).on("mouseout",function(b){if(!g.stickyTracking&&
(j=b.relatedTarget||b.toElement,A(j,"isTracker")!==f))a.onMouseOut()}).css(i).add(h.group||k)})},animate:function(a){var b=this,c=b.points,d=b.options;if(!a)o(c,function(a){var c=a.graphic,a=a.shapeArgs,g=b.yAxis,h=d.threshold;c&&(c.attr({height:0,y:s(h)?g.getThreshold(h):g.translate(g.getExtremes().min,0,1,0,1)}),c.animate({height:a.height,y:a.y},d.animation))}),b.animate=null},remove:function(){var a=this,b=a.chart;b.hasRendered&&o(b.series,function(b){if(b.type===a.type)b.isDirty=!0});$.prototype.remove.apply(a,
arguments)}});Ha.column=zb;w=pa(zb,{type:"bar",init:function(){this.inverted=!0;zb.prototype.init.apply(this,arguments)}});Ha.bar=w;w=pa($,{type:"scatter",sorted:!1,translate:function(){var a=this;$.prototype.translate.apply(a);o(a.points,function(b){b.shapeType="circle";b.shapeArgs={x:b.plotX,y:b.plotY,r:a.chart.options.tooltip.snap}})},drawTracker:function(){for(var a=this,b=a.options.cursor,b=b&&{cursor:b},c=a.points,d=c.length,e;d--;)if(e=c[d].graphic)e.element._i=d;a._hasTracking?a._hasTracking=
!0:a.group.attr({isTracker:!0}).on(Ga?"touchstart":"mouseover",function(b){a.onMouseOver();if(b.target._i!==X)c[b.target._i].onMouseOver()}).on("mouseout",function(){if(!a.options.stickyTracking)a.onMouseOut()}).css(b)}});Ha.scatter=w;w=pa(lb,{init:function(){lb.prototype.init.apply(this,arguments);var a=this,b;L(a,{visible:a.visible!==!1,name:p(a.name,"Slice")});b=function(){a.slice()};ha(a,"select",b);ha(a,"unselect",b);return a},setVisible:function(a){var b=this.series.chart,c=this.tracker,d=this.dataLabel,
e=this.connector,f=this.shadowGroup,g;g=(this.visible=a=a===X?!this.visible:a)?"show":"hide";this.group[g]();if(c)c[g]();if(d)d[g]();if(e)e[g]();if(f)f[g]();this.legendItem&&b.legend.colorizeItem(this,a)},slice:function(a,b,c){var d=this.series.chart,e=this.slicedTranslation;Kb(c,d);p(b,!0);a=this.sliced=s(a)?a:!this.sliced;a={translateX:a?e[0]:d.plotLeft,translateY:a?e[1]:d.plotTop};this.group.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)}});w=pa($,{type:"pie",isCartesian:!1,pointClass:w,
pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color"},getColor:function(){this.initialColor=this.chart.counters.color},animate:function(){var a=this;o(a.points,function(b){var c=b.graphic,b=b.shapeArgs,d=-da/2;c&&(c.attr({r:0,start:d,end:d}),c.animate({r:b.r,start:b.start,end:b.end},a.options.animation))});a.animate=null},setData:function(){$.prototype.setData.apply(this,arguments);this.processData();this.generatePoints()},translate:function(){this.generatePoints();var a=
0,b=-0.25,c=this.options,d=c.slicedOffset,e=d+c.borderWidth,f=c.center.concat([c.size,c.innerSize||0]),g=this.chart,h=g.plotWidth,i=g.plotHeight,k,j,l,n=this.points,p=2*da,r,s=Ua(h,i),w,v,y,q=c.dataLabels.distance,f=Vb(f,function(a,b){return(w=/%$/.test(a))?[h,i,s,s][b]*S(a)/100:a});this.getX=function(a,b){l=oa.asin((a-f[1])/(f[2]/2+q));return f[0]+(b?-1:1)*ja(l)*(f[2]/2+q)};this.center=f;o(n,function(b){a+=b.y});o(n,function(c){r=a?c.y/a:0;k=z(b*p*1E3)/1E3;b+=r;j=z(b*p*1E3)/1E3;c.shapeType="arc";
c.shapeArgs={x:f[0],y:f[1],r:f[2]/2,innerR:f[3]/2,start:k,end:j};l=(j+k)/2;c.slicedTranslation=Vb([ja(l)*d+g.plotLeft,C(l)*d+g.plotTop],z);v=ja(l)*f[2]/2;y=C(l)*f[2]/2;c.tooltipPos=[f[0]+v*0.7,f[1]+y*0.7];c.labelPos=[f[0]+v+ja(l)*q,f[1]+y+C(l)*q,f[0]+v+ja(l)*e,f[1]+y+C(l)*e,f[0]+v,f[1]+y,q<0?"center":l<p/4?"left":"right",l];c.percentage=r*100;c.total=a});this.setTooltipPoints()},render:function(){this.getAttribs();this.drawPoints();this.options.enableMouseTracking!==!1&&this.drawTracker();this.drawDataLabels();
this.options.animation&&this.animate&&this.animate();this.isDirty=!1},drawPoints:function(){var a=this.chart,b=a.renderer,c,d,e,f=this.options.shadow,g,h;o(this.points,function(i){d=i.graphic;h=i.shapeArgs;e=i.group;g=i.shadowGroup;if(f&&!g)g=i.shadowGroup=b.g("shadow").attr({zIndex:4}).add();if(!e)e=i.group=b.g("point").attr({zIndex:5}).add();c=i.sliced?i.slicedTranslation:[a.plotLeft,a.plotTop];e.translate(c[0],c[1]);g&&g.translate(c[0],c[1]);d?d.animate(h):i.graphic=b.arc(h).attr(L(i.pointAttr[Ka],
{"stroke-linejoin":"round"})).add(i.group).shadow(f,g);i.visible===!1&&i.setVisible(!1)})},drawDataLabels:function(){var a=this.data,b,c=this.chart,d=this.options.dataLabels,e=p(d.connectorPadding,10),f=p(d.connectorWidth,1),g,h,i=p(d.softConnector,!0),k=d.distance,j=this.center,l=j[2]/2,j=j[1],n=k>0,t=[[],[]],r,s,w,v,y=2,q;if(d.enabled){$.prototype.drawDataLabels.apply(this);o(a,function(a){a.dataLabel&&t[a.labelPos[7]<da/2?0:1].push(a)});t[1].reverse();v=function(a,b){return b.y-a.y};for(a=t[0][0]&&
t[0][0].dataLabel&&t[0][0].dataLabel.getBBox().height;y--;){var x=[],A=[],z=t[y],E=z.length,C;for(q=j-l-k;q<=j+l+k;q+=a)x.push(q);w=x.length;if(E>w){h=[].concat(z);h.sort(v);for(q=E;q--;)h[q].rank=q;for(q=E;q--;)z[q].rank>=w&&z.splice(q,1);E=z.length}for(q=0;q<E;q++){b=z[q];h=b.labelPos;b=9999;for(s=0;s<w;s++)g=Ba(x[s]-h[1]),g<b&&(b=g,C=s);if(C<q&&x[q]!==null)C=q;else for(w<E-q+C&&x[q]!==null&&(C=w-E+q);x[C]===null;)C++;A.push({i:C,y:x[C]});x[C]=null}A.sort(v);for(q=0;q<E;q++){b=z[q];h=b.labelPos;
g=b.dataLabel;s=A.pop();r=h[1];w=b.visible===!1?ab:eb;C=s.i;s=s.y;if(r>s&&x[C+1]!==null||r<s&&x[C-1]!==null)s=r;r=this.getX(C===0||C===x.length-1?r:s,y);g.attr({visibility:w,align:h[6]})[g.moved?"animate":"attr"]({x:r+d.x+({left:e,right:-e}[h[6]]||0),y:s+d.y});g.moved=!0;if(n&&f)g=b.connector,h=i?[wa,r+(h[6]==="left"?5:-5),s,"C",r,s,2*h[2]-h[4],2*h[3]-h[5],h[2],h[3],fa,h[4],h[5]]:[wa,r+(h[6]==="left"?5:-5),s,fa,h[2],h[3],fa,h[4],h[5]],g?(g.animate({d:h}),g.attr("visibility",w)):b.connector=g=this.chart.renderer.path(h).attr({"stroke-width":f,
stroke:d.connectorColor||b.color||"#606060",visibility:w,zIndex:3}).translate(c.plotLeft,c.plotTop).add()}}}},drawTracker:zb.prototype.drawTracker,getSymbol:function(){}});Ha.pie=w;L(Highcharts,{Chart:wc,dateFormat:ac,pathAnim:La,getOptions:function(){return Ea},hasBidiBug:Qc,numberFormat:dc,Point:lb,Color:ma,Renderer:Xb,SVGRenderer:Eb,VMLRenderer:$a,CanVGRenderer:oc,seriesTypes:Ha,setOptions:function(a){$b=K($b,a.xAxis);kc=K(kc,a.yAxis);a.xAxis=a.yAxis=X;Ea=K(Ea,a);vc();return Ea},Series:$,addEvent:ha,
removeEvent:Qa,createElement:Aa,discardElement:Tb,css:P,each:o,extend:L,map:Vb,merge:K,pick:p,splat:Hb,extendClass:pa,placeBox:uc,product:"Highcharts",version:"2.2.1"})})();
|
YUI.add('router', function(Y) {
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
@module app
@submodule router
@since 3.4.0
**/
var HistoryHash = Y.HistoryHash,
QS = Y.QueryString,
YArray = Y.Array,
win = Y.config.win,
// We have to queue up pushState calls to avoid race conditions, since the
// popstate event doesn't actually provide any info on what URL it's
// associated with.
saveQueue = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
Cached copy of the `html5` attribute for internal use.
@property _html5
@type Boolean
@protected
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._html5 = self.get('html5');
self._routes = [];
self._url = self._getURL();
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Set up a history instance or hashchange listener.
if (self._html5) {
self._history = new Y.HistoryHTML5({force: true});
Y.after('history:change', self._afterHistoryChange, self);
} else {
Y.on('hashchange', self._afterHistoryChange, win, self);
}
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish, then for window.onload, and then an
// additional 20ms to allow the browser to fire a useless initial
// `popstate` event if it wants to (and Chrome always wants to).
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
Y.once('load', function () {
setTimeout(function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
}, 20);
});
});
},
destructor: function () {
if (this._html5) {
Y.detach('history:change', this._afterHistoryChange, this);
} else {
Y.detach('hashchange', this._afterHistoryChange, win);
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function () {
this.once(EVT_READY, function () {
this._ready = true;
if (this._html5 && this.upgrade()) {
return;
} else {
this._dispatch(this._getPath(), this._getURL());
}
});
return this;
},
/**
Gets the current route path, relative to the `root` (if any).
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this._getPath();
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise.
This method enforces the same-origin security constraint on the specified
`url`; any URL which is not from the same origin as the current URL will
always return `false`.
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url) {
if (!this._hasSameOrigin(url)) {
return false;
}
return !!this.match(this.removeRoot(url)).length;
},
/**
Returns an array of route objects that match the specified URL path.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match.
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path) {
return YArray.filter(this._routes, function (route) {
return path.search(route.regex) > -1;
});
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root');
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
if (root && url.indexOf(root) === 0) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._queue(url, true);
},
/**
Adds a route handler for the specified URL _path_.
The _path_ parameter may be either a string or a regular expression. If it's
a string, it may contain named parameters: `:param` will match any single
part of a URL path (not including `/` characters), and `*param` will match
any number of parts of a URL path (including `/` characters). These named
parameters will be made available as keys on the `req.params` object that's
passed to route handlers.
If the _path_ parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
If multiple route handlers match a given URL, they will be executed in the
order they were added. The first route that was added will be the first to
be executed.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
Y.log('Current tag: ' + req.params.tag);
Y.log('Current page number: ' + req.params.page);
});
@method route
@param {String|RegExp} path Path to match. May be a string or a regular
expression.
@param {Function|String} callback Callback function to call whenever this
route is triggered. If specified as a string, the named function will be
called on this router instance.
@param {Object} callback.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callback.req.params Captured parameters matched by
the route path specification. If a string path was used and contained
named parameters, then this will be a key/value hash mapping parameter
names to their matched values. If a regex path was used, this will be
an array of subpattern matches starting at index 0 for the full match,
then 1 for the first subpattern match, and so on.
@param {String} callback.req.path The current URL path.
@param {Object} callback.req.query Query hash representing the URL query
string, if any. Parameter names are keys, and are mapped to parameter
values.
@param {String} callback.req.url The full URL.
@param {String} callback.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate".
@param {Object} callback.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callback.res.req Reference to the request object.
@param {Function} callback.next Callback to pass control to the next
matching route. If you don't call this function, then no further route
handlers will be executed, even if there are more that match. If you do
call this function, then the next matching route handler (if any) will
be called, and will receive the same `req` object that was passed to
this route (so you can use the request object to pass data along to
subsequent routes).
@chainable
**/
route: function (path, callback) {
var keys = [];
this._routes.push({
callback: callback,
keys : keys,
path : path,
regex : this._getRegex(path, keys)
});
return this;
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
save: function (url) {
return this._queue(url);
},
/**
Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
browsers, this method is a noop.
@method upgrade
@return {Boolean} `true` if the URL was upgraded, `false` otherwise.
**/
upgrade: function () {
if (!this._html5) {
return false;
}
// Get the full hash in all its glory!
var hash = HistoryHash.getHash();
if (hash && hash.charAt(0) === '/') {
// This is an HTML5 browser and we have a hash-based path in the
// URL, so we need to upgrade the URL to a non-hash URL. This
// will trigger a `history:change` event, which will in turn
// trigger a dispatch.
this.once(EVT_READY, function () {
this.replace(hash);
});
return true;
}
return false;
},
// -- Protected Methods ----------------------------------------------------
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Shifts the topmost `_save()` call off the queue and executes it. Does
nothing if the queue is empty.
@method _dequeue
@chainable
@see _queue
@protected
**/
_dequeue: function () {
var self = this,
fn;
// If window.onload hasn't yet fired, wait until it has before
// dequeueing. This will ensure that we don't call pushState() before an
// initial popstate event has fired.
if (!YUI.Env.windowLoaded) {
Y.once('load', function () {
self._dequeue();
});
return this;
}
fn = saveQueue.shift();
return fn ? fn() : this;
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {String} path URL path.
@param {String} url Full URL.
@param {String} src What initiated the dispatch.
@chainable
@protected
**/
_dispatch: function (path, url, src) {
var self = this,
routes = self.match(path),
req, res;
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
req = self._getRequest(path, url, src);
res = self._getResponse(req);
req.next = function (err) {
var callback, matches, route;
if (err) {
Y.error(err);
} else if ((route = routes.shift())) {
matches = route.regex.exec(path);
callback = typeof route.callback === 'string' ?
self[route.callback] : route.callback;
// Use named keys for parameter names if the route path contains
// named keys. Otherwise, use numerical match indices.
if (matches.length === route.keys.length + 1) {
req.params = YArray.hash(route.keys, matches.slice(1));
} else {
req.params = matches.concat();
}
callback.call(self, req, res, req.next);
}
};
req.next();
self._dispatching = false;
return self._dequeue();
},
/**
Gets the current path from the location hash, or an empty string if the
hash is empty.
@method _getHashPath
@return {String} Current hash path, or an empty string if the hash is empty.
@protected
**/
_getHashPath: function () {
return HistoryHash.getHash().replace(this._regexUrlQuery, '');
},
/**
Gets the location origin (i.e., protocol, host, and port) as a URL.
@example
http://example.com
@method _getOrigin
@return {String} Location origin (i.e., protocol, host, and port).
@protected
**/
_getOrigin: function () {
var location = Y.getLocation();
return location.origin || (location.protocol + '//' + location.host);
},
/**
Gets the current route path, relative to the `root` (if any).
@method _getPath
@return {String} Current route path.
@protected
**/
_getPath: function () {
var path = (!this._html5 && this._getHashPath()) ||
Y.getLocation().pathname;
return this.removeRoot(path);
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function () {
var location = Y.getLocation(),
hash, matches;
if (this._html5) {
return location.search.substring(1);
}
hash = HistoryHash.getHash();
matches = hash.match(this._regexUrlQuery);
return hash && matches ? matches[1] : location.search.substring(1);
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (path instanceof RegExp) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/]*)';
});
return new RegExp('^' + path + '$');
},
/**
Gets a request object that can be passed to a route handler.
@method _getRequest
@param {String} path Current path being dispatched.
@param {String} url Current full URL being dispatched.
@param {String} src What initiated the dispatch.
@return {Object} Request object.
@protected
**/
_getRequest: function (path, url, src) {
return {
path : path,
query: this._parseQuery(this._getQuery()),
url : url,
src : src
};
},
/**
Gets a response object that can be passed to a route handler.
@method _getResponse
@param {Object} req Request object.
@return {Object} Response Object.
@protected
**/
_getResponse: function (req) {
// For backwards compatibility, the response object is a function that
// calls `next()` on the request object and returns the result.
var res = function () {
return req.next.apply(this, arguments);
};
res.req = req;
return res;
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Gets the current full URL.
@method _getURL
@return {String} URL.
@protected
**/
_getURL: function () {
return Y.getLocation().toString();
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Queues up a `_save()` call to run after all previously-queued calls have
finished.
This is necessary because if we make multiple `_save()` calls before the
first call gets dispatched, then both calls will dispatch to the last call's
URL.
All arguments passed to `_queue()` will be passed on to `_save()` when the
queued function is executed.
@method _queue
@chainable
@see _dequeue
@protected
**/
_queue: function () {
var args = arguments,
self = this;
saveQueue.push(function () {
if (self._html5) {
if (Y.UA.ios && Y.UA.ios < 5) {
// iOS <5 has buggy HTML5 history support, and needs to be
// synchronous.
self._save.apply(self, args);
} else {
// Wrapped in a timeout to ensure that _save() calls are
// always processed asynchronously. This ensures consistency
// between HTML5- and hash-based history.
setTimeout(function () {
self._save.apply(self, args);
}, 1);
}
} else {
self._dispatching = true; // otherwise we'll dequeue too quickly
self._save.apply(self, args);
}
return self;
});
return !this._dispatching ? this._dequeue() : this;
},
/**
Saves a history entry using either `pushState()` or the location hash.
This method enforces the same-origin security constraint; attempting to save
a `url` that is not from the same origin as the current URL will result in
an error.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
**/
_save: function (url, replace) {
var urlIsString = typeof url === 'string';
// Perform same-origin check on the specified URL.
if (urlIsString && !this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Force _ready to true to ensure that the history change is handled
// even if _save is called before the `ready` event fires.
this._ready = true;
if (this._html5) {
this._history[replace ? 'replace' : 'add'](null, {
url: urlIsString ? this._joinURL(url) : url
});
} else {
// Remove the root from the URL before it's set as the hash.
urlIsString && (url = this.removeRoot(url));
// The `hashchange` event only fires when the new hash is actually
// different. This makes sure we'll always dequeue and dispatch,
// mimicking the HTML5 behavior.
if (url === HistoryHash.getHash()) {
this._dispatch(this._getPath(), this._getURL());
} else {
HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
}
}
return this;
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
YArray.each(routes, function (route) {
this.route(route.path, route.callback);
}, this);
return this._routes.concat();
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `history:change` and `hashchange` events.
@method _afterHistoryChange
@param {EventFacade} e
@protected
**/
_afterHistoryChange: function (e) {
var self = this,
src = e.src,
prevURL = self._url,
currentURL = self._getURL();
self._url = currentURL;
// Handles the awkwardness that is the `popstate` event. HTML5 browsers
// fire `popstate` right before they fire `hashchange`, and Chrome fires
// `popstate` on page load. If this router is not ready or the previous
// and current URLs only differ by their hash, then we want to ignore
// this `popstate` event.
if (src === 'popstate' &&
(!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
return;
}
self._dispatch(self._getPath(), currentURL, src);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callback`: Function or a string representing the name of a function
on this router instance that should be called when the route is
triggered. See the docs for the `route()` method for more details.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// Used as the default value for the `html5` attribute, and for testing.
html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3)
});
/**
The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
`Router` class. Use that class instead. This alias will be removed in a future
version of YUI.
@class Controller
@constructor
@extends Base
@deprecated Use `Router` instead.
@see Router
**/
Y.Controller = Y.Router;
}, '@VERSION@' ,{optional:['querystring-parse'], requires:['array-extras', 'base-build', 'history']});
|
YUI.add('graphics-vml', function(Y) {
Y.log('using VML');
var Y_LANG = Y.Lang,
IS_NUM = Y_LANG.isNumber,
IS_ARRAY = Y_LANG.isArray,
Y_DOM = Y.DOM,
Y_SELECTOR = Y.Selector,
DOCUMENT = Y.config.doc,
AttributeLite = Y.AttributeLite,
VMLShape,
VMLCircle,
VMLPath,
VMLRect,
VMLEllipse,
VMLGraphic,
VMLPieSlice;
function VMLDrawing() {}
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Drawing.html">`Drawing`</a> class.
* `VMLDrawing` is not intended to be used directly. Instead, use the <a href="Drawing.html">`Drawing`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Drawing.html">`Drawing`</a> class will point to the `VMLDrawing` class.
*
* @module graphics
* @class VMLDrawing
* @constructor
*/
VMLDrawing.prototype = {
/**
* Current x position of the drqwing.
*
* @property _currentX
* @type Number
* @private
*/
_currentX: 0,
/**
* Current y position of the drqwing.
*
* @property _currentY
* @type Number
* @private
*/
_currentY: 0,
/**
* Draws a bezier curve.
*
* @method curveTo
* @param {Number} cp1x x-coordinate for the first control point.
* @param {Number} cp1y y-coordinate for the first control point.
* @param {Number} cp2x x-coordinate for the second control point.
* @param {Number} cp2y y-coordinate for the second control point.
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
*/
curveTo: function(cp1x, cp1y, cp2x, cp2y, x, y) {
var hiX,
loX,
hiY,
loY;
x = Math.round(x);
y = Math.round(y);
this._path += ' c ' + Math.round(cp1x) + ", " + Math.round(cp1y) + ", " + Math.round(cp2x) + ", " + Math.round(cp2y) + ", " + x + ", " + y;
this._currentX = x;
this._currentY = y;
hiX = Math.max(x, Math.max(cp1x, cp2x));
hiY = Math.max(y, Math.max(cp1y, cp2y));
loX = Math.min(x, Math.min(cp1x, cp2x));
loY = Math.min(y, Math.min(cp1y, cp2y));
this._trackSize(hiX, hiY);
this._trackSize(loX, loY);
},
/**
* Draws a quadratic bezier curve.
*
* @method quadraticCurveTo
* @param {Number} cpx x-coordinate for the control point.
* @param {Number} cpy y-coordinate for the control point.
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
*/
quadraticCurveTo: function(cpx, cpy, x, y) {
var currentX = this._currentX,
currentY = this._currentY,
cp1x = currentX + 0.67*(cpx - currentX),
cp1y = currentY + 0.67*(cpy - currentY),
cp2x = cp1x + (x - currentX) * 0.34,
cp2y = cp1y + (y - currentY) * 0.34;
this.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
},
/**
* Draws a rectangle.
*
* @method drawRect
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
*/
drawRect: function(x, y, w, h) {
this.moveTo(x, y);
this.lineTo(x + w, y);
this.lineTo(x + w, y + h);
this.lineTo(x, y + h);
this.lineTo(x, y);
this._currentX = x;
this._currentY = y;
return this;
},
/**
* Draws a rectangle with rounded corners.
*
* @method drawRect
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
* @param {Number} ew width of the ellipse used to draw the rounded corners
* @param {Number} eh height of the ellipse used to draw the rounded corners
*/
drawRoundRect: function(x, y, w, h, ew, eh) {
this.moveTo(x, y + eh);
this.lineTo(x, y + h - eh);
this.quadraticCurveTo(x, y + h, x + ew, y + h);
this.lineTo(x + w - ew, y + h);
this.quadraticCurveTo(x + w, y + h, x + w, y + h - eh);
this.lineTo(x + w, y + eh);
this.quadraticCurveTo(x + w, y, x + w - ew, y);
this.lineTo(x + ew, y);
this.quadraticCurveTo(x, y, x, y + eh);
return this;
},
/**
* Draws a circle. Used internally by `CanvasCircle` class.
*
* @method drawCircle
* @param {Number} x y-coordinate
* @param {Number} y x-coordinate
* @param {Number} r radius
* @protected
*/
drawCircle: function(x, y, radius) {
var startAngle = 0,
endAngle = 360,
circum = radius * 2;
endAngle *= 65535;
this._drawingComplete = false;
this._trackSize(x + circum, y + circum);
this._path += " m " + (x + circum) + " " + (y + radius) + " ae " + (x + radius) + " " + (y + radius) + " " + radius + " " + radius + " " + startAngle + " " + endAngle;
return this;
},
/**
* Draws an ellipse.
*
* @method drawEllipse
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
* @protected
*/
drawEllipse: function(x, y, w, h) {
var startAngle = 0,
endAngle = 360,
radius = w * 0.5,
yRadius = h * 0.5;
endAngle *= 65535;
this._drawingComplete = false;
this._trackSize(x + w, y + h);
this._path += " m " + (x + w) + " " + (y + yRadius) + " ae " + (x + radius) + " " + (y + yRadius) + " " + radius + " " + yRadius + " " + startAngle + " " + endAngle;
return this;
},
/**
* Draws a diamond.
*
* @method drawDiamond
* @param {Number} x y-coordinate
* @param {Number} y x-coordinate
* @param {Number} width width
* @param {Number} height height
* @protected
*/
drawDiamond: function(x, y, width, height)
{
var midWidth = width * 0.5,
midHeight = height * 0.5;
this.moveTo(x + midWidth, y);
this.lineTo(x + width, y + midHeight);
this.lineTo(x + midWidth, y + height);
this.lineTo(x, y + midHeight);
this.lineTo(x + midWidth, y);
return this;
},
/**
* Draws a wedge.
*
* @method drawWedge
* @param {Number} x x-coordinate of the wedge's center point
* @param {Number} y y-coordinate of the wedge's center point
* @param {Number} startAngle starting angle in degrees
* @param {Number} arc sweep of the wedge. Negative values draw clockwise.
* @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius.
* @param {Number} yRadius [optional] y radius for wedge.
* @private
*/
drawWedge: function(x, y, startAngle, arc, radius, yRadius)
{
var diameter = radius * 2;
x = Math.round(x);
y = Math.round(y);
yRadius = yRadius || radius;
radius = Math.round(radius);
yRadius = Math.round(yRadius);
if(Math.abs(arc) > 360)
{
arc = 360;
}
startAngle *= -65535;
arc *= 65536;
this._path += " m " + x + " " + y + " ae " + x + " " + y + " " + radius + " " + yRadius + " " + startAngle + " " + arc;
this._trackSize(diameter, diameter);
this._currentX = x;
this._currentY = y;
return this;
},
/**
* Draws a line segment using the current line style from the current drawing position to the specified x and y coordinates.
*
* @method lineTo
* @param {Number} point1 x-coordinate for the end point.
* @param {Number} point2 y-coordinate for the end point.
*/
lineTo: function(point1, point2, etc) {
var args = arguments,
i,
len;
if (typeof point1 === 'string' || typeof point1 === 'number') {
args = [[point1, point2]];
}
len = args.length;
if(!this._path)
{
this._path = "";
}
this._path += ' l ';
for (i = 0; i < len; ++i) {
this._path += ' ' + Math.round(args[i][0]) + ', ' + Math.round(args[i][1]);
this._trackSize.apply(this, args[i]);
this._currentX = args[i][0];
this._currentY = args[i][1];
}
return this;
},
/**
* Moves the current drawing position to specified x and y coordinates.
*
* @method moveTo
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
*/
moveTo: function(x, y) {
if(!this._path)
{
this._path = "";
}
this._path += ' m ' + Math.round(x) + ', ' + Math.round(y);
this._trackSize(x, y);
this._currentX = x;
this._currentY = y;
},
/**
* Draws the graphic.
*
* @method _draw
* @private
*/
_closePath: function()
{
var fill = this.get("fill"),
stroke = this.get("stroke"),
node = this.node,
w = this.get("width"),
h = this.get("height"),
path = this._path,
pathEnd = "";
this._fillChangeHandler();
this._strokeChangeHandler();
if(path)
{
if(fill && fill.color)
{
pathEnd += ' x';
}
if(stroke)
{
pathEnd += ' e';
}
}
if(path)
{
node.path = path + pathEnd;
}
if(!isNaN(w) && !isNaN(h))
{
node.coordSize = w + ', ' + h;
node.style.position = "absolute";
node.style.width = w + "px";
node.style.height = h + "px";
}
this._path = path;
this._updateTransform();
},
/**
* Completes a drawing operation.
*
* @method end
*/
end: function()
{
this._closePath();
},
/**
* Ends a fill and stroke
*
* @method closePath
*/
closePath: function()
{
this._path += ' x e ';
},
/**
* Clears the path.
*
* @method clear
*/
clear: function()
{
this._right = 0;
this._bottom = 0;
this._width = 0;
this._height = 0;
this._left = 0;
this._top = 0;
this._path = "";
},
/**
* Updates the size of the graphics object
*
* @method _trackSize
* @param {Number} w width
* @param {Number} h height
* @private
*/
_trackSize: function(w, h) {
if (w > this._right) {
this._right = w;
}
if(w < this._left)
{
this._left = w;
}
if (h < this._top)
{
this._top = h;
}
if (h > this._bottom)
{
this._bottom = h;
}
this._width = this._right - this._left;
this._height = this._bottom - this._top;
},
_left: 0,
_right: 0,
_top: 0,
_bottom: 0,
_width: 0,
_height: 0
};
Y.VMLDrawing = VMLDrawing;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Shape.html">`Shape`</a> class.
* `VMLShape` is not intended to be used directly. Instead, use the <a href="Shape.html">`Shape`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Shape.html">`Shape`</a> class will point to the `VMLShape` class.
*
* @module graphics
* @class VMLShape
* @constructor
* @param {Object} cfg (optional) Attribute configs
*/
VMLShape = function()
{
this._transforms = [];
this.matrix = new Y.Matrix();
this._normalizedMatrix = new Y.Matrix();
VMLShape.superclass.constructor.apply(this, arguments);
};
VMLShape.NAME = "vmlShape";
Y.extend(VMLShape, Y.GraphicBase, Y.mix({
/**
* Indicates the type of shape
*
* @property _type
* @type String
* @private
*/
_type: "shape",
/**
* Init method, invoked during construction.
* Calls `initializer` method.
*
* @method init
* @protected
*/
init: function()
{
this.initializer.apply(this, arguments);
},
/**
* Initializes the shape
*
* @private
* @method _initialize
*/
initializer: function(cfg)
{
var host = this,
graphic = cfg.graphic;
host.createNode();
if(graphic)
{
this._setGraphic(graphic);
}
this._updateHandler();
},
/**
* Set the Graphic instance for the shape.
*
* @method _setGraphic
* @param {Graphic | Node | HTMLElement | String} render This param is used to determine the graphic instance. If it is a `Graphic` instance, it will be assigned
* to the `graphic` attribute. Otherwise, a new Graphic instance will be created and rendered into the dom element that the render represents.
* @private
*/
_setGraphic: function(render)
{
var graphic;
if(render instanceof Y.VMLGraphic)
{
this._graphic = render;
}
else
{
render = Y.one(render);
graphic = new Y.VMLGraphic({
render: render
});
graphic._appendShape(this);
this._graphic = graphic;
}
},
/**
* Creates the dom node for the shape.
*
* @method createNode
* @return HTMLElement
* @private
*/
createNode: function()
{
var node,
x = this.get("x"),
y = this.get("y"),
w = this.get("width"),
h = this.get("height"),
id,
type,
nodestring,
visibility = this.get("visible") ? "visible" : "hidden",
strokestring,
classString,
stroke,
endcap,
opacity,
joinstyle,
miterlimit,
dashstyle,
fill,
fillstring;
id = this.get("id");
type = this._type == "path" ? "shape" : this._type;
classString = 'vml' + type + ' yui3-vmlShape yui3-' + this.constructor.NAME;
stroke = this._getStrokeProps();
fill = this._getFillProps();
nodestring = '<' + type + ' xmlns="urn:schemas-microsft.com:vml" id="' + id + '" class="' + classString + '" style="behavior:url(#default#VML);display:inline-block;position:absolute;left:' + x + 'px;top:' + y + 'px;width:' + w + 'px;height:' + h + 'px;visibility:' + visibility + '"';
if(stroke && stroke.weight && stroke.weight > 0)
{
endcap = stroke.endcap;
opacity = parseFloat(stroke.opacity);
joinstyle = stroke.joinstyle;
miterlimit = stroke.miterlimit;
dashstyle = stroke.dashstyle;
nodestring += ' stroked="t" strokecolor="' + stroke.color + '" strokeWeight="' + stroke.weight + 'px"';
strokestring = '<stroke class="vmlstroke" xmlns="urn:schemas-microsft.com:vml" on="t" style="behavior:url(#default#VML);display:inline-block;"';
strokestring += ' opacity="' + opacity + '"';
if(endcap)
{
strokestring += ' endcap="' + endcap + '"';
}
if(joinstyle)
{
strokestring += ' joinstyle="' + joinstyle + '"';
}
if(miterlimit)
{
strokestring += ' miterlimit="' + miterlimit + '"';
}
if(dashstyle)
{
strokestring += ' dashstyle="' + dashstyle + '"';
}
strokestring += '></stroke>';
this._strokeNode = DOCUMENT.createElement(strokestring);
nodestring += ' stroked="t"';
}
else
{
nodestring += ' stroked="f"';
}
if(fill)
{
if(fill.node)
{
fillstring = fill.node;
this._fillNode = DOCUMENT.createElement(fillstring);
}
if(fill.color)
{
nodestring += ' fillcolor="' + fill.color + '"';
}
nodestring += ' filled="' + fill.filled + '"';
}
nodestring += '>';
nodestring += '</' + type + '>';
node = DOCUMENT.createElement(nodestring);
if(this._strokeNode)
{
node.appendChild(this._strokeNode);
}
if(this._fillNode)
{
node.appendChild(this._fillNode);
}
this.node = node;
this._strokeFlag = false;
this._fillFlag = false;
},
/**
* Add a class name to each node.
*
* @method addClass
* @param {String} className the class name to add to the node's class attribute
*/
addClass: function(className)
{
var node = this.node;
Y_DOM.addClass(node, className);
},
/**
* Removes a class name from each node.
*
* @method removeClass
* @param {String} className the class name to remove from the node's class attribute
*/
removeClass: function(className)
{
var node = this.node;
Y_DOM.removeClass(node, className);
},
/**
* Gets the current position of the node in page coordinates.
*
* @method getXY
* @return Array The XY position of the shape.
*/
getXY: function()
{
var graphic = this._graphic,
parentXY = graphic.getXY(),
x = this.get("x"),
y = this.get("y");
return [parentXY[0] + x, parentXY[1] + y];
},
/**
* Set the position of the shape in page coordinates, regardless of how the node is positioned.
*
* @method setXY
* @param {Array} Contains x & y values for new position (coordinates are page-based)
*
*/
setXY: function(xy)
{
var graphic = this._graphic,
parentXY = graphic.getXY();
this.set("x", xy[0] - parentXY[0]);
this.set("y", xy[1] - parentXY[1]);
},
/**
* Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
*
* @method contains
* @param {VMLShape | HTMLElement} needle The possible node or descendent
* @return Boolean Whether or not this shape is the needle or its ancestor.
*/
contains: function(needle)
{
return needle === Y.one(this.node);
},
/**
* Compares nodes to determine if they match.
* Node instances can be compared to each other and/or HTMLElements.
* @method compareTo
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
* @return {Boolean} True if the nodes match, false if they do not.
*/
compareTo: function(refNode) {
var node = this.node;
return node === refNode;
},
/**
* Test if the supplied node matches the supplied selector.
*
* @method test
* @param {String} selector The CSS selector to test against.
* @return Boolean Wheter or not the shape matches the selector.
*/
test: function(selector)
{
return Y_SELECTOR.test(this.node, selector);
},
/**
* Calculates and returns properties for setting an initial stroke.
*
* @method _getStrokeProps
* @return Object
*
* @private
*/
_getStrokeProps: function()
{
var props,
stroke = this.get("stroke"),
strokeOpacity,
dashstyle,
dash = "",
val,
i = 0,
len,
linecap,
linejoin;
if(stroke && stroke.weight && stroke.weight > 0)
{
props = {};
linecap = stroke.linecap || "flat";
linejoin = stroke.linejoin || "round";
if(linecap != "round" && linecap != "square")
{
linecap = "flat";
}
strokeOpacity = parseFloat(stroke.opacity);
dashstyle = stroke.dashstyle || "none";
stroke.color = stroke.color || "#000000";
stroke.weight = stroke.weight || 1;
stroke.opacity = IS_NUM(strokeOpacity) ? strokeOpacity : 1;
props.stroked = true;
props.color = stroke.color;
props.weight = stroke.weight;
props.endcap = linecap;
props.opacity = stroke.opacity;
if(IS_ARRAY(dashstyle))
{
dash = [];
len = dashstyle.length;
for(i = 0; i < len; ++i)
{
val = dashstyle[i];
dash[i] = val / stroke.weight;
}
}
if(linejoin == "round" || linejoin == "bevel")
{
props.joinstyle = linejoin;
}
else
{
linejoin = parseInt(linejoin, 10);
if(IS_NUM(linejoin))
{
props.miterlimit = Math.max(linejoin, 1);
props.joinstyle = "miter";
}
}
props.dashstyle = dash;
}
return props;
},
/**
* Adds a stroke to the shape node.
*
* @method _strokeChangeHandler
* @private
*/
_strokeChangeHandler: function(e)
{
if(!this._strokeFlag)
{
return;
}
var node = this.node,
stroke = this.get("stroke"),
strokeOpacity,
dashstyle,
dash = "",
val,
i = 0,
len,
linecap,
linejoin;
if(stroke && stroke.weight && stroke.weight > 0)
{
linecap = stroke.linecap || "flat";
linejoin = stroke.linejoin || "round";
if(linecap != "round" && linecap != "square")
{
linecap = "flat";
}
strokeOpacity = parseFloat(stroke.opacity);
dashstyle = stroke.dashstyle || "none";
stroke.color = stroke.color || "#000000";
stroke.weight = stroke.weight || 1;
stroke.opacity = IS_NUM(strokeOpacity) ? strokeOpacity : 1;
node.stroked = true;
node.strokeColor = stroke.color;
node.strokeWeight = stroke.weight + "px";
if(!this._strokeNode)
{
this._strokeNode = this._createGraphicNode("stroke");
node.appendChild(this._strokeNode);
}
this._strokeNode.endcap = linecap;
this._strokeNode.opacity = stroke.opacity;
if(IS_ARRAY(dashstyle))
{
dash = [];
len = dashstyle.length;
for(i = 0; i < len; ++i)
{
val = dashstyle[i];
dash[i] = val / stroke.weight;
}
}
if(linejoin == "round" || linejoin == "bevel")
{
this._strokeNode.joinstyle = linejoin;
}
else
{
linejoin = parseInt(linejoin, 10);
if(IS_NUM(linejoin))
{
this._strokeNode.miterlimit = Math.max(linejoin, 1);
this._strokeNode.joinstyle = "miter";
}
}
this._strokeNode.dashstyle = dash;
this._strokeNode.on = true;
}
else
{
if(this._strokeNode)
{
this._strokeNode.on = false;
}
node.stroked = false;
}
this._strokeFlag = false;
},
/**
* Calculates and returns properties for setting an initial fill.
*
* @method _getFillProps
* @return Object
*
* @private
*/
_getFillProps: function()
{
var fill = this.get("fill"),
fillOpacity,
props,
gradient,
i,
fillstring,
filled = false;
if(fill)
{
props = {};
if(fill.type == "radial" || fill.type == "linear")
{
fillOpacity = parseFloat(fill.opacity);
fillOpacity = IS_NUM(fillOpacity) ? fillOpacity : 1;
filled = true;
gradient = this._getGradientFill(fill);
fillstring = '<fill xmlns="urn:schemas-microsft.com:vml" class="vmlfill" style="behavior:url(#default#VML);display:inline-block;" opacity="' + fillOpacity + '"';
for(i in gradient)
{
if(gradient.hasOwnProperty(i))
{
fillstring += ' ' + i + '="' + gradient[i] + '"';
}
}
fillstring += ' />';
props.node = fillstring;
}
else if(fill.color)
{
fillOpacity = parseFloat(fill.opacity);
filled = true;
props.color = fill.color;
if(IS_NUM(fillOpacity))
{
fillOpacity = Math.max(Math.min(fillOpacity, 1), 0);
props.opacity = fillOpacity;
if(fillOpacity < 1)
{
props.node = '<fill xmlns="urn:schemas-microsft.com:vml" class="vmlfill" style="behavior:url(#default#VML);display:inline-block;" type="solid" opacity="' + fillOpacity + '"/>';
}
}
}
props.filled = filled;
}
return props;
},
/**
* Adds a fill to the shape node.
*
* @method _fillChangeHandler
* @private
*/
_fillChangeHandler: function(e)
{
if(!this._fillFlag)
{
return;
}
var node = this.node,
fill = this.get("fill"),
fillOpacity,
fillstring,
filled = false,
i,
gradient;
if(fill)
{
if(fill.type == "radial" || fill.type == "linear")
{
filled = true;
gradient = this._getGradientFill(fill);
if(this._fillNode)
{
for(i in gradient)
{
if(gradient.hasOwnProperty(i))
{
if(i == "colors")
{
this._fillNode.colors.value = gradient[i];
}
else
{
this._fillNode[i] = gradient[i];
}
}
}
}
else
{
fillstring = '<fill xmlns="urn:schemas-microsft.com:vml" class="vmlfill" style="behavior:url(#default#VML);display:inline-block;"';
for(i in gradient)
{
if(gradient.hasOwnProperty(i))
{
fillstring += ' ' + i + '="' + gradient[i] + '"';
}
}
fillstring += ' />';
this._fillNode = DOCUMENT.createElement(fillstring);
node.appendChild(this._fillNode);
}
}
else if(fill.color)
{
node.fillcolor = fill.color;
fillOpacity = parseFloat(fill.opacity);
filled = true;
if(IS_NUM(fillOpacity) && fillOpacity < 1)
{
fill.opacity = fillOpacity;
if(this._fillNode)
{
if(this._fillNode.getAttribute("type") != "solid")
{
this._fillNode.type = "solid";
}
this._fillNode.opacity = fillOpacity;
}
else
{
fillstring = '<fill xmlns="urn:schemas-microsft.com:vml" class="vmlfill" style="behavior:url(#default#VML);display:inline-block;" type="solid" opacity="' + fillOpacity + '"/>';
this._fillNode = DOCUMENT.createElement(fillstring);
node.appendChild(this._fillNode);
}
}
else if(this._fillNode)
{
this._fillNode.opacity = 1;
this._fillNode.type = "solid";
}
}
}
node.filled = filled;
this._fillFlag = false;
},
//not used. remove next release.
_updateFillNode: function(node)
{
if(!this._fillNode)
{
this._fillNode = this._createGraphicNode("fill");
node.appendChild(this._fillNode);
}
},
/**
* Calculates and returns an object containing gradient properties for a fill node.
*
* @method _getGradientFill
* @param {Object} fill Object containing fill properties.
* @return Object
* @private
*/
_getGradientFill: function(fill)
{
var gradientProps = {},
gradientBoxWidth,
gradientBoxHeight,
type = fill.type,
w = this.get("width"),
h = this.get("height"),
isNumber = IS_NUM,
stop,
stops = fill.stops,
len = stops.length,
opacity,
color,
i = 0,
oi,
colorstring = "",
cx = fill.cx,
cy = fill.cy,
fx = fill.fx,
fy = fill.fy,
r = fill.r,
actualPct,
pct,
rotation = fill.rotation || 0;
if(type === "linear")
{
if(rotation <= 270)
{
rotation = Math.abs(rotation - 270);
}
else if(rotation < 360)
{
rotation = 270 + (360 - rotation);
}
else
{
rotation = 270;
}
gradientProps.type = "gradient";//"gradientunscaled";
gradientProps.angle = rotation;
}
else if(type === "radial")
{
gradientBoxWidth = w * (r * 2);
gradientBoxHeight = h * (r * 2);
fx = r * 2 * (fx - 0.5);
fy = r * 2 * (fy - 0.5);
fx += cx;
fy += cy;
gradientProps.focussize = (gradientBoxWidth/w)/10 + "% " + (gradientBoxHeight/h)/10 + "%";
gradientProps.alignshape = false;
gradientProps.type = "gradientradial";
gradientProps.focus = "100%";
gradientProps.focusposition = Math.round(fx * 100) + "% " + Math.round(fy * 100) + "%";
}
for(;i < len; ++i) {
stop = stops[i];
color = stop.color;
opacity = stop.opacity;
opacity = isNumber(opacity) ? opacity : 1;
pct = stop.offset || i/(len-1);
pct *= (r * 2);
pct = Math.round(100 * pct) + "%";
oi = i > 0 ? i + 1 : "";
gradientProps["opacity" + oi] = opacity + "";
colorstring += ", " + pct + " " + color;
}
if(parseFloat(pct) < 100)
{
colorstring += ", 100% " + color;
}
gradientProps.colors = colorstring.substr(2);
return gradientProps;
},
/**
* Adds a transform to the shape.
*
* @method _addTransform
* @param {String} type The transform being applied.
* @param {Array} args The arguments for the transform.
* @private
*/
_addTransform: function(type, args)
{
args = Y.Array(args);
this._transform = Y_LANG.trim(this._transform + " " + type + "(" + args.join(", ") + ")");
args.unshift(type);
this._transforms.push(args);
if(this.initialized)
{
this._updateTransform();
}
},
/**
* Applies all transforms.
*
* @method _updateTransform
* @private
*/
_updateTransform: function()
{
var node = this.node,
key,
transform,
transformOrigin,
x = this.get("x"),
y = this.get("y"),
tx,
ty,
matrix = this.matrix,
normalizedMatrix = this._normalizedMatrix,
isPathShape = this instanceof Y.VMLPath,
i = 0,
len = this._transforms.length;
if(this._transforms && this._transforms.length > 0)
{
transformOrigin = this.get("transformOrigin");
if(isPathShape)
{
normalizedMatrix.translate(this._left, this._top);
}
//vml skew matrix transformOrigin ranges from -0.5 to 0.5.
//subtract 0.5 from values
tx = transformOrigin[0] - 0.5;
ty = transformOrigin[1] - 0.5;
//ensure the values are within the appropriate range to avoid errors
tx = Math.max(-0.5, Math.min(0.5, tx));
ty = Math.max(-0.5, Math.min(0.5, ty));
for(; i < len; ++i)
{
key = this._transforms[i].shift();
if(key)
{
normalizedMatrix[key].apply(normalizedMatrix, this._transforms[i]);
matrix[key].apply(matrix, this._transforms[i]);
}
}
if(isPathShape)
{
normalizedMatrix.translate(-this._left, -this._top);
}
transform = normalizedMatrix.a + "," +
normalizedMatrix.c + "," +
normalizedMatrix.b + "," +
normalizedMatrix.d + "," +
0 + "," +
0;
}
this._graphic.addToRedrawQueue(this);
if(transform)
{
if(!this._skew)
{
this._skew = DOCUMENT.createElement( '<skew class="vmlskew" xmlns="urn:schemas-microsft.com:vml" on="false" style="behavior:url(#default#VML);display:inline-block;" />');
this.node.appendChild(this._skew);
}
this._skew.matrix = transform;
this._skew.on = true;
//use offset for translate
this._skew.offset = normalizedMatrix.dx + "px, " + normalizedMatrix.dy + "px";
this._skew.origin = tx + ", " + ty;
}
if(this._type != "path")
{
this._transforms = [];
}
node.style.left = x + "px";
node.style.top = y + "px";
},
/**
* Storage for translateX
*
* @property _translateX
* @type Number
* @private
*/
_translateX: 0,
/**
* Storage for translateY
*
* @property _translateY
* @type Number
* @private
*/
_translateY: 0,
/**
* Storage for the transform attribute.
*
* @property _transform
* @type String
* @private
*/
_transform: "",
/**
* Specifies a 2d translation.
*
* @method translate
* @param {Number} x The value to transate on the x-axis.
* @param {Number} y The value to translate on the y-axis.
*/
translate: function(x, y)
{
this._translateX += x;
this._translateY += y;
this._addTransform("translate", arguments);
},
/**
* Translates the shape along the x-axis. When translating x and y coordinates,
* use the `translate` method.
*
* @method translateX
* @param {Number} x The value to translate.
*/
translateX: function(x)
{
this._translateX += x;
this._addTransform("translateX", arguments);
},
/**
* Performs a translate on the y-coordinate. When translating x and y coordinates,
* use the `translate` method.
*
* @method translateY
* @param {Number} y The value to translate.
*/
translateY: function(y)
{
this._translateY += y;
this._addTransform("translateY", arguments);
},
/**
* Skews the shape around the x-axis and y-axis.
*
* @method skew
* @param {Number} x The value to skew on the x-axis.
* @param {Number} y The value to skew on the y-axis.
*/
skew: function(x, y)
{
this._addTransform("skew", arguments);
},
/**
* Skews the shape around the x-axis.
*
* @method skewX
* @param {Number} x x-coordinate
*/
skewX: function(x)
{
this._addTransform("skewX", arguments);
},
/**
* Skews the shape around the y-axis.
*
* @method skewY
* @param {Number} y y-coordinate
*/
skewY: function(y)
{
this._addTransform("skewY", arguments);
},
/**
* Rotates the shape clockwise around it transformOrigin.
*
* @method rotate
* @param {Number} deg The degree of the rotation.
*/
rotate: function(deg)
{
this._addTransform("rotate", arguments);
},
/**
* Specifies a 2d scaling operation.
*
* @method scale
* @param {Number} val
*/
scale: function(x, y)
{
this._addTransform("scale", arguments);
},
/**
* Overrides default `on` method. Checks to see if its a dom interaction event. If so,
* return an event attached to the `node` element. If not, return the normal functionality.
*
* @method on
* @param {String} type event type
* @param {Object} callback function
* @private
*/
on: function(type, fn)
{
if(Y.Node.DOM_EVENTS[type])
{
return Y.one("#" + this.get("id")).on(type, fn);
}
return Y.on.apply(this, arguments);
},
/**
* Draws the shape.
*
* @method _draw
* @private
*/
_draw: function()
{
},
/**
* Updates `Shape` based on attribute changes.
*
* @method _updateHandler
* @private
*/
_updateHandler: function(e)
{
var host = this,
node = host.node;
host._fillChangeHandler();
host._strokeChangeHandler();
node.style.width = this.get("width") + "px";
node.style.height = this.get("height") + "px";
this._draw();
host._updateTransform();
},
/**
* Creates a graphic node
*
* @method _createGraphicNode
* @param {String} type node type to create
* @return HTMLElement
* @private
*/
_createGraphicNode: function(type)
{
type = type || this._type;
return DOCUMENT.createElement('<' + type + ' xmlns="urn:schemas-microsft.com:vml" style="behavior:url(#default#VML);display:inline-block;" class="vml' + type + '"/>');
},
/**
* Value function for fill attribute
*
* @private
* @method _getDefaultFill
* @return Object
*/
_getDefaultFill: function() {
return {
type: "solid",
cx: 0.5,
cy: 0.5,
fx: 0.5,
fy: 0.5,
r: 0.5
};
},
/**
* Value function for stroke attribute
*
* @private
* @method _getDefaultStroke
* @return Object
*/
_getDefaultStroke: function()
{
return {
weight: 1,
dashstyle: "none",
color: "#000",
opacity: 1.0
};
},
/**
* Sets the value of an attribute.
*
* @method set
* @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
* be passed in to set multiple attributes at once.
* @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
* the name param.
*/
set: function()
{
var host = this;
AttributeLite.prototype.set.apply(host, arguments);
if(host.initialized)
{
host._updateHandler();
}
},
/**
* Returns the bounds for a shape.
*
* Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix.
* The calculated bounding box is used by the graphic instance to calculate its viewBox.
*
* @method getBounds
* @param {Matrix} [optional] cfg Reference to matrix instance
* @return Object
*/
getBounds: function(cfg)
{
var stroke = this.get("stroke"),
w = this.get("width"),
h = this.get("height"),
x = this.get("x"),
y = this.get("y"),
wt = 0;
if(stroke && stroke.weight)
{
wt = stroke.weight;
}
w = (x + w + wt) - (x - wt);
h = (y + h + wt) - (y - wt);
x -= wt;
y -= wt;
return this._normalizedMatrix.getContentRect(w, h, x, y);
},
/**
* Destroys shape
*
* @method destroy
*/
destroy: function()
{
var graphic = this.get("graphic");
if(graphic)
{
graphic.removeShape(this);
}
else
{
this._destroy();
}
},
/**
* Implementation for shape destruction
*
* @method destroy
* @protected
*/
_destroy: function()
{
if(this.node)
{
if(this._fillNode)
{
this.node.removeChild(this._fillNode);
this._fillNode = null;
}
if(this._strokeNode)
{
this.node.removeChild(this._strokeNode);
this._strokeNode = null;
}
Y.one(this.node).remove(true);
}
}
}, Y.VMLDrawing.prototype));
VMLShape.ATTRS = {
/**
* An array of x, y values which indicates the transformOrigin in which to rotate the shape. Valid values range between 0 and 1 representing a
* fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5].
*
* @config transformOrigin
* @type Array
*/
transformOrigin: {
valueFn: function()
{
return [0.5, 0.5];
}
},
/**
* <p>A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values:
*
* <dl>
* <dt>rotate</dt><dd>Rotates the shape clockwise around it transformOrigin.</dd>
* <dt>translate</dt><dd>Specifies a 2d translation.</dd>
* <dt>skew</dt><dd>Skews the shape around the x-axis and y-axis.</dd>
* <dt>scale</dt><dd>Specifies a 2d scaling operation.</dd>
* <dt>translateX</dt><dd>Translates the shape along the x-axis.</dd>
* <dt>translateY</dt><dd>Translates the shape along the y-axis.</dd>
* <dt>skewX</dt><dd>Skews the shape around the x-axis.</dd>
* <dt>skewY</dt><dd>Skews the shape around the y-axis.</dd>
* <dt>matrix</dt><dd>Specifies a 2D transformation matrix comprised of the specified six values.</dd>
* </dl>
* </p>
* <p>Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains corresponding methods for each transform
* that will apply the transform to the current matrix. The below code illustrates how you might use the `transform` attribute to instantiate a recangle with a rotation of 45 degrees.</p>
var myRect = new Y.Rect({
type:"rect",
width: 50,
height: 40,
transform: "rotate(45)"
};
* <p>The code below would apply `translate` and `rotate` to an existing shape.</p>
myRect.set("transform", "translate(40, 50) rotate(45)");
* @config transform
* @type String
*/
transform: {
setter: function(val)
{
var i = 0,
len,
transform;
this.matrix.init();
this._normalizedMatrix.init();
this._transforms = this.matrix.getTransformArray(val);
len = this._transforms.length;
for(;i < len; ++i)
{
transform = this._transforms[i];
}
this._transform = val;
if(this.initialized)
{
this._updateTransform();
}
return val;
},
getter: function()
{
return this._transform;
}
},
/**
* Indicates the x position of shape.
*
* @config x
* @type Number
*/
x: {
value: 0
},
/**
* Indicates the y position of shape.
*
* @config y
* @type Number
*/
y: {
value: 0
},
/**
* Unique id for class instance.
*
* @config id
* @type String
*/
id: {
valueFn: function()
{
return Y.guid();
},
setter: function(val)
{
var node = this.node;
if(node)
{
node.setAttribute("id", val);
}
return val;
}
},
/**
*
* @config width
*/
width: {
value: 0
},
/**
*
* @config height
*/
height: {
value: 0
},
/**
* Indicates whether the shape is visible.
*
* @config visible
* @type Boolean
*/
visible: {
value: true,
setter: function(val){
var node = this.node,
visibility = val ? "visible" : "hidden";
if(node)
{
node.style.visibility = visibility;
}
return val;
}
},
/**
* Contains information about the fill of the shape.
* <dl>
* <dt>color</dt><dd>The color of the fill.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.</dd>
* <dt>type</dt><dd>Type of fill.
* <dl>
* <dt>solid</dt><dd>Solid single color fill. (default)</dd>
* <dt>linear</dt><dd>Linear gradient fill.</dd>
* <dt>radial</dt><dd>Radial gradient fill.</dd>
* </dl>
* </dd>
* </dl>
* <p>If a `linear` or `radial` is specified as the fill type. The following additional property is used:
* <dl>
* <dt>stops</dt><dd>An array of objects containing the following properties:
* <dl>
* <dt>color</dt><dd>The color of the stop.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stop. The default value is 1. Note: No effect for IE 6 - 8</dd>
* <dt>offset</dt><dd>Number between 0 and 1 indicating where the color stop is positioned.</dd>
* </dl>
* </dd>
* <p>Linear gradients also have the following property:</p>
* <dt>rotation</dt><dd>Linear gradients flow left to right by default. The rotation property allows you to change the flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)</dd>
* <p>Radial gradients have the following additional properties:</p>
* <dt>r</dt><dd>Radius of the gradient circle.</dd>
* <dt>fx</dt><dd>Focal point x-coordinate of the gradient.</dd>
* <dt>fy</dt><dd>Focal point y-coordinate of the gradient.</dd>
* </dl>
* <p>The corresponding `SVGShape` class implements the following additional properties.</p>
* <dl>
* <dt>cx</dt><dd>
* <p>The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
* </dd>
* <dt>cy</dt><dd>
* <p>The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
* </dd>
* </dl>
* <p>These properties are not currently implemented in `CanvasShape` or `VMLShape`.</p>
*
* @config fill
* @type Object
*/
fill: {
valueFn: "_getDefaultFill",
setter: function(val)
{
var i,
fill,
tmpl = this.get("fill") || this._getDefaultFill();
if(val)
{
//ensure, fill type is solid if color is explicitly passed.
if(val.hasOwnProperty("color"))
{
val.type = "solid";
}
for(i in val)
{
if(val.hasOwnProperty(i))
{
tmpl[i] = val[i];
}
}
}
fill = tmpl;
if(fill && fill.color)
{
if(fill.color === undefined || fill.color == "none")
{
fill.color = null;
}
}
this._fillFlag = true;
return fill;
}
},
/**
* Contains information about the stroke of the shape.
* <dl>
* <dt>color</dt><dd>The color of the stroke.</dd>
* <dt>weight</dt><dd>Number that indicates the width of the stroke.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.</dd>
* <dt>dashstyle</dt>Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set to an array, the first index indicates the
* length of the dash. The second index indicates the length of gap.
* <dt>linecap</dt><dd>Specifies the linecap for the stroke. The following values can be specified:
* <dl>
* <dt>butt (default)</dt><dd>Specifies a butt linecap.</dd>
* <dt>square</dt><dd>Specifies a sqare linecap.</dd>
* <dt>round</dt><dd>Specifies a round linecap.</dd>
* </dl>
* </dd>
* <dt>linejoin</dt><dd>Specifies a linejoin for the stroke. The following values can be specified:
* <dl>
* <dt>round (default)</dt><dd>Specifies that the linejoin will be round.</dd>
* <dt>bevel</dt><dd>Specifies a bevel for the linejoin.</dd>
* <dt>miter limit</dt><dd>An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin of miter, you simply specify the limit as opposed to having
* separate miter and miter limit values.</dd>
* </dl>
* </dd>
* </dl>
*
* @config stroke
* @type Object
*/
stroke: {
valueFn: "_getDefaultStroke",
setter: function(val)
{
var i,
stroke,
wt,
tmpl = this.get("stroke") || this._getDefaultStroke();
if(val)
{
if(val.hasOwnProperty("weight"))
{
wt = parseInt(val.weight, 10);
if(!isNaN(wt))
{
val.weight = wt;
}
}
for(i in val)
{
if(val.hasOwnProperty(i))
{
tmpl[i] = val[i];
}
}
}
stroke = tmpl;
this._strokeFlag = true;
return stroke;
}
},
//Not used. Remove in future.
autoSize: {
value: false
},
// Only implemented in SVG
// Determines whether the instance will receive mouse events.
//
// @config pointerEvents
// @type string
//
pointerEvents: {
value: "visiblePainted"
},
/**
* Dom node for the shape.
*
* @config node
* @type HTMLElement
* @readOnly
*/
node: {
readOnly: true,
getter: function()
{
return this.node;
}
},
/**
* Reference to the container Graphic.
*
* @config graphic
* @type Graphic
*/
graphic: {
readOnly: true,
getter: function()
{
return this._graphic;
}
}
};
Y.VMLShape = VMLShape;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Path.html">`Path`</a> class.
* `VMLPath` is not intended to be used directly. Instead, use the <a href="Path.html">`Path`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Path.html">`Path`</a> class will point to the `VMLPath` class.
*
* @module graphics
* @class VMLPath
* @extends VMLShape
*/
VMLPath = function()
{
VMLPath.superclass.constructor.apply(this, arguments);
};
VMLPath.NAME = "vmlPath";
Y.extend(VMLPath, Y.VMLShape);
VMLPath.ATTRS = Y.merge(Y.VMLShape.ATTRS, {
/**
* Indicates the width of the shape
*
* @config width
* @type Number
*/
width: {
getter: function()
{
var val = Math.max(this._right - this._left, 0);
return val;
}
},
/**
* Indicates the height of the shape
*
* @config height
* @type Number
*/
height: {
getter: function()
{
return Math.max(this._bottom - this._top, 0);
}
},
/**
* Indicates the path used for the node.
*
* @config path
* @type String
* @readOnly
*/
path: {
readOnly: true,
getter: function()
{
return this._path;
}
}
});
Y.VMLPath = VMLPath;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Rect.html">`Rect`</a> class.
* `VMLRect` is not intended to be used directly. Instead, use the <a href="Rect.html">`Rect`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Rect.html">`Rect`</a> class will point to the `VMLRect` class.
*
* @module graphics
* @class VMLRect
* @constructor
*/
VMLRect = function()
{
VMLRect.superclass.constructor.apply(this, arguments);
};
VMLRect.NAME = "vmlRect";
Y.extend(VMLRect, Y.VMLShape, {
/**
* Indicates the type of shape
*
* @property _type
* @type String
* @private
*/
_type: "rect"
});
VMLRect.ATTRS = Y.VMLShape.ATTRS;
Y.VMLRect = VMLRect;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Ellipse.html">`Ellipse`</a> class.
* `VMLEllipse` is not intended to be used directly. Instead, use the <a href="Ellipse.html">`Ellipse`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Ellipse.html">`Ellipse`</a> class will point to the `VMLEllipse` class.
*
* @module graphics
* @class VMLEllipse
* @constructor
*/
VMLEllipse = function()
{
VMLEllipse.superclass.constructor.apply(this, arguments);
};
VMLEllipse.NAME = "vmlEllipse";
Y.extend(VMLEllipse, Y.VMLShape, {
/**
* Indicates the type of shape
*
* @property _type
* @type String
* @private
*/
_type: "oval"
});
VMLEllipse.ATTRS = Y.merge(Y.VMLShape.ATTRS, {
//
// Horizontal radius for the ellipse. This attribute is not implemented in Canvas.
// Will add in 3.4.1.
//
// @config xRadius
// @type Number
// @readOnly
//
xRadius: {
lazyAdd: false,
getter: function()
{
var val = this.get("width");
val = Math.round((val/2) * 100)/100;
return val;
},
setter: function(val)
{
var w = val * 2;
this.set("width", w);
return val;
}
},
//
// Vertical radius for the ellipse. This attribute is not implemented in Canvas.
// Will add in 3.4.1.
//
// @config yRadius
// @type Number
// @readOnly
//
yRadius: {
lazyAdd: false,
getter: function()
{
var val = this.get("height");
val = Math.round((val/2) * 100)/100;
return val;
},
setter: function(val)
{
var h = val * 2;
this.set("height", h);
return val;
}
}
});
Y.VMLEllipse = VMLEllipse;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Circle.html">`Circle`</a> class.
* `VMLCircle` is not intended to be used directly. Instead, use the <a href="Circle.html">`Circle`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Circle.html">`Circle`</a> class will point to the `VMLCircle` class.
*
* @module graphics
* @class VMLCircle
* @constructor
*/
VMLCircle = function(cfg)
{
VMLCircle.superclass.constructor.apply(this, arguments);
};
VMLCircle.NAME = "vmlCircle";
Y.extend(VMLCircle, VMLShape, {
/**
* Indicates the type of shape
*
* @property _type
* @type String
* @private
*/
_type: "oval"
});
VMLCircle.ATTRS = Y.merge(VMLShape.ATTRS, {
/**
* Radius for the circle.
*
* @config radius
* @type Number
*/
radius: {
lazyAdd: false,
value: 0
},
/**
* Indicates the width of the shape
*
* @config width
* @type Number
*/
width: {
setter: function(val)
{
this.set("radius", val/2);
return val;
},
getter: function()
{
var radius = this.get("radius"),
val = radius && radius > 0 ? radius * 2 : 0;
return val;
}
},
/**
* Indicates the height of the shape
*
* @config height
* @type Number
*/
height: {
setter: function(val)
{
this.set("radius", val/2);
return val;
},
getter: function()
{
var radius = this.get("radius"),
val = radius && radius > 0 ? radius * 2 : 0;
return val;
}
}
});
Y.VMLCircle = VMLCircle;
/**
* Draws pie slices
*
* @module graphics
* @class VMLPieSlice
* @constructor
*/
VMLPieSlice = function()
{
VMLPieSlice.superclass.constructor.apply(this, arguments);
};
VMLPieSlice.NAME = "vmlPieSlice";
Y.extend(VMLPieSlice, Y.VMLShape, Y.mix({
/**
* Indicates the type of shape
*
* @property _type
* @type String
* @private
*/
_type: "shape",
/**
* Change event listener
*
* @private
* @method _updateHandler
*/
_draw: function(e)
{
var x = this.get("cx"),
y = this.get("cy"),
startAngle = this.get("startAngle"),
arc = this.get("arc"),
radius = this.get("radius");
this.clear();
this.drawWedge(x, y, startAngle, arc, radius);
this.end();
}
}, Y.VMLDrawing.prototype));
VMLPieSlice.ATTRS = Y.mix({
cx: {
value: 0
},
cy: {
value: 0
},
/**
* Starting angle in relation to a circle in which to begin the pie slice drawing.
*
* @config startAngle
* @type Number
*/
startAngle: {
value: 0
},
/**
* Arc of the slice.
*
* @config arc
* @type Number
*/
arc: {
value: 0
},
/**
* Radius of the circle in which the pie slice is drawn
*
* @config radius
* @type Number
*/
radius: {
value: 0
}
}, Y.VMLShape.ATTRS);
Y.VMLPieSlice = VMLPieSlice;
/**
* <a href="http://www.w3.org/TR/NOTE-VML">VML</a> implementation of the <a href="Graphic.html">`Graphic`</a> class.
* `VMLGraphic` is not intended to be used directly. Instead, use the <a href="Graphic.html">`Graphic`</a> class.
* If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> and <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a>
* capabilities, the <a href="Graphic.html">`Graphic`</a> class will point to the `VMLGraphic` class.
*
* @module graphics
* @class VMLGraphic
* @constructor
*/
VMLGraphic = function() {
VMLGraphic.superclass.constructor.apply(this, arguments);
};
VMLGraphic.NAME = "vmlGraphic";
VMLGraphic.ATTRS = {
/**
* Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node instance or a CSS selector string.
*
* @config render
* @type Node | String
*/
render: {},
/**
* Unique id for class instance.
*
* @config id
* @type String
*/
id: {
valueFn: function()
{
return Y.guid();
},
setter: function(val)
{
var node = this._node;
if(node)
{
node.setAttribute("id", val);
}
return val;
}
},
/**
* Key value pairs in which a shape instance is associated with its id.
*
* @config shapes
* @type Object
* @readOnly
*/
shapes: {
readOnly: true,
getter: function()
{
return this._shapes;
}
},
/**
* Object containing size and coordinate data for the content of a Graphic in relation to the coordSpace node.
*
* @config contentBounds
* @type Object
*/
contentBounds: {
readOnly: true,
getter: function()
{
return this._contentBounds;
}
},
/**
* The html element that represents to coordinate system of the Graphic instance.
*
* @config node
* @type HTMLElement
*/
node: {
readOnly: true,
getter: function()
{
return this._node;
}
},
/**
* Indicates the width of the `Graphic`.
*
* @config width
* @type Number
*/
width: {
setter: function(val)
{
if(this._node)
{
this._node.style.width = val + "px";
}
return val;
}
},
/**
* Indicates the height of the `Graphic`.
*
* @config height
* @type Number
*/
height: {
setter: function(val)
{
if(this._node)
{
this._node.style.height = val + "px";
}
return val;
}
},
/**
* Determines how the size of instance is calculated. If true, the width and height are determined by the size of the contents.
* If false, the width and height values are either explicitly set or determined by the size of the parent node's dimensions.
*
* @config autoSize
* @type Boolean
* @default false
*/
autoSize: {
value: false
},
/**
* The contentBounds will resize to greater values but not values. (for performance)
* When resizing the contentBounds down is desirable, set the resizeDown value to true.
*
* @config resizeDown
* @type Boolean
*/
resizeDown: {
getter: function()
{
return this._resizeDown;
},
setter: function(val)
{
this._resizeDown = val;
if(this._node)
{
this._redraw();
}
return val;
}
},
/**
* Indicates the x-coordinate for the instance.
*
* @config x
* @type Number
*/
x: {
getter: function()
{
return this._x;
},
setter: function(val)
{
this._x = val;
if(this._node)
{
this._node.style.left = val + "px";
}
return val;
}
},
/**
* Indicates the y-coordinate for the instance.
*
* @config y
* @type Number
*/
y: {
getter: function()
{
return this._y;
},
setter: function(val)
{
this._y = val;
if(this._node)
{
this._node.style.top = val + "px";
}
return val;
}
},
/**
* Indicates whether or not the instance will automatically redraw after a change is made to a shape.
* This property will get set to false when batching operations.
*
* @config autoDraw
* @type Boolean
* @default true
* @private
*/
autoDraw: {
value: true
},
visible: {
value: true,
setter: function(val)
{
this._toggleVisible(val);
return val;
}
}
};
Y.extend(VMLGraphic, Y.GraphicBase, {
/**
* Storage for `x` attribute.
*
* @property _x
* @type Number
* @private
*/
_x: 0,
/**
* Storage for `y` attribute.
*
* @property _y
* @type Number
* @private
*/
_y: 0,
/**
* Gets the current position of the graphic instance in page coordinates.
*
* @method getXY
* @return Array The XY position of the shape.
*/
getXY: function()
{
var node = Y.one(this._node),
xy;
if(node)
{
xy = node.getXY();
}
return xy;
},
/**
* @private
* @property _resizeDown
* @type Boolean
*/
_resizeDown: false,
/**
* Initializes the class.
*
* @method initializer
* @private
*/
initializer: function(config) {
var render = this.get("render");
this._shapes = {};
this._contentBounds = {
left: 0,
top: 0,
right: 0,
bottom: 0
};
this._node = this._createGraphic();
this._node.setAttribute("id", this.get("id"));
if(render)
{
this.render(render);
}
},
/**
* Adds the graphics node to the dom.
*
* @method render
* @param {HTMLElement} parentNode node in which to render the graphics node into.
*/
render: function(render) {
var parentNode = Y.one(render),
w = this.get("width") || parseInt(parentNode.getComputedStyle("width"), 10),
h = this.get("height") || parseInt(parentNode.getComputedStyle("height"), 10);
parentNode = parentNode || DOCUMENT.body;
parentNode.appendChild(this._node);
this.setSize(w, h);
this.parentNode = parentNode;
this.set("width", w);
this.set("height", h);
return this;
},
/**
* Removes all nodes.
*
* @method destroy
*/
destroy: function()
{
this.clear();
Y.one(this._node).remove(true);
},
/**
* Generates a shape instance by type.
*
* @method addShape
* @param {Object} cfg attributes for the shape
* @return Shape
*/
addShape: function(cfg)
{
cfg.graphic = this;
var shapeClass = this._getShapeClass(cfg.type),
shape = new shapeClass(cfg);
this._appendShape(shape);
return shape;
},
/**
* Adds a shape instance to the graphic instance.
*
* @method _appendShape
* @param {Shape} shape The shape instance to be added to the graphic.
* @private
*/
_appendShape: function(shape)
{
var node = shape.node,
parentNode = this._frag || this._node;
if(this.get("autoDraw"))
{
parentNode.appendChild(node);
}
else
{
this._getDocFrag().appendChild(node);
}
},
/**
* Removes a shape instance from from the graphic instance.
*
* @method removeShape
* @param {Shape|String} shape The instance or id of the shape to be removed.
*/
removeShape: function(shape)
{
if(!shape instanceof VMLShape)
{
if(Y_LANG.isString(shape))
{
shape = this._shapes[shape];
}
}
if(shape && shape instanceof VMLShape)
{
shape._destroy();
this._shapes[shape.get("id")] = null;
delete this._shapes[shape.get("id")];
}
if(this.get("autoDraw"))
{
this._redraw();
}
},
/**
* Removes all shape instances from the dom.
*
* @method removeAllShapes
*/
removeAllShapes: function()
{
var shapes = this._shapes,
i;
for(i in shapes)
{
if(shapes.hasOwnProperty(i))
{
shapes[i].destroy();
}
}
this._shapes = {};
},
/**
* Removes all child nodes.
*
* @method _removeChildren
* @param node
* @private
*/
_removeChildren: function(node)
{
if(node.hasChildNodes())
{
var child;
while(node.firstChild)
{
child = node.firstChild;
this._removeChildren(child);
node.removeChild(child);
}
}
},
/**
* Clears the graphics object.
*
* @method clear
*/
clear: function() {
this.removeAllShapes();
this._removeChildren(this._node);
},
/**
* Toggles visibility
*
* @method _toggleVisible
* @param {Boolean} val indicates visibilitye
* @private
*/
_toggleVisible: function(val)
{
var i,
shapes = this._shapes,
visibility = val ? "visible" : "hidden";
if(shapes)
{
for(i in shapes)
{
if(shapes.hasOwnProperty(i))
{
shapes[i].set("visible", val);
}
}
}
this._node.style.visibility = visibility;
},
/**
* Sets the size of the graphics object.
*
* @method setSize
* @param w {Number} width to set for the instance.
* @param h {Number} height to set for the instance.
*/
setSize: function(w, h) {
w = Math.round(w);
h = Math.round(h);
this._node.style.width = w + 'px';
this._node.style.height = h + 'px';
this._node.coordSize = w + ' ' + h;
},
/**
* Sets the positon of the graphics object.
*
* @method setPosition
* @param {Number} x x-coordinate for the object.
* @param {Number} y y-coordinate for the object.
*/
setPosition: function(x, y)
{
x = Math.round(x);
y = Math.round(y);
this._node.style.left = x + "px";
this._node.style.top = y + "px";
},
/**
* Creates a group element
*
* @method _createGraphic
* @private
*/
_createGraphic: function() {
var group = DOCUMENT.createElement('<group xmlns="urn:schemas-microsft.com:vml" style="behavior:url(#default#VML);display:block;zoom:1;" />');
group.style.display = "block";
group.style.position = 'absolute';
return group;
},
/**
* Creates a graphic node
*
* @method _createGraphicNode
* @param {String} type node type to create
* @param {String} pe specified pointer-events value
* @return HTMLElement
* @private
*/
_createGraphicNode: function(type)
{
return DOCUMENT.createElement('<' + type + ' xmlns="urn:schemas-microsft.com:vml" style="behavior:url(#default#VML);display:inline-block;zoom:1;" />');
},
/**
* Returns a shape based on the id of its dom node.
*
* @method getShapeById
* @param {String} id Dom id of the shape's node attribute.
* @return Shape
*/
getShapeById: function(id)
{
return this._shapes[id];
},
/**
* Returns a shape class. Used by `addShape`.
*
* @method _getShapeClass
* @param {Shape | String} val Indicates which shape class.
* @return Function
* @private
*/
_getShapeClass: function(val)
{
var shape = this._shapeClass[val];
if(shape)
{
return shape;
}
return val;
},
/**
* Look up for shape classes. Used by `addShape` to retrieve a class for instantiation.
*
* @property _shapeClass
* @type Object
* @private
*/
_shapeClass: {
circle: Y.VMLCircle,
rect: Y.VMLRect,
path: Y.VMLPath,
ellipse: Y.VMLEllipse,
pieslice: Y.VMLPieSlice
},
/**
* Allows for creating multiple shapes in order to batch appending and redraw operations.
*
* @method batch
* @param {Function} method Method to execute.
*/
batch: function(method)
{
var autoDraw = this.get("autoDraw");
this.set("autoDraw", false);
method.apply();
this._redraw();
this.set("autoDraw", autoDraw);
},
/**
* Returns a document fragment to for attaching shapes.
*
* @method _getDocFrag
* @return DocumentFragment
* @private
*/
_getDocFrag: function()
{
if(!this._frag)
{
this._frag = DOCUMENT.createDocumentFragment();
}
return this._frag;
},
/**
* Adds a shape to the redraw queue and calculates the contentBounds.
*
* @method addToRedrawQueue
* @param shape {VMLShape}
* @protected
*/
addToRedrawQueue: function(shape)
{
var shapeBox,
box;
this._shapes[shape.get("id")] = shape;
if(!this._resizeDown)
{
shapeBox = shape.getBounds();
box = this._contentBounds;
box.left = box.left < shapeBox.left ? box.left : shapeBox.left;
box.top = box.top < shapeBox.top ? box.top : shapeBox.top;
box.right = box.right > shapeBox.right ? box.right : shapeBox.right;
box.bottom = box.bottom > shapeBox.bottom ? box.bottom : shapeBox.bottom;
box.width = box.right - box.left;
box.height = box.bottom - box.top;
this._contentBounds = box;
}
if(this.get("autoDraw"))
{
this._redraw();
}
},
/**
* Redraws all shapes.
*
* @method _redraw
* @private
*/
_redraw: function()
{
var box = this._resizeDown ? this._getUpdatedContentBounds() : this._contentBounds;
if(this.get("autoSize"))
{
this.setSize(box.right, box.bottom);
}
if(this._frag)
{
this._node.appendChild(this._frag);
this._frag = null;
}
},
/**
* Recalculates and returns the `contentBounds` for the `Graphic` instance.
*
* @method _getUpdatedContentBounds
* @return {Object}
* @private
*/
_getUpdatedContentBounds: function()
{
var bounds,
i,
shape,
queue = this._shapes,
box = {
left: 0,
top: 0,
right: 0,
bottom: 0
};
for(i in queue)
{
if(queue.hasOwnProperty(i))
{
shape = queue[i];
bounds = shape.getBounds();
box.left = Math.min(box.left, bounds.left);
box.top = Math.min(box.top, bounds.top);
box.right = Math.max(box.right, bounds.right);
box.bottom = Math.max(box.bottom, bounds.bottom);
}
}
box.width = box.right - box.left;
box.height = box.bottom - box.top;
this._contentBounds = box;
return box;
}
});
Y.VMLGraphic = VMLGraphic;
}, '@VERSION@' ,{skinnable:false, requires:['graphics']});
|
/*!
* Globalize v1.0.0-alpha.8
*
* http://github.com/jquery/globalize
*
* Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-10-08T19:13Z
*/
// Core
module.exports = require( "./globalize" );
// Extent core with the following modules
require( "./globalize/date" );
require( "./globalize/message" );
require( "./globalize/number" );
require( "./globalize/plural" );
|
/*
Input Mask plugin dependencyLib
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(["jqlite"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("jqlite"));
} else {
factory(jQuery);
}
}
(function ($) {
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
function indexOf(list, elem) {
var i = 0,
len = list.length;
for (; i < len; i++) {
if (list[i] === elem) {
return i;
}
}
return -1;
}
var class2type = {},
classTypes = "Boolean Number String Function Array Date RegExp Object Error".split(" ");
for (var nameNdx = 0; nameNdx < classTypes.length; nameNdx++) {
class2type["[object " + classTypes[nameNdx] + "]"] = classTypes[nameNdx].toLowerCase();
}
function type(obj) {
if (obj == null) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[class2type.toString.call(obj)] || "object" :
typeof obj;
}
function isWindow(obj) {
return obj != null && obj === obj.window;
}
function isArraylike(obj) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
ltype = type(obj);
if (ltype === "function" || isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && length) {
return true;
}
return ltype === "array" || length === 0 ||
typeof length === "number" && length > 0 && (length - 1) in obj;
}
$.inArray = function (elem, arr, i) {
return arr == null ? -1 : indexOf(arr, elem, i);
};
$.isFunction = function (obj) {
return type(obj) === "function";
};
$.isArray = Array.isArray;
$.isPlainObject = function (obj) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
return false;
}
if (obj.constructor && !class2type.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
};
$.extend = function () {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
// Skip the boolean and the target
target = arguments[i] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !$.isFunction(target)) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && $.isArray(src) ? src : [];
} else {
clone = src && $.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = $.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
$.each = function (obj, callback) {
var value, i = 0;
if (isArraylike(obj)) {
for (var length = obj.length; i < length; i++) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
}
return obj;
};
$.map = function (elems, callback) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike(elems),
ret = [];
// Go through the array, translating each of the items to their new values
if (isArray) {
for (; i < length; i++) {
value = callback(elems[i], i);
if (value != null) {
ret.push(value);
}
}
// Go through every key on the object,
} else {
for (i in elems) {
value = callback(elems[i], i);
if (value != null) {
ret.push(value);
}
}
}
// Flatten any nested arrays
return [].concat(ret);
};
$.data = function (elem, name, data) {
return $(elem).data(name, data);
};
$.Event = $.Event || function CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
$.Event.prototype = window.Event.prototype;
window.dependencyLib = $;
return $;
}));
|
[a, b] = f();
;
|
/*!
Copyright (C) 2014 by Andrea Giammarchi - @WebReflection
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.
*/
define(function () {
var Class = Class || (function (Object) {
'use strict';
/*! (C) Andrea Giammarchi - MIT Style License */
var
// shortcuts for minifiers and ES3 private keywords too
CONSTRUCTOR = 'constructor',
EXTENDS = 'extends',
IMPLEMENTS = 'implements',
INIT = 'init',
PROTOTYPE = 'prototype',
STATIC = 'static',
SUPER = 'super',
WITH = 'with',
// infamous property used as fallback
// for IE8 and lower only
PROTO = '__proto__',
// used to copy non enumerable properties on IE
nonEnumerables = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
],
// IE < 9 bug only
hasIEEnumerableBug = !{valueOf:0}[nonEnumerables[2]](nonEnumerables[5]),
hOP = Object[nonEnumerables[0]],
// basic ad-hoc private fallback for old browsers
// use es5-shim if you want a properly patched polyfill
create = Object.create || function (proto) {
/*jshint newcap: false */
var isInstance = this instanceof create;
create[PROTOTYPE] = isInstance ? createPrototype : proto;
return isInstance ? this : new create();
},
// very old browsers actually work better
// without assigning null as prototype
createPrototype = create[PROTOTYPE],
// redefined if not present
defineProperty = Object.defineProperty,
// basic ad-hoc private fallback for old browsers
// use es5-shim if you want a properly patched polyfill
gOPD = Object.getOwnPropertyDescriptor || function (object, key) {
return {value: object[key]};
},
// basic ad-hoc private fallback for old browsers
// use es5-shim if you want a properly patched polyfill
gOPN = Object.getOwnPropertyNames || function (object) {
var names = [], i, key;
for (key in object) {
if (hOP.call(object, key)) {
names.push(key);
}
}
if (hasIEEnumerableBug) {
for (i = 0; i < nonEnumerables.length; i++) {
key = nonEnumerables[i];
if (hOP.call(object, key)) {
names.push(key);
}
}
}
return names;
},
// needed to verify the existence
getPrototypeOf = Object.getPrototypeOf,
// needed to allow Classes as traits
gPO = getPrototypeOf || function (o) {
return o[PROTO] || null;
},
// used to avoid setting `arguments` and other function properties
// when public static are copied over
nativeFunctionOPN = new RegExp('^(?:' + gOPN(function () {}).join('|') + ')$'),
superRegExp = /\bsuper\b/.test(function () {
// this test should never be minifier sensistive
this['super']();
}) ? /\bsuper\b/ : /.*/
// In 2010 Opera 10.5 for Linux Debian 6
// goes nut with methods to string representation,
// truncating pieces of text in an unpredictable way.
// If you are targeting such browser
// be aware that super invocation might fail.
// This is the only exception I could find
// from year 2000 to modern days browsers
// plus everything else would work just fine.
;
// verified broken IE8
try {
defineProperty({}, '{}', {});
} catch(o_O) {
defineProperty = function (object, name, descriptor) {
object[name] = descriptor.value;
return object;
};
}
// copy all imported enumerable methods and properties
function addMixins(mixins, target, inherits) {
for (var
source,
init = [],
i = 0; i < mixins.length; i++
) {
source = transformMixin(mixins[i]);
if (hOP.call(source, INIT)) {
init.push(source[INIT]);
}
copyOwn(source, target, inherits, false, false);
}
return init;
}
// used to copy properties from a class used as trait
function assignFromPrototype(key) {
/*jshint validthis: true */
if (isNotASpecialKey(key, false) && !hOP.call(this, key)) {
defineProperty(this, key, gOPD(this.init.prototype, key));
}
}
// configure source own properties in the target
function copyOwn(source, target, inherits, publicStatic, allowInit) {
for (var
key,
noFunctionCheck = typeof source !== 'function',
names = gOPN(source),
i = 0; i < names.length; i++
) {
key = names[i];
if (
(noFunctionCheck || !nativeFunctionOPN.test(key)) &&
isNotASpecialKey(key, allowInit)
) {
if (hOP.call(target, key)) {
warn('duplicated: ' + key);
}
setProperty(inherits, target, key, gOPD(source, key), publicStatic);
}
}
}
// return the right constructor analyzing the parent.
// if the parent is empty there is no need to call it.
function createConstructor(hasParentPrototype, parent) {
var Class = function Class() {};
return hasParentPrototype && ('' + parent) !== ('' + Class) ?
function Class() {
return parent.apply(this, arguments);
} :
Class
;
}
// common defineProperty wrapper
function define(target, key, value, publicStatic) {
var configurable = isConfigurable(key, publicStatic);
defineProperty(target, key, {
enumerable: false, // was: publicStatic,
configurable: configurable,
writable: configurable,
value: value
});
}
// is key is UPPER_CASE and the property is public static
// it will define the property as non configurable and non writable
function isConfigurable(key, publicStatic) {
return publicStatic ? !/^[A-Z_]+$/.test(key) : true;
}
// verifies a key is not special for the class
function isNotASpecialKey(key, allowInit) {
return key !== CONSTRUCTOR &&
key !== EXTENDS &&
key !== IMPLEMENTS &&
// Blackberry 7 and old WebKit bug only:
// user defined functions have
// enumerable prototype and constructor
key !== PROTOTYPE &&
key !== STATIC &&
key !== SUPER &&
key !== WITH &&
(allowInit || key !== INIT);
}
// will eventually convert classes or constructors
// into trait objects, before assigning them as such
function transformMixin(trait) {
if (typeof trait === 'object') return trait;
if (trait.length) {
warn((trait.name || 'Class') + ' should not expect arguments');
}
for (var
object = {init: trait},
proto = trait.prototype;
proto && proto !== Object.prototype;
proto = gPO(proto)
) {
gOPN(proto).forEach(assignFromPrototype, object);
}
return object;
}
// set a property via defineProperty using a common descriptor
// only if properties where not defined yet.
// If publicStatic is true, properties are both non configurable and non writable
function setProperty(inherits, target, key, descriptor, publicStatic) {
var
hasValue = hOP.call(descriptor, 'value'),
configurable,
value
;
if (publicStatic) {
if (hOP.call(target, key)) {
return;
}
} else if (hasValue) {
value = descriptor.value;
if (typeof value === 'function' && superRegExp.test(value)) {
descriptor.value = wrap(inherits, key, value, publicStatic);
}
} else {
wrapGetOrSet(inherits, key, descriptor, 'get');
wrapGetOrSet(inherits, key, descriptor, 'set');
}
configurable = isConfigurable(key, publicStatic);
descriptor.enumerable = false; // was: publicStatic;
descriptor.configurable = configurable;
if (hasValue) {
descriptor.writable = configurable;
}
defineProperty(target, key, descriptor);
}
// basic check against expected properties or methods
// used when `implements` is used
function verifyImplementations(interfaces, target) {
for (var
current,
key,
i = 0; i < interfaces.length; i++
) {
current = interfaces[i];
for (key in current) {
if (hOP.call(current, key) && !hOP.call(target, key)) {
warn(key + ' is not implemented');
}
}
}
}
// warn if something doesn't look right
// such overwritten public statics
// or traits / mixins assigning twice same thing
function warn(message) {
try {
console.warn(message);
} catch(meh) {
/*\_(ツ)_*/
}
}
// lightweight wrapper for methods that requires
// .super(...) invokaction - inspired by old klass.js
function wrap(inherits, key, method, publicStatic) {
return function () {
if (!hOP.call(this, SUPER)) {
// define it once in order to use
// fast assignment every other time
define(this, SUPER, null, publicStatic);
}
var
previous = this[SUPER],
current = (this[SUPER] = inherits[key]),
result = method.apply(this, arguments)
;
this[SUPER] = previous;
return result;
};
}
// get/set shortcut for the eventual wrapper
function wrapGetOrSet(inherits, key, descriptor, gs, publicStatic) {
if (hOP.call(descriptor, gs) && superRegExp.test(descriptor[gs])) {
descriptor[gs] = wrap(
gOPD(inherits, key),
gs,
descriptor[gs],
publicStatic
);
}
}
// the actual Class({ ... }) definition
return function (description) {
var
hasConstructor = hOP.call(description, CONSTRUCTOR),
hasParent = hOP.call(description, EXTENDS),
parent = hasParent && description[EXTENDS],
hasParentPrototype = hasParent && typeof parent === 'function',
inherits = hasParentPrototype ? parent[PROTOTYPE] : parent,
constructor = hasConstructor ?
description[CONSTRUCTOR] :
createConstructor(hasParentPrototype, parent),
hasSuper = hasParent && hasConstructor && superRegExp.test(constructor),
prototype = hasParent ? create(inherits) : constructor[PROTOTYPE],
mixins,
length
;
if (hasSuper) {
constructor = wrap(inherits, CONSTRUCTOR, constructor, false);
}
// add modules/mixins (that might swap the constructor)
if (hOP.call(description, WITH)) {
mixins = addMixins([].concat(description[WITH]), prototype, inherits);
length = mixins.length;
if (length) {
constructor = (function (parent) {
return function () {
var i = 0;
while (i < length) mixins[i++].call(this);
return parent.apply(this, arguments);
};
}(constructor));
constructor[PROTOTYPE] = prototype;
}
}
if (hOP.call(description, STATIC)) {
// add new public static properties first
copyOwn(description[STATIC], constructor, inherits, true, true);
}
if (hasParent) {
// in case it's a function
if (parent !== inherits) {
// copy possibly inherited statics too
copyOwn(parent, constructor, inherits, true, true);
}
constructor[PROTOTYPE] = prototype;
}
if (prototype[CONSTRUCTOR] !== constructor) {
define(prototype, CONSTRUCTOR, constructor, false);
}
// enrich the prototype
copyOwn(description, prototype, inherits, false, true);
if (hOP.call(description, IMPLEMENTS)) {
verifyImplementations([].concat(description[IMPLEMENTS]), prototype);
}
if (hasParent && !getPrototypeOf) {
define(prototype, PROTO, inherits, false);
}
return constructor;
};
}(Object));
return Class;
});
|
'use strict';
var $ = require('./$')
, hide = require('./$.hide')
, ctx = require('./$.ctx')
, species = require('./$.species')
, strictNew = require('./$.strict-new')
, defined = require('./$.defined')
, forOf = require('./$.for-of')
, step = require('./$.iter-step')
, ID = require('./$.uid')('id')
, $has = require('./$.has')
, isObject = require('./$.is-object')
, isExtensible = Object.isExtensible || isObject
, SUPPORT_DESC = require('./$.support-desc')
, SIZE = SUPPORT_DESC ? '_s' : 'size'
, id = 0;
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!$has(it, ID)){
// can't set id to frozen object
if(!isExtensible(it))return 'F';
// not necessary to add id
if(!create)return 'E';
// add missing object id
hide(it, ID, ++id);
// return object id with prefix
} return 'O' + it[ID];
};
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = $.create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
require('./$.mix')(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments[1], 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(SUPPORT_DESC)$.setDesc(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
require('./$.iter-define')(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
species(C);
species(require('./$.core')[NAME]); // for wrapper
}
};
|
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutoFocusMixin
* @typechecks static-only
*/
'use strict';
var focusNode = require('focusNode');
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
|
;(function($, window, document, undefined) {
var pluginName = "metisMenu",
defaults = {
toggle: true,
doubleTapToGo: false
};
function Plugin(element, options) {
this.element = $(element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var $this = this.element,
$toggle = this.settings.toggle,
obj = this;
if (this.isIE() <= 9) {
$this.find("li.active").has("ul").children("ul").collapse("show");
$this.find("li").not(".active").has("ul").children("ul").collapse("hide");
} else {
$this.find("li.active").has("ul").children("ul").addClass("collapse in");
$this.find("li").not(".active").has("ul").children("ul").addClass("collapse");
}
//add the "doubleTapToGo" class to active items if needed
if (obj.settings.doubleTapToGo) {
$this.find("li.active").has("ul").children("a").addClass("doubleTapToGo");
}
$this.find("li").has("ul").children("a").on("click" + "." + pluginName, function(e) {
e.preventDefault();
//Do we need to enable the double tap
if (obj.settings.doubleTapToGo) {
//if we hit a second time on the link and the href is valid, navigate to that url
if (obj.doubleTapToGo($(this)) && $(this).attr("href") !== "#" && $(this).attr("href") !== "") {
e.stopPropagation();
document.location = $(this).attr("href");
return;
}
}
$(this).parent("li").toggleClass("active").children("ul").collapse("toggle");
if ($toggle) {
$(this).parent("li").siblings().removeClass("active").children("ul.in").collapse("hide");
}
});
},
isIE: function() { //https://gist.github.com/padolsey/527683
var undef,
v = 3,
div = document.createElement("div"),
all = div.getElementsByTagName("i");
while (
div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->",
all[0]
) {
return v > 4 ? v : undef;
}
},
//Enable the link on the second click.
doubleTapToGo: function(elem) {
var $this = this.element;
//if the class "doubleTapToGo" exists, remove it and return
if (elem.hasClass("doubleTapToGo")) {
elem.removeClass("doubleTapToGo");
return true;
}
//does not exists, add a new class and return false
if (elem.parent().children("ul").length) {
//first remove all other class
$this.find(".doubleTapToGo").removeClass("doubleTapToGo");
//add the class on the current element
elem.addClass("doubleTapToGo");
return false;
}
},
remove: function() {
this.element.off("." + pluginName);
this.element.removeData(pluginName);
}
};
$.fn[pluginName] = function(options) {
this.each(function () {
var el = $(this);
if (el.data(pluginName)) {
el.data(pluginName).remove();
}
el.data(pluginName, new Plugin(this, options));
});
return this;
};
})(jQuery, window, document);
|
/*!
* Qoopido.js library v3.6.1, 2015-2-5
* https://github.com/dlueth/qoopido.js
* (c) 2015 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(e){window.qoopido.register("support/element/svg",e,["../../support"])}(function(e,t,r,n,o,s){"use strict";return e.support.addTest("/element/svg",function(e){s.createElementNS&&s.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect?e.resolve():e.reject()})});
|
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/pl/currency",{"HKD_displayName":"dolar hongkoński","CHF_displayName":"frank szwajcarski","JPY_symbol":"JPY","CAD_displayName":"dolar kanadyjski","HKD_symbol":"HKD","CNY_displayName":"juan chiński","USD_symbol":"USD","AUD_displayName":"dolar australijski","JPY_displayName":"jen japoński","CAD_symbol":"CAD","USD_displayName":"dolar amerykański","CNY_symbol":"CNY","GBP_displayName":"funt szterling","GBP_symbol":"GBP","AUD_symbol":"AUD","EUR_displayName":"euro"});
|
var toString = require('./toString');
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
rsComboSymbolsRange = '\\u20d0-\\u20f0',
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsQuoteRange = '\\u2018\\u2019\\u201c\\u201d',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsQuoteRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
/** Used to match non-compound words composed of alphanumeric characters. */
var reBasicWord = /[a-zA-Z0-9]+/g;
/** Used to match complex or compound words. */
var reComplexWord = RegExp([
rsUpper + '?' + rsLower + '+(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsUpperMisc + '+(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
rsUpper + '?' + rsLowerMisc + '+',
rsUpper + '+',
rsDigits,
rsEmoji
].join('|'), 'g');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasComplexWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord;
}
return string.match(pattern) || [];
}
module.exports = words;
|
(function(global) {
var define = global.define;
var require = global.require;
var Ember = global.Ember;
if (typeof Ember === 'undefined' && typeof require !== 'undefined') {
Ember = require('ember');
}
Ember.libraries.register('Ember Simple Auth Torii', '0.8.0-beta.1');
define("simple-auth-torii/authenticators/torii",
["simple-auth/authenticators/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Base = __dependency1__["default"];
/**
Authenticator that wraps the
[Torii library](https://github.com/Vestorly/torii).
_The factory for this authenticator is registered as
`'simple-auth-authenticator:torii'` in Ember's container._
@class Torii
@namespace SimpleAuth.Authenticators
@module simple-auth-torii/authenticators/torii
@extends Base
*/
__exports__["default"] = Base.extend({
/**
@property torii
@private
*/
torii: null,
/**
@property provider
@private
*/
provider: null,
/**
Restores the session by calling the torii provider's `fetch` method.
@method restore
@param {Object} data The data to restore the session from
@return {Ember.RSVP.Promise} A promise that when it resolves results in the session being authenticated
*/
restore: function(data) {
var _this = this;
data = data || {};
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(data.provider)) {
var provider = data.provider;
_this.torii.fetch(data.provider, data).then(function(data) {
_this.resolveWith(provider, data, resolve);
}, function() {
delete _this.provider;
reject();
});
} else {
delete _this.provider;
reject();
}
});
},
/**
Authenticates the session by opening the torii provider. For more
documentation on torii, see the
[project's README](https://github.com/Vestorly/torii#readme).
@method authenticate
@param {String} provider The provider to authenticate the session with
@param {Object} options The options to pass to the torii provider
@return {Ember.RSVP.Promise} A promise that resolves when the provider successfully authenticates a user and rejects otherwise
*/
authenticate: function(provider, options) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
_this.torii.open(provider, options || {}).then(function(data) {
_this.resolveWith(provider, data, resolve);
}, reject);
});
},
/**
Closes the torii provider.
@method invalidate
@param {Object} data The data that's stored in the session
@return {Ember.RSVP.Promise} A promise that resolves when the provider successfully closes and rejects otherwise
*/
invalidate: function(data) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
_this.torii.close(_this.provider).then(function() {
delete _this.provider;
resolve();
}, reject);
});
},
/**
@method resolveWith
@private
*/
resolveWith: function(provider, data, resolve) {
data.provider = provider;
this.provider = data.provider;
resolve(data);
}
});
});
define("simple-auth-torii/ember",
["./initializer"],
function(__dependency1__) {
"use strict";
var initializer = __dependency1__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer(initializer);
});
});
define("simple-auth-torii/initializer",
["simple-auth-torii/authenticators/torii","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Authenticator = __dependency1__["default"];
__exports__["default"] = {
name: 'simple-auth-torii',
before: 'simple-auth',
after: 'torii',
initialize: function(container, application) {
var torii = container.lookup('torii:main');
var authenticator = Authenticator.create({ torii: torii });
container.register('simple-auth-authenticator:torii', authenticator, { instantiate: false });
}
};
});
})(this);
|
require('conventional-changelog')({
from: "f36e96f9b1c2a8bdf90b2bf94346581f922d4c3c",
repository: 'https://github.com/shakyShane/opt-merger',
version: require('./package.json').version
}, function(err, log) {
require("fs").writeFileSync("./CHANGELOG.md", log);
});
|
module.exports = {
"env": {
"node": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [ "error", 4 ],
"linebreak-style": [ "error", "unix" ],
//"quotes": [ "error", "single" ],
"semi": [ "error", "always" ]
}
};
|
/**
* KEYCHAIN
*
* Manages the actual signing keys for the account.
*
* The account is locked by default. When a transaction is requested, the user
* can enter their password to unlock their account for a certain period of
* time. This class manages the timeout when the account will be re-locked.
*/
var webutil = require('../util/web'),
settings = require('../util/settings'),
log = require('../util/log');
var module = angular.module('keychain', ['popup']);
module.factory('rpKeychain', ['$rootScope', '$timeout', 'rpPopup', 'rpId',
'$interval',
function ($scope, $timeout, popup, id, $interval)
{
var Keychain = function ()
{
var _this = this;
this.secrets = {};
};
// Default unlock duration is 5 minutes
Keychain.unlockDuration = 5 * 60 * 1000;
Keychain.prototype.isUnlocked = function (account) {
return !!this.secrets[account];
};
/**
* Getting a secret for an account with default UI.
*
* This function will immediatly callback if the wallet is already unlocked.
* Otherwise, it will automatically handle the unlock process using a modal
* popover.
*
* If the user cancels the operation, the method will call the callback with
* an error.
*/
Keychain.prototype.requestSecret = function (account, username, purpose, callback) {
var _this = this;
if ('function' === typeof purpose) {
callback = purpose;
purpose = null;
}
// Handle already unlocked accounts
if (this.secrets[account]) {
// Keep the secret in a closure in case it happens to get locked
// between now and when $timeout calls back.
var secret = this.secrets[account].masterkey;
$timeout(function () {
callback(null, secret);
});
return;
}
var popupScope = $scope.$new();
var unlock = popupScope.unlock = {
isConfirming: false,
password: '',
purpose: purpose
};
popupScope.updater = $interval(function() {
var password = $('input[name="popup_unlock_password"]').val();
if (typeof password === 'string') {
popupScope.unlockForm.popup_unlock_password.$setViewValue(password);
}
}, 2000);
popupScope.confirm = function () {
unlock.isConfirming = true;
unlock.error = null;
function handleSecret(err, secret) {
if (err) {
// XXX More fine-grained error handling would be good. Can we detect
// server down?
unlock.isConfirming = false;
// check for 'Could not query PAKDF server'
if (err instanceof Error && typeof err.message === 'string' && err.message.indexOf('PAKDF') !== -1) {
unlock.error = 'server';
} else {
unlock.error = 'password';
}
} else {
$interval.cancel(popupScope.updater);
popup.close();
callback(null, secret);
}
}
_this.getSecret(account, username, popupScope.unlock.password,
handleSecret);
};
popupScope.cancel = function() {
$interval.cancel(popupScope.updater);
// need this for setting password protection
callback('canceled');
popup.close();
};
popupScope.onKeyUp = function($event) {
// esc button
if ($event.which === 27) popupScope.cancel();
};
popup.blank(require('../../jade/popup/unlock.jade')(), popupScope);
};
/**
* Getting a secret for an account with custom UI.
*
* The difference between this method and Keychain#requestSecret is that to
* call this function you have to request the password from the user yourself.
*/
Keychain.prototype.getSecret = function (account, username, password, callback) {
var _this = this;
// Handle already unlocked accounts
if (this.secrets[account] && this.secrets[account].password === password) {
// Keep the secret in a closure in case it happens to get locked
// between now and when $timeout calls back.
var secret = this.secrets[account].masterkey;
$timeout(function () {
callback(null, secret);
});
return;
}
id.unlock(username, password, function (err, secret) {
if (err) {
callback(err);
return;
}
// Cache secret for unlock period
_this.secrets[account] = {
masterkey: secret,
password: password
};
_this.expireSecret(account);
callback(null, secret);
});
};
/**
* Synchronous way to acquire secret.
*
* This function will only work if the account is already unlocked. Throws an
* error otherwise.
*/
Keychain.prototype.getUnlockedSecret = function(account) {
if (!this.isUnlocked(account)) {
throw new Error('Keychain: Tried to get secret for locked account synchronously.');
}
return this.secrets[account].masterkey;
};
/**
* setPasswordProtection
* @param {Object} protect
* @param {Object} callback
*/
Keychain.prototype.setPasswordProtection = function (requirePassword, callback) {
var _this = this;
if (requirePassword === false) {
this.requestSecret(id.account, id.username, function(err, secret) {
if (err) {
return callback(err);
}
setPasswordProtection(requirePassword, secret, callback);
});
} else {
setPasswordProtection(requirePassword, null, callback);
}
function setPasswordProtection (requirePassword, secret, callback) {
$scope.userBlob.set('/clients/rippletradecom/persistUnlock', !requirePassword, function(err, resp) {
if (err) {
return callback(err);
}
if (requirePassword) {
_this.expireSecret(id.account);
}
});
}
};
Keychain.prototype.expireSecret = function (account) {
var _this = this;
$timeout(function() {
if (_this.secrets[account] && !settings.getSetting($scope.userBlob, 'persistUnlock', false)) {
delete _this.secrets[account];
}
}, Keychain.unlockDuration);
};
return new Keychain();
}]);
|
'use strict';
// url we're sending the request to
var xMapTileUrl = 'https://s0{s}-xserver2-test.cloud.ptvgroup.com/services/rest/XMap/tile/{z}/{x}/{y}?storedProfile={profile}&xtok={token}';
var findAddressUrl = 'https://xserver2-test.cloud.ptvgroup.com/services/rest/XLocate/locations';
var calcIsoUrl = 'https://api-test.cloud.ptvgroup.com/xroute/rs/XRoute/calculateIsochrones';
var calcReachableObjectsUrl = 'https://api-test.cloud.ptvgroup.com/xroute/rs/XRoute/calculateReachableObjects';
var searchLocation;
var isoFeature;
var highlightedPois = [];
var isBusy = false;
var marker;
var circle;
var horizon = 600;
var searchMethod = 0;
var index;
var poiData;
var csvRows;
var filter;
var poiLayer;
var colors = {
'DIY': '#00bf59',
'RET': '#f1b2ff',
'DRG': '#e0d400',
'FRN': '#7fa9da',
'FIN': '#ffa53f',
'COM': '#15b4d5',
'EAT': '#a2ad2e',
'PHA': '#b19fbb',
'KFZ': '#5fba3d',
'CLO': '#ffb3c4',
'FOD': '#a0ff8c',
'LEH': '#c7f2ff',
'TVL': '#ffc58f',
'LSR': '#71ffd7',
'GAS': '#d5ffd0'
};
if (!token)
{alert('you need to configure your xServer internet token in token.js!')}
// set up the map
var attribution = '© ' + new Date().getFullYear() + ' PTV AG, HERE';
var mapLocation = new L.LatLng(49, 8.4);
// create a map in the "map" div, set the view to a given place and zoom
var map = new L.Map('map', {
fullscreenControl: true,
preferCanvas: true
}).setView(mapLocation, 12);
// insert xMap back- and forground layers with silica-style
L.tileLayer(xMapTileUrl, {
token: window.token,
profile: 'blackmarble',
attribution: '© ' + new Date().getFullYear() + ' PTV AG, HERE',
maxZoom: 22,
subdomains: '1234'
}).addTo(map);
map._container.style.background = '#000';
// shim: implement missing startsWith();
fixOldIE();
document.getElementById('f1')
.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById('b1').click();
}
});
document.getElementById('f2')
.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById('b2').click();
}
});
// add scale control
L.control.scale().addTo(map);
map.on('click', onMapClick);
// add input control
var info = L.control();
info.onAdd = function (map) {
var container = document.getElementById('panel-control')
L.DomEvent.disableClickPropagation(container);
L.DomEvent.disableScrollPropagation(container);
return container;
};
info.addTo(map);
// using legend code from http://leafletjs.com/examples/choropleth-example.html
var legend = L.control({
position: 'bottomright'
});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
var str = '';
var i = 0;
str += '<div class="pure-g">';
for (var key in colors) {
if (colors.hasOwnProperty(key)) {
str +=
'<div class="pure-u-1-3"><i style="background:' + colors[key] + '"></i> ' + key + '</div>';
if ((i + 1) % 3 === 0 && i > 0 && i < Object.keys(colors).length - 1)
{str += '</div><div class="pure-g">';}
i++;
}
}
str += '</div>';
div.innerHTML = str;
return div;
};
legend.addTo(map);
setBusy(true);
// d3.json('https://cdn.rawgit.com/ptv-logistics/xserverjs/98a9f370/premium-samples/poi-locator/inobas.json', initializeMap);
ssv('https://raw.githubusercontent.com/ptv-logistics/xserverjs/master/premium-samples/poi-locator/data/inobas-slim.csv', initializeMap);
function initializeMap(rows) {
setBusy(false);
// store our data
csvRows = rows;
// set Karlsruhe
searchLocation = new L.LatLng(49.013301829, 8.4277897486);
setMarker();
filterPois();
}
function setBusy(busy) {
isBusy = busy;
document.getElementById('myFieldSet').disabled = busy;
}
function setMarker(radius) {
cleanupMarkers(true);
if (radius) {
circle = L.circle(searchLocation, radius, {
zIndex: 1000
}).addTo(map);
}
var c = 'marker-red';
marker = L.marker(searchLocation, {
zIndexOffset: 1000,
icon: new L.Icon.Default({
imagePath: './icons/',
iconUrl: c + '.png',
iconRetinaUrl: c + '-2x.png'
}),
draggable: true
}).addTo(map)
marker.bindPopup(latFormatter(searchLocation.lat) + ', ' + lngFormatter(searchLocation.lng));
marker.on('dragend', function (e) {
onMapClick(e.target);
});
}
function findNearestObjects() {
if (!searchLocation)
{return;}
cleanupMarkers();
if (searchMethod == 0)
{findByAirline(searchLocation, horizon);}
else if (searchMethod == 1)
{findByReachableObjects(searchLocation, horizon);}
else
{findByIso(searchLocation, horizon);}
}
function setSearchMethod(method) {
searchMethod = method;
findNearestObjects();
}
function setHorizon(hor) {
horizon = hor;
findNearestObjects();
}
function onMapClick(e) {
if (isBusy)
{return;}
searchLocation = e.latlng || e._latlng;
setMarker();
findNearestObjects();
}
function filterPois() {
var e = document.getElementById('type');
var value = e.options[e.selectedIndex].value;
if (value === '---')
{filter = null;}
else
{filter = value;}
poiData = createJsonFromRows(csvRows);
if (filter) {
poiData.features = poiData.features.filter(function (d) {
return d.properties.category === filter;
});
}
// tip: sort the features by latitue, so they overlap nicely on the map!
poiData.features.sort(function (a, b) {
return b.geometry.coordinates[1] - a.geometry.coordinates[1];
});
if (poiLayer)
{map.removeLayer(poiLayer);}
poiLayer = L.geoJson(poiData, {
attribution: 'DDS, Inobas',
pointToLayer: poiStyle
}).addTo(map);
// create full text index
index = lunr(function () {
this.field('description', {
boost: 10
})
this.ref('id')
})
for (var i = 0; i < poiData.features.length; i++) {
index.add({
id: i,
description: poiData.features[i].properties.description
});
}
// initiate search
findNearestObjects();
}
/**
* Loads a semicolon separated text file
* @param {} url
* @param {} callback
*/
function ssv(url, callback) {
var ssvParse = d3.dsvFormat(';');
d3.request(url)
.mimeType('text/csv')
.response(function (xhr) {
return ssvParse.parse(xhr.responseText);
})
.get(callback);
}
/**
* Creates a GeoJson from our row collection
* @param {} rows
*/
function createJsonFromRows(rows) {
var json = {
type: 'FeatureCollection'
};
json.features = rows.map(function (d) {
var feature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: ptvMercatorToWgs(d.X, d.Y)
},
properties: {
id: d.ID,
category: d.CATEGORY,
www: d.WWW,
description: d.NAME
}
};
return feature;
});
return json;
}
function findFulltext(name) {
cleanupMarkers();
var res = index.search(name);
var found = res.map(function (d) {
return {
feature: poiData.features[d.ref],
info: poiData.features[d.ref].name
};
});
highlightPois(found);
setBounds(highlightedPois);
}
function findByAddress(adr) {
setBusy(true);
d3.json(findAddressUrl + '/' + encodeURIComponent(adr) + (token ? '?xtok=' + token : ''),
function (error, response) {
setBusy(false);
if (error) {
var message = JSON.parse(error.target.response).errorMessage;
alert(message);
return;
}
if (response.results.length === 0) {
alert('nothing found!');
return;
}
var firstResult = response.results[0].location;
searchLocation = new L.LatLng(firstResult.referenceCoordinate.y, firstResult.referenceCoordinate.x);
setMarker();
findNearestObjects();
});
}
function findByGeolocation(adr) {
setBusy(true);
map.locate({
setView: true,
maxZoom: 16
});
}
map.on('locationfound', function (e) {
searchLocation = e.latlng;
setMarker(e.accuracy);
findNearestObjects();
});
map.on('locationerror', function (e) {
alert(e.message);
setBusy(false);
});
function findByIso(latlng, hor) {
setBusy(true);
var request = {
'sink': {
'coords': [{
'point': {
'x': latlng.lng,
'y': latlng.lat
}
}],
'linkType': 'NEXT_SEGMENT'
},
'options': [],
'isoOptions': {
'isoDetail': 'POLYS_ONLY',
'polygonCalculationMode': 'NODE_BASED',
'expansionDesc': {
'expansionType': 'EXP_TIME',
'horizons': [
hor
]
}
},
'callerContext': {
'properties': [{
'key': 'CoordFormat',
'value': 'OG_GEODECIMAL'
}, {
'key': 'ResponseGeometry',
'value': 'WKT'
}, {
'key': 'Profile',
'value': 'carfast'
}]
}
};
runRequest(
calcIsoUrl,
request,
token,
function (error, response) {
setBusy(false);
if (error) {
var message = JSON.parse(error.target.response).errorMessage;
alert(message);
return;
}
response = JSON.parse(response.responseText);
var x = isoToPoly(response.isochrones[0].polys.wkt);
var feature = {
'type': 'Feature',
'properties': {
'style': {
weight: 4,
color: '#aaa',
opacity: 1,
fillColor: '#fff',
fillOpacity: 0.5
}
}
};
feature.geometry = {
type: 'Polygon',
coordinates: x
};
isoFeature = L.geoJson([feature], {
style: function (feature) {
return feature.properties && feature.properties.style;
}
});
isoFeature.on('click', onMapClick);
isoFeature.addTo(map);
var pointsInPolygon = poiData.features
.filter(function (d) {
return leafletPip.pointInLayer(d.geometry.coordinates, isoFeature).length > 0;
})
.map(function (d) {
return {
feature: d,
info: d.name
}
});
highlightPois(pointsInPolygon, true);
map.fitBounds(isoFeature.getBounds());
}
);
}
function filterByAirline(latlng, hor) {
var range = hor /* =s*/ * 120 /* km/h */ / 3.6 /* =m/s */ ;
return poiData.features.map(function (d) {
var poiLocation = d.geometry.coordinates;
var p = L.latLng(poiLocation[1], poiLocation[0]);
var distance = latlng.distanceTo(p);
return {
feature: d,
distance: distance
};
})
.filter(function (d) {
return d.distance < range;
});
}
function findByAirline(latlng, hor) {
var found = filterByAirline(latlng, hor)
.map(function (d) {
return {
feature: d.feature,
info: Math.round(d.distance) + 'm'
};
});
highlightPois(found, true);
setBounds(highlightedPois, latlng);
setBusy(false);
}
function findByReachableObjects(latlng, hor) {
var candidates = filterByAirline(latlng, hor);
var locations = new Array();
for (var i = 0; i < candidates.length; i++) {
var location = candidates[i].feature.geometry.coordinates;
locations.push({
'coords': [{
'point': {
'x': location[0],
'y': location[1]
}
}],
'linkType': 'NEXT_SEGMENT'
});
}
setBusy(true);
var request = {
'sink': {
'coords': [{
'point': {
'x': latlng.lng,
'y': latlng.lat
}
}],
'linkType': 'NEXT_SEGMENT'
},
'binaryPathDesc': null,
'locations': locations,
'options': [],
'expansionDesc': {
'expansionType': 'EXP_TIME',
'horizons': [
hor
]
},
'callerContext': {
'properties': [{
'key': 'CoordFormat',
'value': 'OG_GEODECIMAL'
}, {
'key': 'ResponseGeometry',
'value': 'WKT'
}, {
'key': 'Profile',
'value': 'carfast'
}]
}
};
runRequest(
calcReachableObjectsUrl,
request,
token,
function (error, response) {
setBusy(false);
if (error) {
var message = JSON.parse(error.target.response).errorMessage;
alert(message);
return;
}
response = JSON.parse(response.responseText);
var found = candidates.map(function (d, i) {
return {
feature: d.feature,
reachInfo: response.reachInfo[i]
};
}).filter(function (d) {
return d.reachInfo.reachable;
}).map(function (d) {
return {
feature: d.feature,
info: d.reachInfo.routeInfo.distance + ' m'
};
});
highlightPois(found, true);
setBounds(highlightedPois, latlng);
});
}
function setBounds(features, center) {
var coords = features.map(function (d) {
return d._latlng;
});
if (center)
{coords.push(center);}
if (coords.length) {
map.fitBounds(new L.LatLngBounds(coords), {maxZoom: 16});
}
}
function cleanupMarkers(cleanupCirlcle) {
for (var i = 0; i < highlightedPois.length; i++) {
map.removeLayer(highlightedPois[i]);
}
highlightedPois = [];
if (isoFeature) {
map.removeLayer(isoFeature);
isoFeature = null;
}
if (cleanupCirlcle && marker) {
map.removeLayer(marker);
marker = null;
}
if (cleanupCirlcle && circle) {
map.removeLayer(circle);
circle = null;
}
}
function drawSpiderLine(feature, additionalInfo) {
var latlon = [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
var popUp = feature.properties.description;
if (additionalInfo)
{popUp = popUp + '<br>' + additionalInfo;}
var spidlerLineline = L.polyline([searchLocation, latlon], {
color: 'green',
weight: 1
}).addTo(map)
highlightedPois.push(spidlerLineline);
spidlerLineline.bindPopup(popUp);
}
function highlightPois(featureInfo, spiderLine) {
if (spiderLine)
{for (var i = 0; i < featureInfo.length; i++)
{drawSpiderLine(featureInfo[i].feature, featureInfo[i].info);}}
for (var i = 0; i < featureInfo.length; i++)
{highlightPoi(featureInfo[i].feature, featureInfo[i].info);}
}
function highlightPoi(feature, additionalInfo) {
var latlon = [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
var popUp = feature.properties.description;
if (additionalInfo)
{popUp = popUp + '<br>' + additionalInfo;}
var highlightedPoi = L.circleMarker(latlon, {
fillColor: 'yellow',
fillOpacity: 1,
stroke: true,
color: '#000',
boostType: 'balloon',
boostScale: 1,
boostExp: 0,
weight: 2
}).setRadius(10).addTo(map);
highlightedPoi.bindPopup(popUp);
highlightedPois.push(highlightedPoi);
}
function poiStyle(feature, latlng) {
var style =
L.circleMarker([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], {
fillColor: colors[feature.properties.category],
fillOpacity: 1,
stroke: true,
color: '#000',
boostType: 'ball',
boostScale: 2.5,
boostExp: 0.25,
weight: 2,
}).setRadius(6);
var html = feature.properties.description;
if (feature.properties.www) {
var hRef = feature.properties.www;
if (!hRef.startsWith('http'))
{hRef = 'http://' + hRef;}
html = html + '<br><a target="_blank" href="' + hRef + '">' + feature.properties.www + '</a>';
}
style.bindPopup(html);
return style;
}
|
"use strict";
var ClientWeb = require("./Client-web");
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ClientWeb;
|
'use strict';
if ($('show-aside-button')) {
/**
* Change aside margin to show it
* Change content width do adjust to fit on the side of aside
*/
var showAside = (function () {
$('aside-menu').setStyle('margin-left', '0rem');
$('content').setStyle('margin-right', '-17rem');
});
/**
* Change aside margin to hide it
* Change content width do adjust to fit on the side of aside
*/
var hideAside = (function () {
$('aside-menu').setStyle('margin-left', '-18rem');
$('content').setStyle('margin-right', '0rem');
});
/**
* Open and close button for aside-menu
*/
$('show-aside-button').addEvent('click', function (event) {
// Get the aside current margin-left as integer
var asideMargin = parseInt($('aside-menu').getStyle('margin-left'));
if (0 === asideMargin) {
hideAside();
return true;
}
showAside();
});
/**
* Catch all clicks on the content element, then check if we should close the
* aside or not.
*/
$('content').addEvent('click', function (event) {
var asideButtonVisible = $('show-aside-button').getStyle('display') !== 'none';
var asideVisible = parseInt($('aside-menu').getStyle('margin-left')) === 0;
if (false === asideButtonVisible && false === asideVisible) {
showAside();
}
if (true === asideButtonVisible && true === asideVisible) {
hideAside();
}
});
}
|
var request = require('request')
var cheerio = require('cheerio')
module.exports.scrape = scrape
function scrape(id, callback) {
var uri = "http://ingatlan.com/" + id
request({ uri: uri }, function(error, response, body) {
try {
var $ = cheerio.load(body)
} catch(e) {
console.log(e) // XXX: LOL DON'T CARE
return e
}
// this is just to make `name`'s construction more readable
var price = $('.parameter-price .parameter-value').text()
var size = $('.parameter-area-size .parameter-value').text()
var rooms = $('.parameter-room .parameter-value').text()
// construct card name from metadata
var name = price + " " + size + " / " + rooms
// "comment text" with link prepended for card description
var desc = uri + "\n\n" + $('.details .long-description').text() +
"\n\n" + desc
// first photo's URL for attachment
var photo = $('.listing-image .image')
.css('background-image')
.replace("url('","").replace("')","")
// call back with data
if (error) {
callback(error)
} else {
callback(null, {
name: name,
desc: desc,
photo: photo
})
}
})
}
|
registry = {
index: {
// ChannelID: conversationID
}
};
/*load default wikichat channel
conversationId = (process.env.BOT_FRAMEWORK_DIRECT_API_CONVERSATIONID)
var channel = {
type: "wikichat",
auth: {
host: (process.env.CHAT_HOST),
name: (process.env.WIKIA_BOT_NAME),
password: (process.env.WIKIA_BOT_PASSWORD),
key: "",
serverId: (process.env.CHAT_SERVER_ID),
wikiId: (process.env.CHAT_SERVER_ID),
roomId: (process.env.CHAT_ROOM_ID)
},
services: {},
socket: ""
};
registry[conversationId] = channel;
*/
/*
// Discord registry prototype
conversationId: {
type: "discord",
auth: {
name: (process.env.DISCORD_BOT_NAME),
token: (process.env.DISCORD_APP_TOKEN),
channelID: ""
},
services: {
ping: true,
recall: {},
roller: true
},
socket: ""
}
"service-manager": true,
"ping": true,
"recall": {
},
"roller": true,
"hourly": {
src: "./kancolle-hourlies.json",
timer: {}
},
"roleplay": {
ship: "Inazuma",
en: true,
jp: false,
voice: true
},
"air-power": true,
*/
module.exports = registry;
|
const chai = require('chai');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const Promise = require('bluebird');
global.assert = chai.assert;
global.expect = chai.expect;
global.Promise = Promise;
global.sinon = sinon;
global.proxyquire = proxyquire;
module.exports = {};
module.exports.fixtures = {};
|
// adopted from: https://github.com/jonschlinkert/to-flags
// Copyright (c) 2015, Jon Schlinkert. (MIT)
var isPlainObject = require('../lang/isPlainObject')
var toArg = require('./format-args')
function toFlags (obj, keys) {
if (!isPlainObject(obj)) throw new TypeError('toFlags expects an object')
keys = keys || Object.keys(obj)
return keys.map(function (key) {
return toArg(key, obj[key])
})
}
module.exports = toFlags
|
/*
383 RPL_YOURESERVICE
"You are service <servicename>"
- Sent by the server to a service upon successful
registration.
*/
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Spring, animated } from 'react-spring';
import { TimingAnimation, Easing } from 'react-spring/dist/addons.cjs';
class PulsedStepSelectorButton extends Component {
constructor(props) {
super(props);
this.state = {
pulseOpacity: 1.0,
pulseColor: 'rgba(249, 199, 100, 1)'
};
}
componentDidMount() {
this.pulseInterval = setInterval(() => {
if (this.state.pulseOpacity === 1.0) {
this.setState({ pulseOpacity: 0.8, pulseColor: 'rgba(255,255,255,1)' });
} else {
this.setState({ pulseOpacity: 1.0, pulseColor: 'rgba(249,199,100,1)' });
}
}, this.props.pulseDelay);
}
componentWillUnmount() {
clearInterval(this.pulseInterval);
}
render() {
const { onClick, stepNum, vertical } = this.props;
const { pulseOpacity, pulseColor } = this.state;
let classes = `step-selector-btn-${stepNum}`;
if (vertical) {
classes += ' vertical';
}
const animationDuration = pulseOpacity === 1.0 ? 300 : 600;
return (
<button
className={classes}
onClick={e => {
onClick(stepNum);
}}
>
<Spring
native
to={{
opacity: pulseOpacity,
color: pulseColor,
borderColor: pulseColor
}}
impl={TimingAnimation}
config={{ animationDuration, easing: Easing.linear }}
>
{style => (
<animated.div className="circle" style={{ ...style }}>
{stepNum + 1}
</animated.div>
)}
</Spring>
</button>
);
}
}
PulsedStepSelectorButton.defaultProps = {
pulseDelay: 600,
vertical: false
};
PulsedStepSelectorButton.propTypes = {
onClick: PropTypes.func.isRequired,
stepNum: PropTypes.number.isRequired,
pulseDelay: PropTypes.number,
vertical: PropTypes.bool
};
export default PulsedStepSelectorButton;
|
var _ = require('underscore');
var Netcat = require('node-netcat');
var Readable = require('stream').Readable || require('readable-stream').Readable;
var split = require('split-json');
module.exports = Subscribe;
function Subscribe (port, host, options) {
if (!(this instanceof Subscribe)) return new Subscribe(port, host, options);
Subscribe.init.call(this, port, host, options);
}
Subscribe.init = function (port, host, options) {
// check args
if (_.isObject(host)) {
options = host;
host = 'localhost';
}
this._port = port;
this._host = host || 'localhost';
this._timeout = (options && options.timeout) || 3600000;
this._client = Netcat.client(this._port, this._host, {timeout: this._timeout});
};
Subscribe.prototype.end = function () {
return this._client.send(null, true);
};
Subscribe.prototype.start = function (channel, cb) {
var self = this;
var json = JSON.stringify({channel: channel});
// events callbacks
function open () {
setTimeout(function cb_send_channel () {
self._client.send(json);
}, 500);
}
function error (err) { cb(err); }
function data (data) {
// create a readable stream
var rs = new Readable();
rs.push(data);
rs.push(null);
rs.pipe(split(/\n/)).on('data', function cb_data (data) { cb(null, data); });
}
// events
this._client.on('open', open);
this._client.on('data', data);
this._client.on('error', error);
this._client.start();
};
|
/**
* Main application file
*/
'use strict';
// Set default node environment to development
/* istanbul ignore next */
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var config = require('./config/environment');
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
/* bootstrap Application */
var routes = require('./routes');
routes.init(app);
//Let's get started
server.listen(config.port, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
/* istanbul ignore next */
process.on('uncaughtException', function (error) {
console.error(error.stack);
});
// MONGODB
var mongoose = require('mongoose');
mongoose.connect(config.mongo.uri, config.mongo.options);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('connected to mongo');
});
// SOCKET IO
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
config.ws = io;
module.exports = app;
|
class RequestCache {
constructor() {
this.cache = {};
}
setExpiry = (name, time) => {
this.cache[name].expiry = time;
}
createCache = (name) => {
this.cache[name] = {
expiry: new Date().getHours() + 1
};
}
find = (name, key) => {
let expired = new Date().getHours() + 1;
if(this.cache[name]){
if(this.cache[name][key] && this.cache[name][key].expiresOn < expired) {
return this.cache[name][key].value;
}
}
return false;
}
update = (name, key, value) => {
if(!this.cache[name]){
this.createCache(name);
}
let expiresOn = new Date().getHours() + 1;
this.cache[name][key] = {
value,
expiresOn
};
return this.cache[name][key].value;
}
clear = (name) => {
this.cache[name] = {
expiry: -1
};
}
}
let cacheInstance = new RequestCache();
export default cacheInstance;
|
var nops = require("../lib/nops.js");
var nopt = require("nopt");
var path = require("path");
var knownOpts = {
"source" : path,
"target" : path,
"dumpvars" : Boolean
};
var opts = nopt(knownOpts, {}, process.argv, 2);
nops.exec(opts);
|
// preLoadImages
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preloadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
})(window.jQuery);
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
(function(doc){
var write = doc.write;
doc.write = function(q){
log('document.write(): ',arguments);
if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);
};
})(document);
|
/**
* Created by zhouxin on 2017/9/22.
*/
import iflux, {msg, Store} from 'iflux';
let appStore = Store({
title:""
});
msg.on('cwx-index:query:getBannerList', function () {
appStore.cursor().set('title', "第一个页面");
});
export default appStore;
|
#!/usr/bin/env node
// a test of Node.js stream events
// from node-experiments by Rafał Pocztarski
// See: https://github.com/rsp/node-experiments
// This experiment shows which file events are fired
// with a 'data' event handler.
"use strict";
var fs = require('fs');
var num = 0;
function logEvent(message) {
console.log(++num + '. ' + message);
}
var file = process.argv[2];
if (file === undefined) {
console.log("argument missing");
process.exit(1);
}
console.log(
"file '" + file + "' stream events with 'data' event handler:"
);
var stream = fs.createReadStream(file);
stream.on('open', function () { logEvent('file open'); });
stream.on('end', function () { logEvent('file end'); });
stream.on('close', function () { logEvent('file close'); });
stream.on('data', function () { logEvent('file data'); });
stream.on('readable', function () { logEvent('file readable'); });
stream.on('error', function () { logEvent('file error'); });
|
import PIXI from 'pixi.js';
export default class ShapeEffect {
getParamDefaults() {
return [
{
name: 'color',
label: 'Color',
},
{
name: 'points',
label: 'Shape Points',
}
];
}
render({ params: { color, points } }) {
if (!points || !points.length) {
return false;
}
const colorRaw = parseInt(color.substring(1), 16);
const graphic = new PIXI.Graphics();
graphic.beginFill(colorRaw, 1);
graphic.drawPolygon(points);
graphic.endFill();
return graphic;
}
}
|
import React from 'react'
import IndexLink from 'react-router/lib/IndexLink'
import Link from 'react-router/lib/Link'
import { StyleSheet, css } from 'aphrodite'
const Nav = () => (
<div>
<IndexLink to='/' className={css(styles.link)} activeClassName={css(styles.link, styles.activeLink)}>
Home
</IndexLink>
<Link to='/rebates' className={css(styles.link)} activeClassName={css(styles.link, styles.activeLink)}> Rebates
</Link>
{/*
<a href='https://github.com/jaredpalmer/react-production-starter' className={css(styles.link)} target='_blank'>GitHub</a>
<a href='https://twitter.com/jaredpalmer' className={css(styles.link)} target='_blank'>Twitter</a>
*/}
</div>
)
const styles = StyleSheet.create({
link: {
maxWidth: 1140,
color: '#999',
margin: '1.5rem 1rem 1.5rem 0',
display: 'inline-block',
textDecoration: 'none',
fontWeight: 'bold',
transition: '.2s opacity ease',
':hover': {
opacity: 0.6
}
},
activeLink: {
color: '#fff'
}
})
export default Nav
|
define([
'underscore', 'marionette', 'jquery', 'config',
'moment', './lyt-tile', 'i18n'
],
function(_, Marionette, $, config, Moment, LytTile) {
'use strict';
return Marionette.LayoutView.extend({
template: 'app/base/home/tpl/tpl-home.html',
className: 'home-page ns-full-height',
events: {
'click #nextPage': 'nextPage',
'click #prevPage': 'prevPage',
},
ui: {
'tileContainer': '#tileContainer',
'user': '#user',
'country': '#country',
'siteName': '#siteName',
},
initialize: function() {
this.model = window.app.user;
var locale = config.language;
if(locale == 'fr'){
require(['momentLocale/fr']);
}
},
animateIn: function() {
this.$el.find('#tiles').removeClass('zoomOutDown');
this.$el.find('#tiles').addClass('zoomInDown');
this.$el.find('#tiles').animate(
{opacity: 1},
500,
_.bind(this.trigger, this, 'animateIn')
);
},
// Same as above, except this time we trigger 'animateOut'
animateOut: function() {
this.$el.find('#tiles').removeClass('zoomInUp');
this.$el.animate(
{opacity: 0},
500,
_.bind(this.trigger, this, 'animateOut')
);
},
style: function() {
console.log(window.doNotloadBg);
if(window.doNotloadBg) {
$(this.$el[0]).css('background', 'grey');
} else {
var imgBackHomePage = window.app.siteInfo.get('imgBackHomePage');
$(this.$el[0]).css('background',
'url(data:image/png;base64,' + imgBackHomePage + ') ');
$(this.$el[0]).css({
'background-position': 'center',
'background-attachment': 'fixed',
'background-size': 'cover',
});
}
},
onShow: function(options) {
this.style();
this.ui.country.html(window.app.siteInfo.get('country'));
this.ui.siteName.html(window.app.siteInfo.get('legend'));
this.startTime();
this.displayTiles();
this.$el.i18n();
},
ripple: function() {
var ink;
var d;
var x;
var y;
$('.ripplelink').click(function(e) {
if ($(this).find('.ink').length === 0) {
$(this).prepend('<span class="ink"></span>');
}
ink = $(this).find('.ink');
ink.removeClass('animate');
if (!ink.height() && !ink.width()) {
d = Math.max($(this).outerWidth(), $(this).outerHeight());
ink.css({height: d, width: d});
}
x = e.pageX - $(this).offset().left - ink.width() / 2;
y = e.pageY - $(this).offset().top - ink.height() / 2;
ink.css({top: y + 'px', left: x + 'px'}).addClass('animate');
});
},
startTime: function() {
var locale = config.language;
var dateNow ;
if(locale == 'fr'){
//require(['momentLocale/fr']);
dateNow = new Moment().locale('fr').format('LLLL');
} else {
dateNow = new Moment().format('MMMM Do YYYY, h:mm:ss a').replace(/([rdths]{2})\s2015/,"<sup>\$1</sup> 2015");
}
var _this = this;
this.$el.find('time').html(dateNow);
var t = setTimeout(function() {
_this.startTime();
}, 1000);
},
displayTiles: function() {
var _this = this;
var TileColl = Backbone.Collection.extend({
url: config.coreUrl + '/tiles',
});
this.tileColl = new TileColl();
this.tileColl.url = config.coreUrl + 'instance';
var TileCollView = Backbone.Marionette.CollectionView.extend({
className: 'tiles-wrapper',
childView: LytTile,
_renderChildren: function() {
this.destroyEmptyView();
this.destroyChildren();
if (this.isEmpty(this.collection)) {
this.showEmptyView();
} else {
this.triggerMethod('before:render:collection', this);
this.startBuffering();
this.showCollection();
this.endBuffering();
this.triggerMethod('render:collection', this);
if (!this.children.length) {
this.filter = null;
this.render();
}
// If we have shown children and none have passed the filter, show the empty view
if (this.children.isEmpty()) {
this.showEmptyView();
}
}
},
attachBuffer: function(collectionView) {
if (collectionView.children.length != 0) {
var html = $(this._createBuffer(collectionView));
var page = '';
var perPageTab = _.chunk(html.children(), 10);
collectionView.$el.empty();
for (var i = 0; i < html.children().length; i++) {
if (i % 10 == 0) {
page = '<div class="page clearfix hidden"></div>';
collectionView.$el.append(page);
}
};
collectionView.$el.find('.page').each(function(index) {
$(this).append(perPageTab[index]);
if (index === 0) {
$(this).removeClass('hidden');
}
});
if (collectionView.$el.find('.page').length > 1) {
_this.$el.find('#nextPage').removeClass('hidden');
}else {
_this.$el.find('#nextPage').addClass('hidden');
}
_this.$el.find('#prevPage').addClass('hidden');
}
},
});
this.tileCollView = new TileCollView({
collection: this.tileColl
});
//keyboard events
var timer;
$(document).keydown(function(e) {
var char = String.fromCharCode(e.keyCode || e.charCode);
var code = e.keyCode;
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
_this.tileCollView.filter = function(child, index, collection) {
var tmp = child.get('TIns_Label').toUpperCase();
return tmp.lastIndexOf(char, 0) === 0;
},
_this.tileCollView.render();
clearTimeout(timer);
timer = setTimeout(function() {
_this.tileCollView.filter = null;
_this.tileCollView.render();
}, 2000);
}
return;
});
this.tileColl.fetch({
success: function() {
_this.tileCollView.render();
_this.ui.tileContainer.html(_this.tileCollView.el);
}
});
},
//a bit dirty
nextPage: function() {
var current = this.$el.find('.tiles-wrapper').find('.page:not(.hidden)');
var index = parseInt(current.index());
var nbPage = this.$el.find('.tiles-wrapper').find('.page').length;
if (nbPage !== (index + 1)) {
current.addClass('hidden');
current.next().removeClass('hidden');
if ((current.next().index() + 1) == nbPage) {
this.$el.find('#nextPage').addClass('hidden');
}
this.$el.find('#prevPage').removeClass('hidden');
}
},
prevPage: function() {
var current = this.$el.find('.tiles-wrapper').find('.page:not(.hidden)');
var nbPage = this.$el.find('.tiles-wrapper').find('.page').length;
var index = current.index();
if (index >= 1) {
current.addClass('hidden');
current.prev().removeClass('hidden');
this.$el.find('#nextPage').removeClass('hidden');
if (current.prev().index() == 0) {
this.$el.find('#prevPage').addClass('hidden');
}
}
},
});
});
|
/* */
module.exports = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) return arguments[i];
}
};
|
require.ensure([], function(require) {
require("./2.async.js");
require("./5.async.js");
require("./10.async.js");
require("./20.async.js");
});
module.exports = 21;
|
/**
* Copyright (c) 2015-present, Viro, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ViroCamera
* @flow
*/
'use strict';
import { requireNativeComponent, View, StyleSheet } from 'react-native';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
var createReactClass = require('create-react-class');
import { checkMisnamedProps } from './Utilities/ViroProps';
var ViroCamera = createReactClass({
propTypes: {
...View.propTypes,
position: PropTypes.arrayOf(PropTypes.number),
rotation: PropTypes.arrayOf(PropTypes.number),
active: PropTypes.bool.isRequired,
animation: PropTypes.shape({
name: PropTypes.string,
delay: PropTypes.number,
loop: PropTypes.bool,
onStart: PropTypes.func,
onFinish: PropTypes.func,
run: PropTypes.bool,
interruptible: PropTypes.bool,
}),
fieldOfView: PropTypes.number,
},
componentDidMount() {
this.context.cameraDidMount(this);
},
componentWillUnmount() {
this.context.cameraWillUnmount(this);
},
componentDidUpdate(prevProps, prevState) {
if(prevProps.active != this.props.active) {
this.context.cameraDidUpdate(this, this.props.active);
}
},
setNativeProps: function(nativeProps) {
this._component.setNativeProps(nativeProps);
},
_onAnimationStart: function(event: Event) {
this.props.animation && this.props.animation.onStart && this.props.animation.onStart();
},
_onAnimationFinish: function(event: Event) {
this.props.animation && this.props.animation.onFinish && this.props.animation.onFinish();
},
render: function() {
// Uncomment this to check props
//checkMisnamedProps("ViroCamera", this.props);
return (
<VRTCamera
ref={ component => {this._component = component; }}
{...this.props}
onAnimationStartViro={this._onAnimationStart}
onAnimationFinishViro={this._onAnimationFinish}
/>
);
},
});
ViroCamera.contextTypes = {
cameraDidMount: PropTypes.func,
cameraWillUnmount: PropTypes.func,
cameraDidUpdate: PropTypes.func,
};
var VRTCamera = requireNativeComponent(
'VRTCamera',
ViroCamera, {
nativeOnly: {
scale:[1,1,1],
materials:[],
visible: true,
canHover: true,
canClick: true,
canTouch: true,
canScroll: true,
canSwipe: true,
canDrag: true,
canPinch: true,
canRotate: true,
onPinchViro: true,
onRotateViro: true,
onHoverViro:true,
onClickViro:true,
onTouchViro:true,
onScrollViro:true,
onSwipeViro:true,
onDragViro:true,
transformBehaviors:true,
canFuse: true,
onFuseViro:true,
timeToFuse:true,
viroTag: true,
scalePivot: true,
rotationPivot: true,
canCollide:true,
onCollisionViro:true,
onNativeTransformDelegateViro:true,
hasTransformDelegate:true,
physicsBody:true,
dragType: true,
onAnimationStartViro:true,
onAnimationFinishViro:true,
ignoreEventHandling:true,
dragPlane:true,
renderingOrder:true,
}
});
module.exports = ViroCamera;
|
/**
* A Set datastructure. Note: only stores strings.
*
* NOTE: this class is broken if anyone adds methods to Object.prototype
*
* Examples:
* var set = new Set(["a", "b"]);
* set.contains("b"); // true
* set.add("b"); // does nothing
* set.remove("b");
* set.contains("b"); // false
* set.clear();
* set.add("c");
* set.size(); // 1
* for (var value in set.values) {
* set.contains(value); // true
* }
*/
function Set(items) {
this.clear();
if (items !== undefined) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
}
Set.prototype.list = function() {
var all = [];
for (val in this.values) {
all.push(val);
}
return all;
};
/**
* returns if the item wasn't already in the set.
*/
Set.prototype.add = function(item) {
this._size = undefined;
var old_value = this.values[item];
this.values[item] = item;
return old_value === undefined;
};
Set.prototype.remove = function(item) {
this._size = undefined;
delete this.values[item];
};
Set.prototype.contains = function(item) {
return this.values[item] !== undefined;
};
Set.prototype.size = function() {
if (this._size === undefined) {
this._size = 0;
for (var item in this.values) {
this._size++;
}
}
return this._size;
};
Set.prototype.isEmpty = function() {
// don't need to use size
for (var item in this.values) {
return false;
}
return true;
};
Set.prototype.clear = function() {
this.values = {};
this._size = 0;
};
Set.prototype.equals = function(other) {
if (other.constructor !== Set) {
return false;
}
if (this.size() !== other.size()) {
return false;
}
for (var item in this.values) {
if (!other.contains(item)) {
return false;
}
}
return true;
};
Set.prototype.minus = function(other) {
var result = new Set();
for (var item in this.values) {
if (!other.contains(item)) {
result.add(item);
}
}
return result;
};
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var HashHandler = require("./keyboard/hash_handler").HashHandler;
var AcePopup = require("./autocomplete/popup").AcePopup;
var util = require("./autocomplete/util");
var event = require("./lib/event");
var lang = require("./lib/lang");
var snippetManager = require("./snippets").snippetManager;
var Autocomplete = function() {
this.autoInsert = true;
this.autoSelect = true;
this.keyboardHandler = new HashHandler();
this.keyboardHandler.bindKeys(this.commands);
this.blurListener = this.blurListener.bind(this);
this.changeListener = this.changeListener.bind(this);
this.mousedownListener = this.mousedownListener.bind(this);
this.mousewheelListener = this.mousewheelListener.bind(this);
this.changeTimer = lang.delayedCall(function() {
this.updateCompletions(true);
}.bind(this))
};
(function() {
this.$init = function() {
this.popup = new AcePopup(document.body || document.documentElement);
this.popup.on("click", function(e) {
this.insertMatch();
e.stop();
}.bind(this));
};
this.openPopup = function(editor, prefix, keepPopupPosition) {
if (!this.popup)
this.$init();
this.popup.setData(this.completions.filtered);
var renderer = editor.renderer;
this.popup.setRow(this.autoSelect ? 0 : -1);
if (!keepPopupPosition) {
this.popup.setFontSize(editor.getFontSize());
var lineHeight = renderer.layerConfig.lineHeight;
var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
pos.left -= this.popup.getTextLeftOffset();
var rect = editor.container.getBoundingClientRect();
pos.top += rect.top - renderer.layerConfig.offset;
pos.left += rect.left - editor.renderer.scrollLeft;
pos.left += renderer.$gutterLayer.gutterWidth;
this.popup.show(pos, lineHeight);
}
};
this.detach = function() {
this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
this.editor.off("changeSelection", this.changeListener);
this.editor.off("blur", this.blurListener);
this.editor.off("mousedown", this.mousedownListener);
this.editor.off("mousewheel", this.mousewheelListener);
this.changeTimer.cancel();
if (this.popup)
this.popup.hide();
this.activated = false;
this.completions = this.base = null;
};
this.changeListener = function(e) {
var cursor = this.editor.selection.lead;
if (cursor.row != this.base.row || cursor.column < this.base.column) {
this.detach();
}
if (this.activated)
this.changeTimer.schedule();
else
this.detach();
};
this.blurListener = function() {
if (document.activeElement != this.editor.textInput.getElement())
this.detach();
};
this.mousedownListener = function(e) {
this.detach();
};
this.mousewheelListener = function(e) {
this.detach();
};
this.goTo = function(where) {
var row = this.popup.getRow();
var max = this.popup.session.getLength() - 1;
switch(where) {
case "up": row = row < 0 ? max : row - 1; break;
case "down": row = row >= max ? -1 : row + 1; break;
case "start": row = 0; break;
case "end": row = max; break;
}
this.popup.setRow(row);
};
this.insertMatch = function(data) {
if (!data)
data = this.popup.getData(this.popup.getRow());
if (!data)
return false;
if (data.completer && data.completer.insertMatch) {
data.completer.insertMatch(this.editor);
} else {
if (this.completions.filterText) {
var ranges = this.editor.selection.getAllRanges();
for (var i = 0, range; range = ranges[i]; i++) {
range.start.column -= this.completions.filterText.length;
this.editor.session.remove(range);
}
}
if (data.snippet)
snippetManager.insertSnippet(this.editor, data.snippet);
else
this.editor.execCommand("insertstring", data.value || data);
}
this.detach();
};
this.commands = {
"Up": function(editor) { editor.completer.goTo("up"); },
"Down": function(editor) { editor.completer.goTo("down"); },
"Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
"Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
"Esc": function(editor) { editor.completer.detach(); },
"Space": function(editor) { editor.completer.detach(); editor.insert(" ");},
"Return": function(editor) {
if (editor.completer.popup.getRow() > -1) {
editor.completer.insertMatch();
} else {
editor.insert("\n");
}
},
"Shift-Return": function(editor) { editor.completer.insertMatch(true); },
"Tab": function(editor) { editor.completer.insertMatch(); },
"PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
"PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
};
this.gatherCompletions = function(editor, callback) {
var session = editor.getSession();
var pos = editor.getCursorPosition();
var line = session.getLine(pos.row);
var prefix = util.retrievePrecedingIdentifier(line, pos.column);
this.base = editor.getCursorPosition();
this.base.column -= prefix.length;
var matches = [];
util.parForEach(editor.completers, function(completer, next) {
completer.getCompletions(editor, session, pos, prefix, function(err, results) {
if (!err)
matches = matches.concat(results);
next();
});
}, function() {
callback(null, {
prefix: prefix,
matches: matches
});
});
return true;
};
this.showPopup = function(editor) {
if (this.editor)
this.detach();
this.activated = true;
this.editor = editor;
if (editor.completer != this) {
if (editor.completer)
editor.completer.detach();
editor.completer = this;
}
editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
editor.on("changeSelection", this.changeListener);
editor.on("blur", this.blurListener);
editor.on("mousedown", this.mousedownListener);
editor.on("mousewheel", this.mousewheelListener);
this.updateCompletions();
};
this.updateCompletions = function(keepPopupPosition) {
if (keepPopupPosition && this.base && this.completions) {
var pos = this.editor.getCursorPosition();
var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
if (prefix == this.completions.filterText)
return;
this.completions.setFilter(prefix);
if (!this.completions.filtered.length)
return this.detach();
this.openPopup(this.editor, prefix, keepPopupPosition);
return;
}
this.gatherCompletions(this.editor, function(err, results) {
var matches = results && results.matches;
if (!matches || !matches.length)
return this.detach();
// TODO reenable this when we have proper change tracking
// if (matches.length == 1)
// return this.insertMatch(matches[0]);
this.completions = new FilteredList(matches);
this.completions.setFilter(results.prefix);
var filtered = this.completions.filtered;
if (!filtered.length)
return this.detach();
if (this.autoInsert && filtered.length == 1)
return this.insertMatch(filtered[0]);
this.openPopup(this.editor, results.prefix, keepPopupPosition);
}.bind(this));
};
this.cancelContextMenu = function() {
var stop = function(e) {
this.editor.off("nativecontextmenu", stop);
if (e && e.domEvent)
event.stopEvent(e.domEvent);
}.bind(this);
setTimeout(stop, 10);
this.editor.on("nativecontextmenu", stop);
};
}).call(Autocomplete.prototype);
Autocomplete.startCommand = {
name: "startAutocomplete",
exec: function(editor) {
if (!editor.completer)
editor.completer = new Autocomplete();
editor.completer.showPopup(editor);
// needed for firefox on mac
editor.completer.cancelContextMenu();
},
bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
};
var FilteredList = function(array, filterText, mutateData) {
this.all = array;
this.filtered = array;
this.filterText = filterText || "";
};
(function(){
this.setFilter = function(str) {
if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
var matches = this.filtered;
else
var matches = this.all;
this.filterText = str;
matches = this.filterCompletions(matches, this.filterText);
matches = matches.sort(function(a, b) {
return b.exactMatch - a.exactMatch || b.score - a.score;
});
// make unique
var prev = null;
matches = matches.filter(function(item){
var caption = item.value || item.caption || item.snippet;
if (caption === prev) return false;
prev = caption;
return true;
});
this.filtered = matches;
};
this.filterCompletions = function(items, needle) {
var results = [];
var upper = needle.toUpperCase();
var lower = needle.toLowerCase();
loop: for (var i = 0, item; item = items[i]; i++) {
var caption = item.value || item.caption || item.snippet;
if (!caption) continue;
var lastIndex = -1;
var matchMask = 0;
var penalty = 0;
var index, distance;
// caption char iteration is faster in Chrome but slower in Firefox, so lets use indexOf
for (var j = 0; j < needle.length; j++) {
// TODO add penalty on case mismatch
var i1 = caption.indexOf(lower[j], lastIndex + 1);
var i2 = caption.indexOf(upper[j], lastIndex + 1);
index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
if (index < 0)
continue loop;
distance = index - lastIndex - 1;
if (distance > 0) {
// first char mismatch should be more sensitive
if (lastIndex === -1)
penalty += 10;
penalty += distance;
}
matchMask = matchMask | (1 << index);
lastIndex = index;
}
item.matchMask = matchMask;
item.exactMatch = penalty ? 0 : 1;
item.score = (item.score || 0) - penalty;
results.push(item);
}
return results;
};
}).call(FilteredList.prototype);
exports.Autocomplete = Autocomplete;
exports.FilteredList = FilteredList;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.