/*!
* Copyright (c) Handsoncode sp. z o.o.
*
* This Handsontable Pro is a commercial software distributed by Handsoncode sp. z o. o., a limited liability
* company registered under the laws of Poland, with its registered office in Gdynia, Poland, at 96/98 Aleja Zwycięstwa,
* postal code 81-451, entered into the Entrepreneurs Register of the National Court Register under number 0000538651,
* share capital: PLN 62,800.00., hereinafter referred to as "HANDSONCODE".
*
* By installing, copying, or otherwise using this software, you agree to be bound by the terms
* of its General Software License Terms ("Terms") outlined in a file "handsontable-pro-general-terms.pdf"
* available in the main directory of the software repository.
* This software is copyrighted and protected by copyright laws and international treaties.
*
* You shall obtain a commercial license for this software at handsontable.com.
*
* YOU EXPRESSLY ACKNOWLEDGE AND AGREE THAT USE OF THE SOFTWARE IS AT YOUR OWN RISK AND THAT THE SOFTWARE
* IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES OR CONDITIONS WHATSOEVER. HANDSONCODE EXPRESSLY DISCLAIMS ANY WARRANTY,
* EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. HANDSONCODE DOES NOT WARRANT THAT THE SOFTWARE AND ITS FUNCTIONALITY,
* RELIABILITY AND PERFORMANCE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFTWARE WILL BE
* UNINTERRUPTED OR ERROR FREE.
*
* Version: 1.18.1
* Release date: 20/03/2018 (built at 20/03/2018 10:43:43)
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("Handsontable", [], factory);
else if(typeof exports === 'object')
exports["Handsontable"] = factory();
else
root["Handsontable"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 476);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.to2dArray = to2dArray;
exports.extendArray = extendArray;
exports.pivot = pivot;
exports.arrayReduce = arrayReduce;
exports.arrayFilter = arrayFilter;
exports.arrayMap = arrayMap;
exports.arrayEach = arrayEach;
exports.arraySum = arraySum;
exports.arrayMax = arrayMax;
exports.arrayMin = arrayMin;
exports.arrayAvg = arrayAvg;
exports.arrayFlatten = arrayFlatten;
exports.arrayUnique = arrayUnique;
function to2dArray(arr) {
var i = 0,
ilen = arr.length;
while (i < ilen) {
arr[i] = [arr[i]];
i++;
}
}
function extendArray(arr, extension) {
var i = 0,
ilen = extension.length;
while (i < ilen) {
arr.push(extension[i]);
i++;
}
}
function pivot(arr) {
var pivotedArr = [];
if (!arr || arr.length === 0 || !arr[0] || arr[0].length === 0) {
return pivotedArr;
}
var rowCount = arr.length;
var colCount = arr[0].length;
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
if (!pivotedArr[j]) {
pivotedArr[j] = [];
}
pivotedArr[j][i] = arr[i][j];
}
}
return pivotedArr;
}
/**
* A specialized version of `.reduce` for arrays without support for callback
* shorthands and `this` binding.
*
* {@link https://github.com/lodash/lodash/blob/master/lodash.js}
*
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {Boolean} [initFromArray] Specify using the first element of `array` as the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initFromArray) {
var index = -1;
var iterable = array;
if (!Array.isArray(array)) {
iterable = Array.from(array);
}
var length = iterable.length;
if (initFromArray && length) {
accumulator = iterable[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, iterable[index], index, iterable);
}
return accumulator;
}
/**
* A specialized version of `.filter` for arrays without support for callback
* shorthands and `this` binding.
*
* {@link https://github.com/lodash/lodash/blob/master/lodash.js}
*
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1;
var iterable = array;
if (!Array.isArray(array)) {
iterable = Array.from(array);
}
var length = iterable.length;
var result = [];
var resIndex = -1;
while (++index < length) {
var value = iterable[index];
if (predicate(value, index, iterable)) {
result[++resIndex] = value;
}
}
return result;
}
/**
* A specialized version of `.map` for arrays without support for callback
* shorthands and `this` binding.
*
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayMap(array, iteratee) {
var index = -1;
var iterable = array;
if (!Array.isArray(array)) {
iterable = Array.from(array);
}
var length = iterable.length;
var result = [];
var resIndex = -1;
while (++index < length) {
var value = iterable[index];
result[++resIndex] = iteratee(value, index, iterable);
}
return result;
}
/**
* A specialized version of `.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* {@link https://github.com/lodash/lodash/blob/master/lodash.js}
*
* @param {Array|*} array The array to iterate over or an any element with implemented iterator protocol.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1;
var iterable = array;
if (!Array.isArray(array)) {
iterable = Array.from(array);
}
var length = iterable.length;
while (++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return array;
}
/**
* Calculate sum value for each item of the array.
*
* @param {Array} array The array to process.
* @returns {Number} Returns calculated sum value.
*/
function arraySum(array) {
return arrayReduce(array, function (a, b) {
return a + b;
}, 0);
}
/**
* Returns the highest value from an array. Can be array of numbers or array of strings.
* NOTICE: Mixed values is not supported.
*
* @param {Array} array The array to process.
* @returns {Number} Returns the highest value from an array.
*/
function arrayMax(array) {
return arrayReduce(array, function (a, b) {
return a > b ? a : b;
}, Array.isArray(array) ? array[0] : void 0);
}
/**
* Returns the lowest value from an array. Can be array of numbers or array of strings.
* NOTICE: Mixed values is not supported.
*
* @param {Array} array The array to process.
* @returns {Number} Returns the lowest value from an array.
*/
function arrayMin(array) {
return arrayReduce(array, function (a, b) {
return a < b ? a : b;
}, Array.isArray(array) ? array[0] : void 0);
}
/**
* Calculate average value for each item of the array.
*
* @param {Array} array The array to process.
* @returns {Number} Returns calculated average value.
*/
function arrayAvg(array) {
if (!array.length) {
return 0;
}
return arraySum(array) / array.length;
}
/**
* Flatten multidimensional array.
*
* @param {Array} array Array of Arrays
* @returns {Array}
*/
function arrayFlatten(array) {
return arrayReduce(array, function (initial, value) {
return initial.concat(Array.isArray(value) ? arrayFlatten(value) : value);
}, []);
}
/**
* Unique values in the array.
*
* @param {Array} array The array to process.
* @returns {Array}
*/
function arrayUnique(array) {
var unique = [];
arrayEach(array, function (value) {
if (unique.indexOf(value) === -1) {
unique.push(value);
}
});
return unique;
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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; };
exports.duckSchema = duckSchema;
exports.inherit = inherit;
exports.extend = extend;
exports.deepExtend = deepExtend;
exports.deepClone = deepClone;
exports.clone = clone;
exports.mixin = mixin;
exports.isObjectEqual = isObjectEqual;
exports.isObject = isObject;
exports.defineGetter = defineGetter;
exports.objectEach = objectEach;
exports.getProperty = getProperty;
exports.deepObjectSize = deepObjectSize;
exports.createObjectPropListener = createObjectPropListener;
exports.hasOwnProperty = hasOwnProperty;
var _array = __webpack_require__(0);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Generate schema for passed object.
*
* @param {Array|Object} object
* @returns {Array|Object}
*/
function duckSchema(object) {
var schema;
if (Array.isArray(object)) {
schema = [];
} else {
schema = {};
objectEach(object, function (value, key) {
if (key === '__children') {
return;
}
if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !Array.isArray(value)) {
schema[key] = duckSchema(value);
} else if (Array.isArray(value)) {
if (value.length && _typeof(value[0]) === 'object' && !Array.isArray(value[0])) {
schema[key] = [duckSchema(value[0])];
} else {
schema[key] = [];
}
} else {
schema[key] = null;
}
});
}
return schema;
}
/**
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
* Creates temporary dummy function to call it as constructor.
* Described in ticket: https://github.com/handsontable/handsontable/pull/516
*
* @param {Object} Child child class
* @param {Object} Parent parent class
* @return {Object} extended Child
*/
function inherit(Child, Parent) {
Parent.prototype.constructor = Parent;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
return Child;
}
/**
* Perform shallow extend of a target object with extension's own properties.
*
* @param {Object} target An object that will receive the new properties.
* @param {Object} extension An object containing additional properties to merge into the target.
*/
function extend(target, extension) {
objectEach(extension, function (value, key) {
target[key] = value;
});
return target;
}
/**
* Perform deep extend of a target object with extension's own properties.
*
* @param {Object} target An object that will receive the new properties.
* @param {Object} extension An object containing additional properties to merge into the target.
*/
function deepExtend(target, extension) {
objectEach(extension, function (value, key) {
if (extension[key] && _typeof(extension[key]) === 'object') {
if (!target[key]) {
if (Array.isArray(extension[key])) {
target[key] = [];
} else if (Object.prototype.toString.call(extension[key]) === '[object Date]') {
target[key] = extension[key];
} else {
target[key] = {};
}
}
deepExtend(target[key], extension[key]);
} else {
target[key] = extension[key];
}
});
}
/**
* Perform deep clone of an object.
* WARNING! Only clones JSON properties. Will cause error when `obj` contains a function, Date, etc.
*
* @param {Object} obj An object that will be cloned
* @return {Object}
*/
function deepClone(obj) {
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') {
return JSON.parse(JSON.stringify(obj));
}
return obj;
}
/**
* Shallow clone object.
*
* @param {Object} object
* @returns {Object}
*/
function clone(object) {
var result = {};
objectEach(object, function (value, key) {
result[key] = value;
});
return result;
}
/**
* Extend the Base object (usually prototype) of the functionality the `mixins` objects.
*
* @param {Object} Base Base object which will be extended.
* @param {Object} mixins The object of the functionality will be "copied".
* @returns {Object}
*/
function mixin(Base) {
if (!Base.MIXINS) {
Base.MIXINS = [];
}
for (var _len = arguments.length, mixins = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
mixins[_key - 1] = arguments[_key];
}
(0, _array.arrayEach)(mixins, function (mixin) {
Base.MIXINS.push(mixin.MIXIN_NAME);
objectEach(mixin, function (value, key) {
if (Base.prototype[key] !== void 0) {
throw new Error('Mixin conflict. Property \'' + key + '\' already exist and cannot be overwritten.');
}
if (typeof value === 'function') {
Base.prototype[key] = value;
} else {
var getter = function _getter(propertyName, initialValue) {
propertyName = '_' + propertyName;
var initValue = function initValue(value) {
if (Array.isArray(value) || isObject(value)) {
value = deepClone(value);
}
return value;
};
return function () {
if (this[propertyName] === void 0) {
this[propertyName] = initValue(initialValue);
}
return this[propertyName];
};
};
var setter = function _setter(propertyName) {
propertyName = '_' + propertyName;
return function (value) {
this[propertyName] = value;
};
};
Object.defineProperty(Base.prototype, key, {
get: getter(key, value),
set: setter(key),
configurable: true
});
}
});
});
return Base;
}
/**
* Checks if two objects or arrays are (deep) equal
*
* @param {Object|Array} object1
* @param {Object|Array} object2
* @returns {Boolean}
*/
function isObjectEqual(object1, object2) {
return JSON.stringify(object1) === JSON.stringify(object2);
}
/**
* Determines whether given object is a plain Object.
* Note: String and Array are not plain Objects
* @param {*} obj
* @returns {boolean}
*/
function isObject(obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
}
function defineGetter(object, property, value, options) {
options.value = value;
options.writable = options.writable !== false;
options.enumerable = options.enumerable !== false;
options.configurable = options.configurable !== false;
Object.defineProperty(object, property, options);
}
/**
* A specialized version of `.forEach` for objects.
*
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function objectEach(object, iteratee) {
for (var key in object) {
if (!object.hasOwnProperty || object.hasOwnProperty && Object.prototype.hasOwnProperty.call(object, key)) {
if (iteratee(object[key], key, object) === false) {
break;
}
}
}
return object;
}
/**
* Get object property by its name. Access to sub properties can be achieved by dot notation (e.q. `'foo.bar.baz'`).
*
* @param {Object} object Object which value will be exported.
* @param {String} name Object property name.
* @returns {*}
*/
function getProperty(object, name) {
var names = name.split('.');
var result = object;
objectEach(names, function (name) {
result = result[name];
if (result === void 0) {
result = void 0;
return false;
}
});
return result;
}
/**
* Return object length (recursively).
*
* @param {*} object Object for which we want get length.
* @returns {Number}
*/
function deepObjectSize(object) {
if (!isObject(object)) {
return 0;
}
var recursObjLen = function recursObjLen(obj) {
var result = 0;
if (isObject(obj)) {
objectEach(obj, function (key) {
result += recursObjLen(key);
});
} else {
result++;
}
return result;
};
return recursObjLen(object);
}
/**
* Create object with property where its value change will be observed.
*
* @param {*} [defaultValue=undefined] Default value.
* @param {String} [propertyToListen='value'] Property to listen.
* @returns {Object}
*/
function createObjectPropListener(defaultValue) {
var _holder;
var propertyToListen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'value';
var privateProperty = '_' + propertyToListen;
var holder = (_holder = {
_touched: false
}, _defineProperty(_holder, privateProperty, defaultValue), _defineProperty(_holder, 'isTouched', function isTouched() {
return this._touched;
}), _holder);
Object.defineProperty(holder, propertyToListen, {
get: function get() {
return this[privateProperty];
},
set: function set(value) {
this._touched = true;
this[privateProperty] = value;
},
enumerable: true,
configurable: true
});
return holder;
}
/**
* Check if at specified `key` there is any value for `object`.
*
* @param {Object} object Object to search value at specyfic key.
* @param {String} key String key to check.
*/
function hasOwnProperty(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.HTML_CHARACTERS = undefined;
exports.getParent = getParent;
exports.closest = closest;
exports.closestDown = closestDown;
exports.isChildOf = isChildOf;
exports.isChildOfWebComponentTable = isChildOfWebComponentTable;
exports.polymerWrap = polymerWrap;
exports.polymerUnwrap = polymerUnwrap;
exports.index = index;
exports.overlayContainsElement = overlayContainsElement;
exports.hasClass = hasClass;
exports.addClass = addClass;
exports.removeClass = removeClass;
exports.removeTextNodes = removeTextNodes;
exports.empty = empty;
exports.fastInnerHTML = fastInnerHTML;
exports.fastInnerText = fastInnerText;
exports.isVisible = isVisible;
exports.offset = offset;
exports.getWindowScrollTop = getWindowScrollTop;
exports.getWindowScrollLeft = getWindowScrollLeft;
exports.getScrollTop = getScrollTop;
exports.getScrollLeft = getScrollLeft;
exports.getScrollableElement = getScrollableElement;
exports.getTrimmingContainer = getTrimmingContainer;
exports.getStyle = getStyle;
exports.getComputedStyle = getComputedStyle;
exports.outerWidth = outerWidth;
exports.outerHeight = outerHeight;
exports.innerHeight = innerHeight;
exports.innerWidth = innerWidth;
exports.addEvent = addEvent;
exports.removeEvent = removeEvent;
exports.getCaretPosition = getCaretPosition;
exports.getSelectionEndPosition = getSelectionEndPosition;
exports.getSelectionText = getSelectionText;
exports.setCaretPosition = setCaretPosition;
exports.getScrollbarWidth = getScrollbarWidth;
exports.hasVerticalScrollbar = hasVerticalScrollbar;
exports.hasHorizontalScrollbar = hasHorizontalScrollbar;
exports.setOverlayPosition = setOverlayPosition;
exports.getCssTransform = getCssTransform;
exports.resetCssTransform = resetCssTransform;
exports.isInput = isInput;
exports.isOutsideInput = isOutsideInput;
var _browser = __webpack_require__(33);
var _feature = __webpack_require__(43);
/**
* Get the parent of the specified node in the DOM tree.
*
* @param {HTMLElement} element Element from which traversing is started.
* @param {Number} [level=0] Traversing deep level.
* @return {HTMLElement|null}
*/
function getParent(element) {
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var iteration = -1;
var parent = null;
while (element != null) {
if (iteration === level) {
parent = element;
break;
}
if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
element = element.host;
} else {
iteration++;
element = element.parentNode;
}
}
return parent;
}
/**
* Goes up the DOM tree (including given element) until it finds an element that matches the nodes or nodes name.
* This method goes up through web components.
*
* @param {HTMLElement} element Element from which traversing is started
* @param {Array} nodes Array of elements or Array of elements name
* @param {HTMLElement} [until]
* @returns {HTMLElement|null}
*/
function closest(element, nodes, until) {
while (element != null && element !== until) {
if (element.nodeType === Node.ELEMENT_NODE && (nodes.indexOf(element.nodeName) > -1 || nodes.indexOf(element) > -1)) {
return element;
}
if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
element = element.host;
} else {
element = element.parentNode;
}
}
return null;
}
/**
* Goes "down" the DOM tree (including given element) until it finds an element that matches the nodes or nodes name.
*
* @param {HTMLElement} element Element from which traversing is started
* @param {Array} nodes Array of elements or Array of elements name
* @param {HTMLElement} [until]
* @returns {HTMLElement|null}
*/
function closestDown(element, nodes, until) {
var matched = [];
while (element) {
element = closest(element, nodes, until);
if (!element || until && !until.contains(element)) {
break;
}
matched.push(element);
if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
element = element.host;
} else {
element = element.parentNode;
}
}
var length = matched.length;
return length ? matched[length - 1] : null;
}
/**
* Goes up the DOM tree and checks if element is child of another element.
*
* @param child Child element
* @param {Object|String} parent Parent element OR selector of the parent element.
* If string provided, function returns `true` for the first occurrence of element with that class.
* @returns {Boolean}
*/
function isChildOf(child, parent) {
var node = child.parentNode;
var queriedParents = [];
if (typeof parent === 'string') {
queriedParents = Array.prototype.slice.call(document.querySelectorAll(parent), 0);
} else {
queriedParents.push(parent);
}
while (node != null) {
if (queriedParents.indexOf(node) > -1) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* Check if an element is part of `hot-table` web component.
*
* @param {Element} element
* @returns {Boolean}
*/
function isChildOfWebComponentTable(element) {
var hotTableName = 'hot-table',
result = false,
parentNode;
parentNode = polymerWrap(element);
function isHotTable(element) {
return element.nodeType === Node.ELEMENT_NODE && element.nodeName === hotTableName.toUpperCase();
}
while (parentNode != null) {
if (isHotTable(parentNode)) {
result = true;
break;
} else if (parentNode.host && parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
result = isHotTable(parentNode.host);
if (result) {
break;
}
parentNode = parentNode.host;
}
parentNode = parentNode.parentNode;
}
return result;
}
/**
* Wrap element into polymer/webcomponent container if exists
*
* @param element
* @returns {*}
*/
function polymerWrap(element) {
/* global Polymer */
return typeof Polymer !== 'undefined' && typeof wrap === 'function' ? wrap(element) : element;
}
/**
* Unwrap element from polymer/webcomponent container if exists
*
* @param element
* @returns {*}
*/
function polymerUnwrap(element) {
/* global Polymer */
return typeof Polymer !== 'undefined' && typeof unwrap === 'function' ? unwrap(element) : element;
}
/**
* Counts index of element within its parent
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
* Otherwise would need to check for nodeType or use previousElementSibling
*
* @see http://jsperf.com/sibling-index/10
* @param {Element} element
* @return {Number}
*/
function index(element) {
var i = 0;
if (element.previousSibling) {
/* eslint-disable no-cond-assign */
while (element = element.previousSibling) {
++i;
}
}
return i;
}
/**
* Check if the provided overlay contains the provided element
*
* @param {String} overlay
* @param {HTMLElement} element
* @returns {boolean}
*/
function overlayContainsElement(overlayType, element) {
var overlayElement = document.querySelector('.ht_clone_' + overlayType);
return overlayElement ? overlayElement.contains(element) : null;
}
var classListSupport = !!document.documentElement.classList;
var _hasClass, _addClass, _removeClass;
function filterEmptyClassNames(classNames) {
var len = 0,
result = [];
if (!classNames || !classNames.length) {
return result;
}
while (classNames[len]) {
result.push(classNames[len]);
len++;
}
return result;
}
if (classListSupport) {
var isSupportMultipleClassesArg = function () {
var element = document.createElement('div');
element.classList.add('test', 'test2');
return element.classList.contains('test2');
}();
_hasClass = function _hasClass(element, className) {
if (element.classList === void 0 || className === '') {
return false;
}
return element.classList.contains(className);
};
_addClass = function _addClass(element, className) {
var len = 0;
if (typeof className === 'string') {
className = className.split(' ');
}
className = filterEmptyClassNames(className);
if (isSupportMultipleClassesArg) {
element.classList.add.apply(element.classList, className);
} else {
while (className && className[len]) {
element.classList.add(className[len]);
len++;
}
}
};
_removeClass = function _removeClass(element, className) {
var len = 0;
if (typeof className === 'string') {
className = className.split(' ');
}
className = filterEmptyClassNames(className);
if (isSupportMultipleClassesArg) {
element.classList.remove.apply(element.classList, className);
} else {
while (className && className[len]) {
element.classList.remove(className[len]);
len++;
}
}
};
} else {
var createClassNameRegExp = function createClassNameRegExp(className) {
return new RegExp('(\\s|^)' + className + '(\\s|$)');
};
_hasClass = function _hasClass(element, className) {
// http://snipplr.com/view/3561/addclass-removeclass-hasclass/
return element.className !== void 0 && createClassNameRegExp(className).test(element.className);
};
_addClass = function _addClass(element, className) {
var len = 0,
_className = element.className;
if (typeof className === 'string') {
className = className.split(' ');
}
if (_className === '') {
_className = className.join(' ');
} else {
while (className && className[len]) {
if (!createClassNameRegExp(className[len]).test(_className)) {
_className += ' ' + className[len];
}
len++;
}
}
element.className = _className;
};
_removeClass = function _removeClass(element, className) {
var len = 0,
_className = element.className;
if (typeof className === 'string') {
className = className.split(' ');
}
while (className && className[len]) {
// String.prototype.trim is defined in polyfill.js
_className = _className.replace(createClassNameRegExp(className[len]), ' ').trim();
len++;
}
if (element.className !== _className) {
element.className = _className;
}
};
}
/**
* Checks if element has class name
*
* @param {HTMLElement} element
* @param {String} className Class name to check
* @returns {Boolean}
*/
function hasClass(element, className) {
return _hasClass(element, className);
}
/**
* Add class name to an element
*
* @param {HTMLElement} element
* @param {String|Array} className Class name as string or array of strings
*/
function addClass(element, className) {
return _addClass(element, className);
}
/**
* Remove class name from an element
*
* @param {HTMLElement} element
* @param {String|Array} className Class name as string or array of strings
*/
function removeClass(element, className) {
return _removeClass(element, className);
}
function removeTextNodes(element, parent) {
if (element.nodeType === 3) {
parent.removeChild(element); // bye text nodes!
} else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(element.nodeName) > -1) {
var childs = element.childNodes;
for (var i = childs.length - 1; i >= 0; i--) {
removeTextNodes(childs[i], element);
}
}
}
/**
* Remove childs function
* WARNING - this doesn't unload events and data attached by jQuery
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
*
* @param element
* @returns {void}
*/
//
function empty(element) {
var child;
/* eslint-disable no-cond-assign */
while (child = element.lastChild) {
element.removeChild(child);
}
}
var HTML_CHARACTERS = exports.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
/**
* Insert content into element trying avoid innerHTML method.
* @return {void}
*/
function fastInnerHTML(element, content) {
if (HTML_CHARACTERS.test(content)) {
element.innerHTML = content;
} else {
fastInnerText(element, content);
}
}
/**
* Insert text content into element
* @return {void}
*/
var textContextSupport = !!document.createTextNode('test').textContent;
function fastInnerText(element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
// fast lane - replace existing text node
if (textContextSupport) {
// http://jsperf.com/replace-text-vs-reuse
child.textContent = content;
} else {
// http://jsperf.com/replace-text-vs-reuse
child.data = content;
}
} else {
// slow lane - empty element and insert a text node
empty(element);
element.appendChild(document.createTextNode(content));
}
}
/**
* Returns true if element is attached to the DOM and visible, false otherwise
* @param elem
* @returns {boolean}
*/
function isVisible(elem) {
var next = elem;
while (polymerUnwrap(next) !== document.documentElement) {
// until reached
if (next === null) {
// parent detached from DOM
return false;
} else if (next.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
if (next.host) {
// this is Web Components Shadow DOM
// see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
// according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
if (next.host.impl) {
// Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
return isVisible(next.host.impl);
} else if (next.host) {
// Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
return isVisible(next.host);
}
throw new Error('Lost in Web Components world');
} else {
return false; // this is a node detached from document in IE8
}
} else if (next.style.display === 'none') {
return false;
}
next = next.parentNode;
}
return true;
}
/**
* Returns elements top and left offset relative to the document. Function is not compatible with jQuery offset.
*
* @param {HTMLElement} elem
* @return {Object} Returns object with `top` and `left` props
*/
function offset(elem) {
var offsetLeft, offsetTop, lastElem, docElem, box;
docElem = document.documentElement;
if ((0, _feature.hasCaptionProblem)() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
// fixes problem with Firefox ignoring
in TABLE offset (see also export outerHeight)
// http://jsperf.com/offset-vs-getboundingclientrect/8
box = elem.getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
};
}
offsetLeft = elem.offsetLeft;
offsetTop = elem.offsetTop;
lastElem = elem;
/* eslint-disable no-cond-assign */
while (elem = elem.offsetParent) {
// from my observation, document.body always has scrollLeft/scrollTop == 0
if (elem === document.body) {
break;
}
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
lastElem = elem;
}
// slow - http://jsperf.com/offset-vs-getboundingclientrect/6
if (lastElem && lastElem.style.position === 'fixed') {
// if(lastElem !== document.body) { //faster but does gives false positive in Firefox
offsetLeft += window.pageXOffset || docElem.scrollLeft;
offsetTop += window.pageYOffset || docElem.scrollTop;
}
return {
left: offsetLeft,
top: offsetTop
};
}
/**
* Returns the document's scrollTop property.
*
* @returns {Number}
*/
function getWindowScrollTop() {
var res = window.scrollY;
if (res === void 0) {
// IE8-11
res = document.documentElement.scrollTop;
}
return res;
}
/**
* Returns the document's scrollLeft property.
*
* @returns {Number}
*/
function getWindowScrollLeft() {
var res = window.scrollX;
if (res === void 0) {
// IE8-11
res = document.documentElement.scrollLeft;
}
return res;
}
/**
* Returns the provided element's scrollTop property.
*
* @param element
* @returns {Number}
*/
function getScrollTop(element) {
if (element === window) {
return getWindowScrollTop();
}
return element.scrollTop;
}
/**
* Returns the provided element's scrollLeft property.
*
* @param element
* @returns {Number}
*/
function getScrollLeft(element) {
if (element === window) {
return getWindowScrollLeft();
}
return element.scrollLeft;
}
/**
* Returns a DOM element responsible for scrolling of the provided element.
*
* @param {HTMLElement} element
* @returns {HTMLElement} Element's scrollable parent
*/
function getScrollableElement(element) {
var el = element.parentNode,
props = ['auto', 'scroll'],
overflow,
overflowX,
overflowY,
computedStyle = '',
computedOverflow = '',
computedOverflowY = '',
computedOverflowX = '';
while (el && el.style && document.body !== el) {
overflow = el.style.overflow;
overflowX = el.style.overflowX;
overflowY = el.style.overflowY;
if (overflow == 'scroll' || overflowX == 'scroll' || overflowY == 'scroll') {
return el;
} else if (window.getComputedStyle) {
computedStyle = window.getComputedStyle(el);
computedOverflow = computedStyle.getPropertyValue('overflow');
computedOverflowY = computedStyle.getPropertyValue('overflow-y');
computedOverflowX = computedStyle.getPropertyValue('overflow-x');
if (computedOverflow === 'scroll' || computedOverflowX === 'scroll' || computedOverflowY === 'scroll') {
return el;
}
}
// The '+ 1' after the scrollHeight/scrollWidth is to prevent problems with zoomed out Chrome.
if (el.clientHeight <= el.scrollHeight + 1 && (props.indexOf(overflowY) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowY) !== -1)) {
return el;
}
if (el.clientWidth <= el.scrollWidth + 1 && (props.indexOf(overflowX) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowX) !== -1)) {
return el;
}
el = el.parentNode;
}
return window;
}
/**
* Returns a DOM element responsible for trimming the provided element.
*
* @param {HTMLElement} base Base element
* @returns {HTMLElement} Base element's trimming parent
*/
function getTrimmingContainer(base) {
var el = base.parentNode;
while (el && el.style && document.body !== el) {
if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
return el;
} else if (window.getComputedStyle) {
var computedStyle = window.getComputedStyle(el);
if (computedStyle.getPropertyValue('overflow') !== 'visible' && computedStyle.getPropertyValue('overflow') !== '') {
return el;
}
}
el = el.parentNode;
}
return window;
}
/**
* Returns a style property for the provided element. (Be it an inline or external style).
*
* @param {HTMLElement} element
* @param {String} prop Wanted property
* @returns {String|undefined} Element's style property
*/
function getStyle(element, prop) {
/* eslint-disable */
if (!element) {
return;
} else if (element === window) {
if (prop === 'width') {
return window.innerWidth + 'px';
} else if (prop === 'height') {
return window.innerHeight + 'px';
}
return;
}
var styleProp = element.style[prop],
computedStyle;
if (styleProp !== '' && styleProp !== void 0) {
return styleProp;
} else {
computedStyle = getComputedStyle(element);
if (computedStyle[prop] !== '' && computedStyle[prop] !== void 0) {
return computedStyle[prop];
}
}
}
/**
* Returns a computed style object for the provided element. (Needed if style is declared in external stylesheet).
*
* @param element
* @returns {IEElementStyle|CssStyle} Elements computed style object
*/
function getComputedStyle(element) {
return element.currentStyle || document.defaultView.getComputedStyle(element);
}
/**
* Returns the element's outer width.
*
* @param element
* @returns {number} Element's outer width
*/
function outerWidth(element) {
return element.offsetWidth;
}
/**
* Returns the element's outer height
*
* @param elem
* @returns {number} Element's outer height
*/
function outerHeight(elem) {
if ((0, _feature.hasCaptionProblem)() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
// fixes problem with Firefox ignoring
in TABLE.offsetHeight
// jQuery (1.10.1) still has this unsolved
// may be better to just switch to getBoundingClientRect
// http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
// http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
// http://bugs.jquery.com/ticket/2196
// http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
return elem.offsetHeight + elem.firstChild.offsetHeight;
}
return elem.offsetHeight;
}
/**
* Returns the element's inner height.
*
* @param element
* @returns {number} Element's inner height
*/
function innerHeight(element) {
return element.clientHeight || element.innerHeight;
}
/**
* Returns the element's inner width.
*
* @param element
* @returns {number} Element's inner width
*/
function innerWidth(element) {
return element.clientWidth || element.innerWidth;
}
function addEvent(element, event, callback) {
if (window.addEventListener) {
element.addEventListener(event, callback, false);
} else {
element.attachEvent('on' + event, callback);
}
}
function removeEvent(element, event, callback) {
if (window.removeEventListener) {
element.removeEventListener(event, callback, false);
} else {
element.detachEvent('on' + event, callback);
}
}
/**
* Returns caret position in text input
*
* @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
* @return {Number}
*/
function getCaretPosition(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
// IE8
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
/**
* Returns end of the selection in text input
*
* @return {Number}
*/
function getSelectionEndPosition(el) {
if (el.selectionEnd) {
return el.selectionEnd;
} else if (document.selection) {
// IE8
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange();
return re.text.indexOf(r.text) + r.text.length;
}
return 0;
}
/**
* Returns text under selection.
*
* @returns {String}
*/
function getSelectionText() {
var text = '';
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type !== 'Control') {
text = document.selection.createRange().text;
}
return text;
}
/**
* Sets caret position in text input.
*
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
* @param {Element} element
* @param {Number} pos
* @param {Number} endPos
*/
function setCaretPosition(element, pos, endPos) {
if (endPos === void 0) {
endPos = pos;
}
if (element.setSelectionRange) {
element.focus();
try {
element.setSelectionRange(pos, endPos);
} catch (err) {
var elementParent = element.parentNode;
var parentDisplayValue = elementParent.style.display;
elementParent.style.display = 'block';
element.setSelectionRange(pos, endPos);
elementParent.style.display = parentDisplayValue;
}
} else if (element.createTextRange) {
// IE8
var range = element.createTextRange();
range.collapse(true);
range.moveEnd('character', endPos);
range.moveStart('character', pos);
range.select();
}
}
var cachedScrollbarWidth;
// http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
var inner = document.createElement('div');
inner.style.height = '200px';
inner.style.width = '100%';
var outer = document.createElement('div');
outer.style.boxSizing = 'content-box';
outer.style.height = '150px';
outer.style.left = '0px';
outer.style.overflow = 'hidden';
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.width = '200px';
outer.style.visibility = 'hidden';
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) {
w2 = outer.clientWidth;
}
(document.body || document.documentElement).removeChild(outer);
return w1 - w2;
}
/**
* Returns the computed width of the native browser scroll bar.
*
* @return {Number} width
*/
function getScrollbarWidth() {
if (cachedScrollbarWidth === void 0) {
cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
}
return cachedScrollbarWidth;
}
/**
* Checks if the provided element has a vertical scrollbar.
*
* @param {HTMLElement} element
* @returns {Boolean}
*/
function hasVerticalScrollbar(element) {
return element.offsetWidth !== element.clientWidth;
}
/**
* Checks if the provided element has a vertical scrollbar.
*
* @param {HTMLElement} element
* @returns {Boolean}
*/
function hasHorizontalScrollbar(element) {
return element.offsetHeight !== element.clientHeight;
}
/**
* Sets overlay position depending on it's type and used browser
*/
function setOverlayPosition(overlayElem, left, top) {
if ((0, _browser.isIE8)() || (0, _browser.isIE9)()) {
overlayElem.style.top = top;
overlayElem.style.left = left;
} else if ((0, _browser.isSafari)()) {
overlayElem.style['-webkit-transform'] = 'translate3d(' + left + ',' + top + ',0)';
} else {
overlayElem.style.transform = 'translate3d(' + left + ',' + top + ',0)';
}
}
function getCssTransform(element) {
var transform;
if (element.style.transform && (transform = element.style.transform) !== '') {
return ['transform', transform];
} else if (element.style['-webkit-transform'] && (transform = element.style['-webkit-transform']) !== '') {
return ['-webkit-transform', transform];
}
return -1;
}
function resetCssTransform(element) {
if (element.style.transform && element.style.transform !== '') {
element.style.transform = '';
} else if (element.style['-webkit-transform'] && element.style['-webkit-transform'] !== '') {
element.style['-webkit-transform'] = '';
}
}
/**
* Determines if the given DOM element is an input field.
* Notice: By 'input' we mean input, textarea and select nodes
*
* @param {HTMLElement} element - DOM element
* @returns {Boolean}
*/
function isInput(element) {
var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];
return element && (inputs.indexOf(element.nodeName) > -1 || element.contentEditable === 'true');
}
/**
* Determines if the given DOM element is an input field placed OUTSIDE of HOT.
* Notice: By 'input' we mean input, textarea and select nodes
*
* @param {HTMLElement} element - DOM element
* @returns {Boolean}
*/
function isOutsideInput(element) {
return isInput(element) && element.className.indexOf('handsontableInput') == -1 && element.className.indexOf('copyPaste') == -1;
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
/**
* Constants for parts of translation.
*/
var CONTEXT_MENU_ITEMS_NAMESPACE = exports.CONTEXT_MENU_ITEMS_NAMESPACE = 'ContextMenu:items';
var CONTEXTMENU_ITEMS_ROW_ABOVE = exports.CONTEXTMENU_ITEMS_ROW_ABOVE = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertRowAbove';
var CONTEXTMENU_ITEMS_ROW_BELOW = exports.CONTEXTMENU_ITEMS_ROW_BELOW = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertRowBelow';
var CONTEXTMENU_ITEMS_INSERT_LEFT = exports.CONTEXTMENU_ITEMS_INSERT_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertColumnOnTheLeft';
var CONTEXTMENU_ITEMS_INSERT_RIGHT = exports.CONTEXTMENU_ITEMS_INSERT_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertColumnOnTheRight';
var CONTEXTMENU_ITEMS_REMOVE_ROW = exports.CONTEXTMENU_ITEMS_REMOVE_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeRow';
var CONTEXTMENU_ITEMS_REMOVE_COLUMN = exports.CONTEXTMENU_ITEMS_REMOVE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeColumn';
var CONTEXTMENU_ITEMS_UNDO = exports.CONTEXTMENU_ITEMS_UNDO = CONTEXT_MENU_ITEMS_NAMESPACE + '.undo';
var CONTEXTMENU_ITEMS_REDO = exports.CONTEXTMENU_ITEMS_REDO = CONTEXT_MENU_ITEMS_NAMESPACE + '.redo';
var CONTEXTMENU_ITEMS_READ_ONLY = exports.CONTEXTMENU_ITEMS_READ_ONLY = CONTEXT_MENU_ITEMS_NAMESPACE + '.readOnly';
var CONTEXTMENU_ITEMS_CLEAR_COLUMN = exports.CONTEXTMENU_ITEMS_CLEAR_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.clearColumn';
var CONTEXTMENU_ITEMS_COPY = exports.CONTEXTMENU_ITEMS_COPY = CONTEXT_MENU_ITEMS_NAMESPACE + '.copy';
var CONTEXTMENU_ITEMS_CUT = exports.CONTEXTMENU_ITEMS_CUT = CONTEXT_MENU_ITEMS_NAMESPACE + '.cut';
var CONTEXTMENU_ITEMS_FREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_FREEZE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.freezeColumn';
var CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.unfreezeColumn';
var CONTEXTMENU_ITEMS_MERGE_CELLS = exports.CONTEXTMENU_ITEMS_MERGE_CELLS = CONTEXT_MENU_ITEMS_NAMESPACE + '.mergeCells';
var CONTEXTMENU_ITEMS_UNMERGE_CELLS = exports.CONTEXTMENU_ITEMS_UNMERGE_CELLS = CONTEXT_MENU_ITEMS_NAMESPACE + '.unmergeCells';
var CONTEXTMENU_ITEMS_ADD_COMMENT = exports.CONTEXTMENU_ITEMS_ADD_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.addComment';
var CONTEXTMENU_ITEMS_EDIT_COMMENT = exports.CONTEXTMENU_ITEMS_EDIT_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.editComment';
var CONTEXTMENU_ITEMS_REMOVE_COMMENT = exports.CONTEXTMENU_ITEMS_REMOVE_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeComment';
var CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = exports.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.readOnlyComment';
var CONTEXTMENU_ITEMS_ALIGNMENT = exports.CONTEXTMENU_ITEMS_ALIGNMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align';
var CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = exports.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.left';
var CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = exports.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.center';
var CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = exports.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.right';
var CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = exports.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.justify';
var CONTEXTMENU_ITEMS_ALIGNMENT_TOP = exports.CONTEXTMENU_ITEMS_ALIGNMENT_TOP = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.top';
var CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = exports.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.middle';
var CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = exports.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.bottom';
var CONTEXTMENU_ITEMS_BORDERS = exports.CONTEXTMENU_ITEMS_BORDERS = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders';
var CONTEXTMENU_ITEMS_BORDERS_TOP = exports.CONTEXTMENU_ITEMS_BORDERS_TOP = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.top';
var CONTEXTMENU_ITEMS_BORDERS_RIGHT = exports.CONTEXTMENU_ITEMS_BORDERS_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.right';
var CONTEXTMENU_ITEMS_BORDERS_BOTTOM = exports.CONTEXTMENU_ITEMS_BORDERS_BOTTOM = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.bottom';
var CONTEXTMENU_ITEMS_BORDERS_LEFT = exports.CONTEXTMENU_ITEMS_BORDERS_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.left';
var CONTEXTMENU_ITEMS_REMOVE_BORDERS = exports.CONTEXTMENU_ITEMS_REMOVE_BORDERS = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.remove';
var CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = CONTEXT_MENU_ITEMS_NAMESPACE + '.nestedHeaders.insertChildRow';
var CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = CONTEXT_MENU_ITEMS_NAMESPACE + '.nestedHeaders.detachFromParent';
var CONTEXTMENU_ITEMS_HIDE_COLUMN = exports.CONTEXTMENU_ITEMS_HIDE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.hideColumn';
var CONTEXTMENU_ITEMS_SHOW_COLUMN = exports.CONTEXTMENU_ITEMS_SHOW_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.showColumn';
var CONTEXTMENU_ITEMS_HIDE_ROW = exports.CONTEXTMENU_ITEMS_HIDE_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.hideRow';
var CONTEXTMENU_ITEMS_SHOW_ROW = exports.CONTEXTMENU_ITEMS_SHOW_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.showRow';
var FILTERS_NAMESPACE = exports.FILTERS_NAMESPACE = 'Filters:';
var FILTERS_CONDITIONS_NAMESPACE = exports.FILTERS_CONDITIONS_NAMESPACE = FILTERS_NAMESPACE + 'conditions';
var FILTERS_CONDITIONS_NONE = exports.FILTERS_CONDITIONS_NONE = FILTERS_CONDITIONS_NAMESPACE + '.none';
var FILTERS_CONDITIONS_EMPTY = exports.FILTERS_CONDITIONS_EMPTY = FILTERS_CONDITIONS_NAMESPACE + '.isEmpty';
var FILTERS_CONDITIONS_NOT_EMPTY = exports.FILTERS_CONDITIONS_NOT_EMPTY = FILTERS_CONDITIONS_NAMESPACE + '.isNotEmpty';
var FILTERS_CONDITIONS_EQUAL = exports.FILTERS_CONDITIONS_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.isEqualTo';
var FILTERS_CONDITIONS_NOT_EQUAL = exports.FILTERS_CONDITIONS_NOT_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.isNotEqualTo';
var FILTERS_CONDITIONS_BEGINS_WITH = exports.FILTERS_CONDITIONS_BEGINS_WITH = FILTERS_CONDITIONS_NAMESPACE + '.beginsWith';
var FILTERS_CONDITIONS_ENDS_WITH = exports.FILTERS_CONDITIONS_ENDS_WITH = FILTERS_CONDITIONS_NAMESPACE + '.endsWith';
var FILTERS_CONDITIONS_CONTAINS = exports.FILTERS_CONDITIONS_CONTAINS = FILTERS_CONDITIONS_NAMESPACE + '.contains';
var FILTERS_CONDITIONS_NOT_CONTAIN = exports.FILTERS_CONDITIONS_NOT_CONTAIN = FILTERS_CONDITIONS_NAMESPACE + '.doesNotContain';
var FILTERS_CONDITIONS_BY_VALUE = exports.FILTERS_CONDITIONS_BY_VALUE = FILTERS_CONDITIONS_NAMESPACE + '.byValue';
var FILTERS_CONDITIONS_GREATER_THAN = exports.FILTERS_CONDITIONS_GREATER_THAN = FILTERS_CONDITIONS_NAMESPACE + '.greaterThan';
var FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.greaterThanOrEqualTo';
var FILTERS_CONDITIONS_LESS_THAN = exports.FILTERS_CONDITIONS_LESS_THAN = FILTERS_CONDITIONS_NAMESPACE + '.lessThan';
var FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.lessThanOrEqualTo';
var FILTERS_CONDITIONS_BETWEEN = exports.FILTERS_CONDITIONS_BETWEEN = FILTERS_CONDITIONS_NAMESPACE + '.isBetween';
var FILTERS_CONDITIONS_NOT_BETWEEN = exports.FILTERS_CONDITIONS_NOT_BETWEEN = FILTERS_CONDITIONS_NAMESPACE + '.isNotBetween';
var FILTERS_CONDITIONS_AFTER = exports.FILTERS_CONDITIONS_AFTER = FILTERS_CONDITIONS_NAMESPACE + '.after';
var FILTERS_CONDITIONS_BEFORE = exports.FILTERS_CONDITIONS_BEFORE = FILTERS_CONDITIONS_NAMESPACE + '.before';
var FILTERS_CONDITIONS_TODAY = exports.FILTERS_CONDITIONS_TODAY = FILTERS_CONDITIONS_NAMESPACE + '.today';
var FILTERS_CONDITIONS_TOMORROW = exports.FILTERS_CONDITIONS_TOMORROW = FILTERS_CONDITIONS_NAMESPACE + '.tomorrow';
var FILTERS_CONDITIONS_YESTERDAY = exports.FILTERS_CONDITIONS_YESTERDAY = FILTERS_CONDITIONS_NAMESPACE + '.yesterday';
var FILTERS_DIVS_FILTER_BY_CONDITION = exports.FILTERS_DIVS_FILTER_BY_CONDITION = FILTERS_NAMESPACE + 'labels.filterByCondition';
var FILTERS_DIVS_FILTER_BY_VALUE = exports.FILTERS_DIVS_FILTER_BY_VALUE = FILTERS_NAMESPACE + 'labels.filterByValue';
var FILTERS_LABELS_CONJUNCTION = exports.FILTERS_LABELS_CONJUNCTION = FILTERS_NAMESPACE + 'labels.conjunction';
var FILTERS_LABELS_DISJUNCTION = exports.FILTERS_LABELS_DISJUNCTION = FILTERS_NAMESPACE + 'labels.disjunction';
var FILTERS_VALUES_BLANK_CELLS = exports.FILTERS_VALUES_BLANK_CELLS = FILTERS_NAMESPACE + 'values.blankCells';
var FILTERS_BUTTONS_SELECT_ALL = exports.FILTERS_BUTTONS_SELECT_ALL = FILTERS_NAMESPACE + 'buttons.selectAll';
var FILTERS_BUTTONS_CLEAR = exports.FILTERS_BUTTONS_CLEAR = FILTERS_NAMESPACE + 'buttons.clear';
var FILTERS_BUTTONS_OK = exports.FILTERS_BUTTONS_OK = FILTERS_NAMESPACE + 'buttons.ok';
var FILTERS_BUTTONS_CANCEL = exports.FILTERS_BUTTONS_CANCEL = FILTERS_NAMESPACE + 'buttons.cancel';
var FILTERS_BUTTONS_PLACEHOLDER_SEARCH = exports.FILTERS_BUTTONS_PLACEHOLDER_SEARCH = FILTERS_NAMESPACE + 'buttons.placeholder.search';
var FILTERS_BUTTONS_PLACEHOLDER_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_VALUE = FILTERS_NAMESPACE + 'buttons.placeholder.value';
var FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = FILTERS_NAMESPACE + 'buttons.placeholder.secondValue';
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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; };
exports.isNumeric = isNumeric;
exports.rangeEach = rangeEach;
exports.rangeEachReverse = rangeEachReverse;
exports.valueAccordingPercent = valueAccordingPercent;
/**
* Checks if value of n is a numeric one
* http://jsperf.com/isnan-vs-isnumeric/4
* @param n
* @returns {boolean}
*/
function isNumeric(n) {
/* eslint-disable */
var t = typeof n === 'undefined' ? 'undefined' : _typeof(n);
return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == 'number' && !(n instanceof Date) : false;
}
/**
* A specialized version of `.forEach` defined by ranges.
*
* @param {Number} rangeFrom The number from start iterate.
* @param {Number|Function} rangeTo The number where finish iterate or function as a iteratee.
* @param {Function} [iteratee] The function invoked per iteration.
*/
function rangeEach(rangeFrom, rangeTo, iteratee) {
var index = -1;
if (typeof rangeTo === 'function') {
iteratee = rangeTo;
rangeTo = rangeFrom;
} else {
index = rangeFrom - 1;
}
while (++index <= rangeTo) {
if (iteratee(index) === false) {
break;
}
}
}
/**
* A specialized version of `.forEach` defined by ranges iterable in reverse order.
*
* @param {Number} rangeFrom The number from start iterate.
* @param {Number} rangeTo The number where finish iterate.
* @param {Function} iteratee The function invoked per iteration.
*/
function rangeEachReverse(rangeFrom, rangeTo, iteratee) {
var index = rangeFrom + 1;
if (typeof rangeTo === 'function') {
iteratee = rangeTo;
rangeTo = 0;
}
while (--index >= rangeTo) {
if (iteratee(index) === false) {
break;
}
}
}
/**
* Calculate value from percent.
*
* @param {Number} value Base value from percent will be calculated.
* @param {String|Number} percent Can be Number or String (eq. `'33%'`).
* @returns {Number}
*/
function valueAccordingPercent(value, percent) {
percent = parseInt(percent.toString().replace('%', ''), 10);
percent = parseInt(value * percent / 100, 10);
return percent;
}
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(17);
var core = __webpack_require__(50);
var hide = __webpack_require__(39);
var redefine = __webpack_require__(38);
var ctx = __webpack_require__(40);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getPluginName = exports.getRegistredPluginNames = exports.getPlugin = exports.registerPlugin = undefined;
var _pluginHooks = __webpack_require__(14);
var _pluginHooks2 = _interopRequireDefault(_pluginHooks);
var _object = __webpack_require__(1);
var _string = __webpack_require__(31);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var registeredPlugins = new WeakMap();
/**
* Registers plugin under given name
*
* @param {String} pluginName
* @param {Function} PluginClass
*/
/**
* Utility to register plugins and common namespace for keeping reference to all plugins classes
*/
function registerPlugin(pluginName, PluginClass) {
pluginName = (0, _string.toUpperCaseFirst)(pluginName);
_pluginHooks2.default.getSingleton().add('construct', function () {
var holder = void 0;
if (!registeredPlugins.has(this)) {
registeredPlugins.set(this, {});
}
holder = registeredPlugins.get(this);
if (!holder[pluginName]) {
holder[pluginName] = new PluginClass(this);
}
});
_pluginHooks2.default.getSingleton().add('afterDestroy', function () {
if (registeredPlugins.has(this)) {
var pluginsHolder = registeredPlugins.get(this);
(0, _object.objectEach)(pluginsHolder, function (plugin) {
return plugin.destroy();
});
registeredPlugins.delete(this);
}
});
}
/**
* @param {Object} instance
* @param {String|Function} pluginName
* @returns {Function} pluginClass Returns plugin instance if exists or `undefined` if not exists.
*/
function getPlugin(instance, pluginName) {
if (typeof pluginName != 'string') {
throw Error('Only strings can be passed as "plugin" parameter');
}
var _pluginName = (0, _string.toUpperCaseFirst)(pluginName);
if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[_pluginName]) {
return void 0;
}
return registeredPlugins.get(instance)[_pluginName];
}
/**
* Get all registred plugins names for concrete Handsontable instance.
*
* @param {Object} hotInstance
* @returns {Array}
*/
function getRegistredPluginNames(hotInstance) {
return registeredPlugins.has(hotInstance) ? Object.keys(registeredPlugins.get(hotInstance)) : [];
}
/**
* Get plugin name.
*
* @param {Object} hotInstance
* @param {Object} plugin
* @returns {String|null}
*/
function getPluginName(hotInstance, plugin) {
var pluginName = null;
if (registeredPlugins.has(hotInstance)) {
(0, _object.objectEach)(registeredPlugins.get(hotInstance), function (pluginInstance, name) {
if (pluginInstance === plugin) {
pluginName = name;
}
});
}
return pluginName;
}
exports.registerPlugin = registerPlugin;
exports.getPlugin = getPlugin;
exports.getRegistredPluginNames = getRegistredPluginNames;
exports.getPluginName = getPluginName;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _object = __webpack_require__(1);
var _array = __webpack_require__(0);
var _recordTranslator = __webpack_require__(53);
var _plugins = __webpack_require__(6);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var privatePool = new WeakMap();
var initializedPlugins = null;
/**
* @private
*/
var BasePlugin = function () {
/**
* @param {Object} hotInstance Handsontable instance.
*/
function BasePlugin(hotInstance) {
var _this = this;
_classCallCheck(this, BasePlugin);
/**
* Handsontable instance.
*
* @type {Core}
*/
(0, _object.defineGetter)(this, 'hot', hotInstance, {
writable: false
});
(0, _object.defineGetter)(this, 't', (0, _recordTranslator.getTranslator)(hotInstance), {
writable: false
});
privatePool.set(this, { hooks: {} });
initializedPlugins = null;
this.pluginName = null;
this.pluginsInitializedCallbacks = [];
this.isPluginsReady = false;
this.enabled = false;
this.initialized = false;
this.hot.addHook('afterPluginsInitialized', function () {
return _this.onAfterPluginsInitialized();
});
this.hot.addHook('afterUpdateSettings', function () {
return _this.onUpdateSettings();
});
this.hot.addHook('beforeInit', function () {
return _this.init();
});
}
_createClass(BasePlugin, [{
key: 'init',
value: function init() {
this.pluginName = (0, _plugins.getPluginName)(this.hot, this);
if (this.isEnabled && this.isEnabled()) {
this.enablePlugin();
}
if (!initializedPlugins) {
initializedPlugins = (0, _plugins.getRegistredPluginNames)(this.hot);
}
if (initializedPlugins.indexOf(this.pluginName) >= 0) {
initializedPlugins.splice(initializedPlugins.indexOf(this.pluginName), 1);
}
if (!initializedPlugins.length) {
this.hot.runHooks('afterPluginsInitialized');
}
this.initialized = true;
}
/**
* Enable plugin for this Handsontable instance.
*/
}, {
key: 'enablePlugin',
value: function enablePlugin() {
this.enabled = true;
}
/**
* Disable plugin for this Handsontable instance.
*/
}, {
key: 'disablePlugin',
value: function disablePlugin() {
if (this.eventManager) {
this.eventManager.clear();
}
this.clearHooks();
this.enabled = false;
}
/**
* Add listener to plugin hooks system.
*
* @param {String} name
* @param {Function} callback
*/
}, {
key: 'addHook',
value: function addHook(name, callback) {
privatePool.get(this).hooks[name] = privatePool.get(this).hooks[name] || [];
var hooks = privatePool.get(this).hooks[name];
this.hot.addHook(name, callback);
hooks.push(callback);
privatePool.get(this).hooks[name] = hooks;
}
/**
* Remove all hooks listeners by hook name.
*
* @param {String} name
*/
}, {
key: 'removeHooks',
value: function removeHooks(name) {
var _this2 = this;
(0, _array.arrayEach)(privatePool.get(this).hooks[name] || [], function (callback) {
_this2.hot.removeHook(name, callback);
});
}
/**
* Clear all hooks.
*/
}, {
key: 'clearHooks',
value: function clearHooks() {
var _this3 = this;
var hooks = privatePool.get(this).hooks;
(0, _object.objectEach)(hooks, function (callbacks, name) {
return _this3.removeHooks(name);
});
hooks.length = 0;
}
/**
* Register function which will be immediately called after all plugins initialized.
*
* @param {Function} callback
*/
}, {
key: 'callOnPluginsReady',
value: function callOnPluginsReady(callback) {
if (this.isPluginsReady) {
callback();
} else {
this.pluginsInitializedCallbacks.push(callback);
}
}
/**
* On after plugins initialized listener.
*
* @private
*/
}, {
key: 'onAfterPluginsInitialized',
value: function onAfterPluginsInitialized() {
(0, _array.arrayEach)(this.pluginsInitializedCallbacks, function (callback) {
return callback();
});
this.pluginsInitializedCallbacks.length = 0;
this.isPluginsReady = true;
}
/**
* On update settings listener.
*
* @private
*/
}, {
key: 'onUpdateSettings',
value: function onUpdateSettings() {
if (this.isEnabled) {
if (this.enabled && !this.isEnabled()) {
this.disablePlugin();
}
if (!this.enabled && this.isEnabled()) {
this.enablePlugin();
}
if (this.enabled && this.isEnabled()) {
this.updatePlugin();
}
}
}
/**
* Updates the plugin to use the latest options you have specified.
*
* @private
*/
}, {
key: 'updatePlugin',
value: function updatePlugin() {}
/**
* Destroy plugin.
*/
}, {
key: 'destroy',
value: function destroy() {
var _this4 = this;
if (this.eventManager) {
this.eventManager.destroy();
}
this.clearHooks();
(0, _object.objectEach)(this, function (value, property) {
if (property !== 'hot' && property !== 't') {
_this4[property] = null;
}
});
delete this.t;
delete this.hot;
}
}]);
return BasePlugin;
}();
exports.default = BasePlugin;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.Viewport = exports.TableRenderer = exports.Table = exports.Settings = exports.Selection = exports.Scroll = exports.Overlays = exports.Event = exports.Core = exports.default = exports.Border = exports.TopLeftCornerOverlay = exports.TopOverlay = exports.LeftOverlay = exports.DebugOverlay = exports.RowFilter = exports.ColumnFilter = exports.CellRange = exports.CellCoords = exports.ViewportRowsCalculator = exports.ViewportColumnsCalculator = undefined;
__webpack_require__(84);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
__webpack_require__(96);
__webpack_require__(98);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(102);
__webpack_require__(103);
__webpack_require__(104);
__webpack_require__(105);
__webpack_require__(106);
__webpack_require__(107);
__webpack_require__(108);
__webpack_require__(109);
__webpack_require__(110);
__webpack_require__(111);
__webpack_require__(112);
__webpack_require__(113);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(123);
__webpack_require__(124);
__webpack_require__(125);
__webpack_require__(126);
__webpack_require__(127);
__webpack_require__(128);
__webpack_require__(130);
__webpack_require__(131);
__webpack_require__(132);
__webpack_require__(133);
__webpack_require__(134);
__webpack_require__(80);
__webpack_require__(135);
__webpack_require__(136);
__webpack_require__(137);
__webpack_require__(138);
__webpack_require__(139);
__webpack_require__(140);
__webpack_require__(141);
__webpack_require__(142);
__webpack_require__(143);
__webpack_require__(144);
__webpack_require__(145);
__webpack_require__(146);
__webpack_require__(147);
__webpack_require__(148);
__webpack_require__(149);
var _viewportColumns = __webpack_require__(189);
var _viewportColumns2 = _interopRequireDefault(_viewportColumns);
var _viewportRows = __webpack_require__(190);
var _viewportRows2 = _interopRequireDefault(_viewportRows);
var _coords = __webpack_require__(61);
var _coords2 = _interopRequireDefault(_coords);
var _range = __webpack_require__(150);
var _range2 = _interopRequireDefault(_range);
var _column = __webpack_require__(191);
var _column2 = _interopRequireDefault(_column);
var _row = __webpack_require__(192);
var _row2 = _interopRequireDefault(_row);
var _debug = __webpack_require__(499);
var _debug2 = _interopRequireDefault(_debug);
var _left = __webpack_require__(501);
var _left2 = _interopRequireDefault(_left);
var _top = __webpack_require__(502);
var _top2 = _interopRequireDefault(_top);
var _topLeftCorner = __webpack_require__(503);
var _topLeftCorner2 = _interopRequireDefault(_topLeftCorner);
var _border = __webpack_require__(321);
var _border2 = _interopRequireDefault(_border);
var _core = __webpack_require__(193);
var _core2 = _interopRequireDefault(_core);
var _event = __webpack_require__(314);
var _event2 = _interopRequireDefault(_event);
var _overlays = __webpack_require__(315);
var _overlays2 = _interopRequireDefault(_overlays);
var _scroll = __webpack_require__(316);
var _scroll2 = _interopRequireDefault(_scroll);
var _selection = __webpack_require__(504);
var _selection2 = _interopRequireDefault(_selection);
var _settings = __webpack_require__(317);
var _settings2 = _interopRequireDefault(_settings);
var _table = __webpack_require__(318);
var _table2 = _interopRequireDefault(_table);
var _tableRenderer = __webpack_require__(319);
var _tableRenderer2 = _interopRequireDefault(_tableRenderer);
var _viewport = __webpack_require__(320);
var _viewport2 = _interopRequireDefault(_viewport);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.ViewportColumnsCalculator = _viewportColumns2.default;
exports.ViewportRowsCalculator = _viewportRows2.default;
exports.CellCoords = _coords2.default;
exports.CellRange = _range2.default;
exports.ColumnFilter = _column2.default;
exports.RowFilter = _row2.default;
exports.DebugOverlay = _debug2.default;
exports.LeftOverlay = _left2.default;
exports.TopOverlay = _top2.default;
exports.TopLeftCornerOverlay = _topLeftCorner2.default;
exports.Border = _border2.default;
exports.default = _core2.default;
exports.Core = _core2.default;
exports.Event = _event2.default;
exports.Overlays = _overlays2.default;
exports.Scroll = _scroll2.default;
exports.Selection = _selection2.default;
exports.Settings = _settings2.default;
exports.Table = _table2.default;
exports.TableRenderer = _tableRenderer2.default;
exports.Viewport = _viewport2.default;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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; }; }();
exports.getListenersCounter = getListenersCounter;
var _element = __webpack_require__(2);
var _object = __webpack_require__(1);
var _feature = __webpack_require__(43);
var _event = __webpack_require__(11);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Counter which tracks unregistered listeners (useful for detecting memory leaks).
*
* @type {Number}
*/
var listenersCounter = 0;
/**
* Event DOM manager for internal use in Handsontable.
*
* @class EventManager
* @util
*/
var EventManager = function () {
/**
* @param {Object} [context=null]
* @private
*/
function EventManager() {
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
_classCallCheck(this, EventManager);
this.context = context || this;
if (!this.context.eventListeners) {
this.context.eventListeners = [];
}
}
/**
* Register specified listener (`eventName`) to the element.
*
* @param {Element} element Target element.
* @param {String} eventName Event name.
* @param {Function} callback Function which will be called after event occur.
* @returns {Function} Returns function which you can easily call to remove that event
*/
_createClass(EventManager, [{
key: 'addEventListener',
value: function addEventListener(element, eventName, callback) {
var _this = this;
var context = this.context;
function callbackProxy(event) {
event = extendEvent(context, event);
callback.call(this, event);
}
this.context.eventListeners.push({
element: element,
event: eventName,
callback: callback,
callbackProxy: callbackProxy
});
if (window.addEventListener) {
element.addEventListener(eventName, callbackProxy, false);
} else {
element.attachEvent('on' + eventName, callbackProxy);
}
listenersCounter++;
return function () {
_this.removeEventListener(element, eventName, callback);
};
}
/**
* Remove the event listener previously registered.
*
* @param {Element} element Target element.
* @param {String} eventName Event name.
* @param {Function} callback Function to remove from the event target. It must be the same as during registration listener.
*/
}, {
key: 'removeEventListener',
value: function removeEventListener(element, eventName, callback) {
var len = this.context.eventListeners.length;
var tmpEvent = void 0;
while (len--) {
tmpEvent = this.context.eventListeners[len];
if (tmpEvent.event == eventName && tmpEvent.element == element) {
if (callback && callback != tmpEvent.callback) {
/* eslint-disable no-continue */
continue;
}
this.context.eventListeners.splice(len, 1);
if (tmpEvent.element.removeEventListener) {
tmpEvent.element.removeEventListener(tmpEvent.event, tmpEvent.callbackProxy, false);
} else {
tmpEvent.element.detachEvent('on' + tmpEvent.event, tmpEvent.callbackProxy);
}
listenersCounter--;
}
}
}
/**
* Clear all previously registered events.
*
* @private
* @since 0.15.0-beta3
*/
}, {
key: 'clearEvents',
value: function clearEvents() {
if (!this.context) {
return;
}
var len = this.context.eventListeners.length;
while (len--) {
var event = this.context.eventListeners[len];
if (event) {
this.removeEventListener(event.element, event.event, event.callback);
}
}
}
/**
* Clear all previously registered events.
*/
}, {
key: 'clear',
value: function clear() {
this.clearEvents();
}
/**
* Destroy instance of EventManager.
*/
}, {
key: 'destroy',
value: function destroy() {
this.clearEvents();
this.context = null;
}
/**
* Trigger event at the specified target element.
*
* @param {Element} element Target element.
* @param {String} eventName Event name.
*/
}, {
key: 'fireEvent',
value: function fireEvent(element, eventName) {
var options = {
bubbles: true,
cancelable: eventName !== 'mousemove',
view: window,
detail: 0,
screenX: 0,
screenY: 0,
clientX: 1,
clientY: 1,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: undefined
};
var event;
if (document.createEvent) {
event = document.createEvent('MouseEvents');
event.initMouseEvent(eventName, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || document.body.parentNode);
} else {
event = document.createEventObject();
}
if (element.dispatchEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent('on' + eventName, event);
}
}
}]);
return EventManager;
}();
/**
* @param {Object} context
* @param {Event} event
* @private
* @returns {*}
*/
function extendEvent(context, event) {
var componentName = 'HOT-TABLE';
var isHotTableSpotted = void 0;
var fromElement = void 0;
var realTarget = void 0;
var target = void 0;
var len = void 0;
var nativeStopImmediatePropagation = void 0;
event.isTargetWebComponent = false;
event.realTarget = event.target;
nativeStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function () {
nativeStopImmediatePropagation.apply(this);
(0, _event.stopImmediatePropagation)(this);
};
if (!EventManager.isHotTableEnv) {
return event;
}
event = (0, _element.polymerWrap)(event);
len = event.path ? event.path.length : 0;
while (len--) {
if (event.path[len].nodeName === componentName) {
isHotTableSpotted = true;
} else if (isHotTableSpotted && event.path[len].shadowRoot) {
target = event.path[len];
break;
}
if (len === 0 && !target) {
target = event.path[len];
}
}
if (!target) {
target = event.target;
}
event.isTargetWebComponent = true;
if ((0, _feature.isWebComponentSupportedNatively)()) {
event.realTarget = event.srcElement || event.toElement;
} else if ((0, _object.hasOwnProperty)(context, 'hot') || context.isHotTableEnv || context.wtTable) {
// Polymer doesn't support `event.target` property properly we must emulate it ourselves
if ((0, _object.hasOwnProperty)(context, 'hot')) {
// Custom element
fromElement = context.hot ? context.hot.view.wt.wtTable.TABLE : null;
} else if (context.isHotTableEnv) {
// Handsontable.Core
fromElement = context.view.activeWt.wtTable.TABLE.parentNode.parentNode;
} else if (context.wtTable) {
// Walkontable
fromElement = context.wtTable.TABLE.parentNode.parentNode;
}
realTarget = (0, _element.closest)(event.target, [componentName], fromElement);
if (realTarget) {
event.realTarget = fromElement.querySelector(componentName) || event.target;
} else {
event.realTarget = event.target;
}
}
Object.defineProperty(event, 'target', {
get: function get() {
return (0, _element.polymerWrap)(target);
},
enumerable: true,
configurable: true
});
return event;
}
exports.default = EventManager;
function getListenersCounter() {
return listenersCounter;
};
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getCondition = getCondition;
exports.getConditionDescriptor = getConditionDescriptor;
exports.registerCondition = registerCondition;
var conditions = exports.conditions = {};
/**
* Get condition closure with pre-bound arguments.
*
* @param {String} name Condition name.
* @param {Array} args Condition arguments.
* @returns {Function}
*/
function getCondition(name, args) {
if (!conditions[name]) {
throw Error("Filter condition \"" + name + "\" does not exist.");
}
var _conditions$name = conditions[name],
condition = _conditions$name.condition,
descriptor = _conditions$name.descriptor;
if (descriptor.inputValuesDecorator) {
args = descriptor.inputValuesDecorator(args);
}
return function (dataRow) {
return condition.apply(dataRow.meta.instance, [].concat([dataRow], [args]));
};
}
/**
* Get condition object descriptor which defines some additional informations about this condition.
*
* @param {String} name Condition name.
* @returns {Object}
*/
function getConditionDescriptor(name) {
if (!conditions[name]) {
throw Error("Filter condition \"" + name + "\" does not exist.");
}
return conditions[name].descriptor;
}
/**
* Condition registerer.
*
* @param {String} name Condition name.
* @param {Function} condition Condition function
* @param {Object} descriptor Condition descriptor
*/
function registerCondition(name, condition, descriptor) {
descriptor.key = name;
conditions[name] = {
condition: condition, descriptor: descriptor
};
}
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.stopImmediatePropagation = stopImmediatePropagation;
exports.isImmediatePropagationStopped = isImmediatePropagationStopped;
exports.stopPropagation = stopPropagation;
exports.pageX = pageX;
exports.pageY = pageY;
exports.isRightClick = isRightClick;
exports.isLeftClick = isLeftClick;
var _element = __webpack_require__(2);
/**
* Prevent other listeners of the same event from being called.
*
* @param {Event} event
*/
function stopImmediatePropagation(event) {
event.isImmediatePropagationEnabled = false;
event.cancelBubble = true;
}
/**
* Check if event was stopped by `stopImmediatePropagation`.
*
* @param event {Event}
* @returns {Boolean}
*/
function isImmediatePropagationStopped(event) {
return event.isImmediatePropagationEnabled === false;
}
/**
* Prevent further propagation of the current event (prevent bubbling).
*
* @param event {Event}
*/
function stopPropagation(event) {
// ie8
// http://msdn.microsoft.com/en-us/library/ie/ff975462(v=vs.85).aspx
if (typeof event.stopPropagation === 'function') {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
/**
* Get horizontal coordinate of the event object relative to the whole document.
*
* @param {Event} event
* @returns {Number}
*/
function pageX(event) {
if (event.pageX) {
return event.pageX;
}
return event.clientX + (0, _element.getWindowScrollLeft)();
}
/**
* Get vertical coordinate of the event object relative to the whole document.
*
* @param {Event} event
* @returns {Number}
*/
function pageY(event) {
if (event.pageY) {
return event.pageY;
}
return event.clientY + (0, _element.getWindowScrollTop)();
}
/**
* Check if provided event was triggered by clicking the right mouse button.
*
* @param {Event} event DOM Event.
* @returns {Boolean}
*/
function isRightClick(event) {
return event.button === 2;
}
/**
* Check if provided event was triggered by clicking the left mouse button.
*
* @param {Event} event DOM Event.
* @returns {Boolean}
*/
function isLeftClick(event) {
return event.button === 0;
}
/***/ }),
/* 12 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _templateObject = _taggedTemplateLiteral(['\n Your license key of Handsontable Pro has expired.\u200C\u200C\u200C\u200C \n Renew your maintenance plan at https://handsontable.com or downgrade to the previous version of the software.\n '], ['\n Your license key of Handsontable Pro has expired.\u200C\u200C\u200C\u200C\\x20\n Renew your maintenance plan at https://handsontable.com or downgrade to the previous version of the software.\n ']);
exports.stringify = stringify;
exports.isDefined = isDefined;
exports.isUndefined = isUndefined;
exports.isEmpty = isEmpty;
exports.isRegExp = isRegExp;
exports._injectProductInfo = _injectProductInfo;
var _moment = __webpack_require__(23);
var _moment2 = _interopRequireDefault(_moment);
var _templateLiteralTag = __webpack_require__(34);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
/**
* Converts any value to string.
*
* @param {*} value
* @returns {String}
*/
function stringify(value) {
var result = void 0;
switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) {
case 'string':
case 'number':
result = '' + value;
break;
case 'object':
result = value === null ? '' : value.toString();
break;
case 'undefined':
result = '';
break;
default:
result = value.toString();
break;
}
return result;
}
/**
* Checks if given variable is defined.
*
* @param {*} variable Variable to check.
* @returns {Boolean}
*/
function isDefined(variable) {
return typeof variable !== 'undefined';
}
/**
* Checks if given variable is undefined.
*
* @param {*} variable Variable to check.
* @returns {Boolean}
*/
function isUndefined(variable) {
return typeof variable === 'undefined';
}
/**
* Check if given variable is null, empty string or undefined.
*
* @param {*} variable Variable to check.
* @returns {Boolean}
*/
function isEmpty(variable) {
return variable === null || variable === '' || isUndefined(variable);
}
/**
* Check if given variable is a regular expression.
*
* @param {*} variable Variable to check.
* @returns {Boolean}
*/
function isRegExp(variable) {
return Object.prototype.toString.call(variable) === '[object RegExp]';
}
/* eslint-disable */
var _m = '\x6C\x65\x6E\x67\x74\x68';
var _hd = function _hd(v) {
return parseInt(v, 16);
};
var _pi = function _pi(v) {
return parseInt(v, 10);
};
var _ss = function _ss(v, s, l) {
return v['\x73\x75\x62\x73\x74\x72'](s, l);
};
var _cp = function _cp(v) {
return v['\x63\x6F\x64\x65\x50\x6F\x69\x6E\x74\x41\x74'](0) - 65;
};
var _norm = function _norm(v) {
return ('' + v).replace(/\-/g, '');
};
var _extractTime = function _extractTime(v) {
return _hd(_ss(_norm(v), _hd('12'), _cp('\x46'))) / (_hd(_ss(_norm(v), _cp('\x42'), ~~![][_m])) || 9);
};
var _ignored = function _ignored() {
return typeof location !== 'undefined' && /^([a-z0-9\-]+\.)?\x68\x61\x6E\x64\x73\x6F\x6E\x74\x61\x62\x6C\x65\x2E\x63\x6F\x6D$/i.test(location.host);
};
var _notified = false;
function _injectProductInfo(key, element) {
key = _norm(key || '');
var warningMessage = '';
var showDomMessage = true;
var schemaValidity = _checkKeySchema(key);
var ignored = _ignored();
var trial = isEmpty(key) || key === 'trial';
if (trial || schemaValidity) {
if (schemaValidity) {
var releaseTime = Math.floor((0, _moment2.default)('20/03/2018', 'DD/MM/YYYY').toDate().getTime() / 8.64e7);
var keyGenTime = _extractTime(key);
if (keyGenTime > 45000 || keyGenTime !== parseInt(keyGenTime, 10)) {
warningMessage = 'The license key provided to Handsontable Pro is invalid. Make sure you pass it correctly.';
}
if (!warningMessage) {
if (releaseTime > keyGenTime + 1) {
warningMessage = (0, _templateLiteralTag.toSingleLine)(_templateObject);
}
showDomMessage = releaseTime > keyGenTime + 15;
}
} else {
warningMessage = 'Evaluation version of Handsontable Pro. Not licensed for use in a production environment.';
}
} else {
warningMessage = 'The license key provided to Handsontable Pro is invalid. Make sure you pass it correctly.';
}
if (ignored) {
warningMessage = false;
showDomMessage = false;
}
if (warningMessage && !_notified) {
console[trial ? 'info' : 'warn'](warningMessage);
_notified = true;
}
if (showDomMessage && element.parentNode) {
var message = document.createElement('div');
message.id = 'hot-display-license-info';
message.appendChild(document.createTextNode('Evaluation version of Handsontable Pro.'));
message.appendChild(document.createElement('br'));
message.appendChild(document.createTextNode('Not licensed for production use.'));
element.parentNode.insertBefore(message, element.nextSibling);
}
}
function _checkKeySchema(v) {
var z = [][_m];
var p = z;
if (v[_m] !== _cp('\x5A')) {
return false;
}
for (var c = '', i = '\x42\x3C\x48\x34\x50\x2B'.split(''), j = _cp(i.shift()); j; j = _cp(i.shift() || 'A')) {
--j < ''[_m] ? p = p | (_pi('' + _pi(_hd(c) + (_hd(_ss(v, Math.abs(j), 2)) + []).padStart(2, '0'))) % 97 || 2) >> 1 : c = _ss(v, j, !j ? 6 : i[_m] === 1 ? 9 : 8);
}
return p === z;
}
/* eslint-enable */
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _array = __webpack_require__(0);
var _object = __webpack_require__(1);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @description
* Handsontable events are the common interface that function in 2 ways: as __callbacks__ and as __hooks__.
*
* @example
*
* ```js
* // Using events as callbacks:
* ...
* var hot1 = new Handsontable(document.getElementById('example1'), {
* afterChange: function(changes, source) {
* $.ajax({
* url: "save.php',
* data: change
* });
* }
* });
* ...
* ```
*
* ```js
* // Using events as plugin hooks:
* ...
* var hot1 = new Handsontable(document.getElementById('example1'), {
* myPlugin: true
* });
*
* var hot2 = new Handsontable(document.getElementById('example2'), {
* myPlugin: false
* });
*
* // global hook
* Handsontable.hooks.add('afterChange', function() {
* // Fired twice - for hot1 and hot2
* if (this.getSettings().myPlugin) {
* // function body - will only run for hot1
* }
* });
*
* // local hook (has same effect as a callback)
* hot2.addHook('afterChange', function() {
* // function body - will only run in #example2
* });
* ```
* ...
*/
// @TODO: Move plugin description hooks to plugin?
var REGISTERED_HOOKS = [
/**
* Callback fired after resetting a cell's meta.
*
* @event Hooks#afterCellMetaReset
* @since 0.11
*/
'afterCellMetaReset',
/**
* @description
* Callback fired after one or more cells has been changed. Its main use case is to save the input.
*
* __Note:__ For performance reasons, the `changes` array is null for `"loadData"` source.
*
* @event Hooks#afterChange
* @param {Array} changes 2D array containing information about each of the edited cells `[[row, prop, oldVal, newVal], ...]`.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterChange',
/**
* @description
* Fired after observing changes.
*
* @event Hooks#afterChangesObserved
*/
'afterChangesObserved',
/**
* @description
* Fired after setting up the Context Menu's default options. These options are a collection which user can select by setting
* an array of keys or an array of objects in `contextMenu` option.
*
* @event Hooks#afterContextMenuDefaultOptions
* @param {Array} predefinedItems Array of objects containing information about the pre-defined Context Menu items.
*/
'afterContextMenuDefaultOptions',
/**
* @description
* Fired before setting up the Context Menu's items but after filtering these options by user (`contextMenu` option). This hook
* can by helpful to determine if user use specified menu item or to set up one of the menu item to by always visible.
*
* @event Hooks#beforeContextMenuSetItems
* @param {Array} menuItems Array of objects containing information about to generated Context Menu items.
*/
'beforeContextMenuSetItems',
/**
* @description
* Fired after setting up the Context Menu's default options. These options are a collection which user can select by setting
* an array of keys or an array of objects in `contextMenu` option.
*
* @pro
* @event Hooks#afterDropdownMenuDefaultOptions
* @param {Array} predefinedItems Array of objects containing information about the pre-defined Context Menu items.
*/
'afterDropdownMenuDefaultOptions',
/**
* @description
* Fired before setting up the Dropdown Menu's items but after filtering these options by user (`dropdownMenu` option). This hook
* can by helpful to determine if user use specified menu item or to set up one of the menu item to by always visible.
*
* @pro
* @event Hooks#beforeDropdownMenuSetItems
* @param {Array} menuItems Array of objects containing information about to generated Dropdown Menu items.
*/
'beforeDropdownMenuSetItems',
/**
* @description
* Fired after hiding the Context Menu.
*
* @event Hooks#afterContextMenuHide
* @param {Object} context The Context menu instance.
*/
'afterContextMenuHide',
/**
* @description
* Fired after opening the Context Menu.
*
* @event Hooks#afterContextMenuShow
* @param {Object} context The Context Menu instance.
*/
'afterContextMenuShow',
/**
* @description
* Fired after reaching the copy limit while copying data.
*
* @event Hooks#afterCopyLimit
* @param {Number} selectedRows Count of selected copyable rows.
* @param {Number} selectedColumns Count of selected copyable columns.
* @param {Number} copyRowsLimit Current copy rows limit.
* @param {Number} copyColumnsLimit Current copy columns limit.
*/
'afterCopyLimit',
/**
* Callback is fired before a new column was created.
*
* @since 0.28.0
* @event Hooks#beforeCreateCol
* @param {Number} index Represents the visual index of first newly created column in the data source array.
* @param {Number} amount Number of newly created columns in the data source array.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'beforeCreateCol',
/**
* Callback is fired after a new column was created.
*
* @event Hooks#afterCreateCol
* @param {Number} index Represents the visual index of first newly created column in the data source array.
* @param {Number} amount Number of newly created columns in the data source array.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterCreateCol',
/**
* Callback is fired before a new row was created.
*
* @since 0.28.0
* @event Hooks#beforeCreateRow
* @param {Number} index Represents the visual index of first newly created row in the data source array.
* @param {Number} amount Number of newly created rows in the data source array.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'beforeCreateRow',
/**
* Callback is fired after a new row was created.
*
* @event Hooks#afterCreateRow
* @param {Number} index Represents the visual index of first newly created row in the data source array.
* @param {Number} amount Number of newly created rows in the data source array.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterCreateRow',
/**
* Fired after the current cell is deselected.
*
* @event Hooks#afterDeselect
*/
'afterDeselect',
/**
* Fired after destroying the Handsontable instance.
*
* @event Hooks#afterDestroy
*/
'afterDestroy',
/**
* Fired on a `keydown` event on the document body.
*
* @event Hooks#afterDocumentKeyDown
* @param {Event} event A `keydown` event.
*/
'afterDocumentKeyDown',
/**
* Callback fired after getting the cell settings.
*
* @event Hooks#afterGetCellMeta
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {Object} cellProperties Object containing the cell properties.
*/
'afterGetCellMeta',
/**
* Callback fired after retrieving information about a column header and appending it to the table header.
*
* @event Hooks#afterGetColHeader
* @param {Number} col Visual column index.
* @param {Element} TH Header's TH element.
*/
'afterGetColHeader',
/**
* Callback fired after retrieving information about a column header and appending it to the table header.
*
* @event Hooks#afterGetRowHeader
* @param {Number} row Visual row index.
* @param {Element} TH Header's TH element.
*/
'afterGetRowHeader',
/**
* Callback fired after Handsontable instance is initiated.
*
* @event Hooks#afterInit
*/
'afterInit',
/**
* Callback fired after new data is loaded (by `loadData` method) into the data source array.
*
* @event Hooks#afterLoadData
* @param {Boolean} firstTime flag that determines whether the data has been loaded during the initialization.
*/
'afterLoadData',
/**
* Fired after a scroll event, which is identified as a momentum scroll (e.g. on an iPad).
*
* @event Hooks#afterMomentumScroll
*/
'afterMomentumScroll',
/**
* Fired after a `mousedown` event is triggered on the cell corner (the drag handle).
*
* @event Hooks#afterOnCellCornerMouseDown
* @since 0.11
* @param {Object} event `mousedown` event object.
*/
'afterOnCellCornerMouseDown',
/**
* Fired after a `dblclick` event is triggered on the cell corner (the drag handle).
*
* @event Hooks#afterOnCellCornerDblClick
* @since 0.30.0
* @param {Object} event `dblclick` event object.
*/
'afterOnCellCornerDblClick',
/**
* Callback fired after clicking on a cell or row/column header.
* In case the row/column header was clicked, the index is negative.
* For example clicking on the row header of cell (0, 0) results with `afterOnCellMouseDown` called
* with coords `{row: 0, col: -1}`.
*
* @event Hooks#afterOnCellMouseDown
* @since 0.11
* @param {Object} event `mousedown` event object.
* @param {Object} coords Coordinates object containing the visual row and visual column indexes of the clicked cell.
* @param {Element} TD Cell's TD (or TH) element.
*/
'afterOnCellMouseDown',
/**
* Callback fired after hovering a cell or row/column header with the mouse cursor.
* In case the row/column header was hovered, the index is negative.
* For example, hovering over the row header of cell (0, 0) results with `afterOnCellMouseOver` called
* with coords `{row: 0, col: -1}`.
*
* @event Hooks#afterOnCellMouseOver
* @since 0.11
* @param {Object} event `mouseover` event object.
* @param {Object} coords Hovered cell's visual coordinate object.
* @param {Element} TD Cell's TD (or TH) element.
*/
'afterOnCellMouseOver',
/**
* Callback fired after leaving a cell or row/column header with the mouse cursor.
*
* @event Hooks#afterOnCellMouseOut
* @since 0.31.1
* @param {Object} event `mouseout` event object.
* @param {Object} coords Leaved cell's visual coordinate object.
* @param {Element} TD Cell's TD (or TH) element.
*/
'afterOnCellMouseOut',
/**
* Callback is fired when one or more columns are removed.
*
* @event Hooks#afterRemoveCol
* @param {Number} index Is an visual index of starter column.
* @param {Number} amount Is an amount of removed columns.
*/
'afterRemoveCol',
/**
* Callback is fired when one or more rows are removed.
*
* @event Hooks#afterRemoveRow
* @param {Number} index Is an visual index of starter row.
* @param {Number} amount Is an amount of removed rows.
*/
'afterRemoveRow',
/**
* Callback fired after the Handsontable table is rendered.
*
* @event Hooks#afterRender
* @param {Boolean} isForced Is `true` if rendering was triggered by a change of settings or data; or `false` if
* rendering was triggered by scrolling or moving selection.
*/
'afterRender',
/**
* Fired before starting rendering the cell.
*
* @event Hooks#beforeRenderer
* @since 0.24.2
* @param {Element} TD Currently rendered cell's TD element.
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays.
* @param {String} value Value of the rendered cell.
* @param {Object} cellProperties Object containing the cell's properties.
*/
'beforeRenderer',
/**
* Fired after finishing rendering the cell (after the renderer finishes).
*
* @event Hooks#afterRenderer
* @since 0.11.0
* @param {Element} TD Currently rendered cell's TD element.
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays.
* @param {String} value Value of the rendered cell.
* @param {Object} cellProperties Object containing the cell's properties.
*/
'afterRenderer',
/**
* Fired after the horizontal scroll event.
*
* @event Hooks#afterScrollHorizontally
* @since 0.11
*/
'afterScrollHorizontally',
/**
* Fired after the vertical scroll event.
*
* @event Hooks#afterScrollVertically
* @since 0.11
*/
'afterScrollVertically',
/**
* Callback fired after one or more cells are selected (e.g. during mouse move).
*
* @event Hooks#afterSelection
* @param {Number} r Selection start visual row index.
* @param {Number} c Selection start visual column index.
* @param {Number} r2 Selection end visual row index.
* @param {Number} c2 Selection end visual column index.
* @param {Object} preventScrolling Object with `value` property where its value change will be observed.
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified.
* * @example
* ```js
* handsontable({
* afterSelection: function (r, c, r2, c2, preventScrolling, selectionLayerLevel) {
* // setting if prevent scrolling after selection
* preventScrolling.value = true;
* }
* })
* ```
*/
'afterSelection',
/**
* Callback fired after one or more cells are selected. The `p` argument represents the source object property name instead of the column number.
*
* @event Hooks#afterSelectionByProp
* @param {Number} r Selection start visual row index.
* @param {String} p Selection start data source object property name.
* @param {Number} r2 Selection end visual row index.
* @param {String} p2 Selection end data source object property name.
* @param {Object} preventScrolling Object with `value` property where its value change will be observed.
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified.
* * @example
* ```js
* handsontable({
* afterSelectionByProp: function (r, c, r2, c2, preventScrolling, selectionLayerLevel) {
* // setting if prevent scrolling after selection
* preventScrolling.value = true;
* }
* })
* ```
*/
'afterSelectionByProp',
/**
* Callback fired after one or more cells are selected (e.g. on mouse up).
*
* @event Hooks#afterSelectionEnd
* @param {Number} r Selection start visual row index.
* @param {Number} c Selection start visual column index.
* @param {Number} r2 Selection end visual row index.
* @param {Number} c2 Selection end visual column index.
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified.
*/
'afterSelectionEnd',
/**
* Callback fired after one or more cells are selected (e.g. on mouse up). The `p` argument represents the data source object
* property name instead of the column number.
*
* @event Hooks#afterSelectionEndByProp
* @param {Number} r Selection start visual row index.
* @param {String} p Selection start data source object property index.
* @param {Number} r2 Selection end visual row index.
* @param {String} p2 Selection end data source object property index.
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified.
*/
'afterSelectionEndByProp',
/**
* Called after cell meta is changed.
*
* @event Hooks#afterSetCellMeta
* @since 0.11.0
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String} key The updated meta key.
* @param {*} value The updated meta value.
*/
'afterSetCellMeta',
/**
* Called after cell meta is removed.
*
* @event Hooks#afterRemoveCellMeta
* @since 0.33.1
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String} key The removed meta key.
* @param {*} value Value which was under removed key of cell meta.
*/
'afterRemoveCellMeta',
/**
* Called after cell data was changed.
*
* @event Hooks#afterSetDataAtCell
* @since 0.28.0
* @param {Array} changes An array of changes in format `[[row, col, oldValue, value], ...]`.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterSetDataAtCell',
/**
* Called after cell data was changed.
*
* @event Hooks#afterSetDataAtRowProp
* @since 0.28.0
* @param {Array} changes An array of changes in format `[[row, prop, oldValue, value], ...]`.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterSetDataAtRowProp',
/**
* Fired after calling the `updateSettings` method.
*
* @event Hooks#afterUpdateSettings
* @param {Object} settings New settings object.
*/
'afterUpdateSettings',
/**
* @description
* A plugin hook executed after validator function, only if validator function is defined.
* Validation result is the first parameter. This can be used to determinate if validation passed successfully or not.
*
* __Returning false from the callback will mark the cell as invalid.__
*
* @event Hooks#afterValidate
* @since 0.9.5
* @param {Boolean} isValid `true` if valid, `false` if not.
* @param {*} value The value in question.
* @param {Number} row Row index.
* @param {String|Number} prop Property name / column index.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'afterValidate',
/**
* Fired before successful change of language (when proper language code was set)
*
* @event Hooks#beforeLanguageChange
* @since 0.35.0
* @param {String} languageCode New language code.
*/
'beforeLanguageChange',
/**
* Fired after successful change of language (when proper language code was set)
*
* @event Hooks#afterLanguageChange
* @since 0.35.0
* @param {String} languageCode New language code.
*/
'afterLanguageChange',
/**
* Fired before populating the data in the autofill feature.
*
* @event Hooks#beforeAutofill
* @param {Object} start Object containing information about first filled cell: `{row: 2, col: 0}`.
* @param {Object} end Object containing information about last filled cell: `{row: 4, col: 1}`.
* @param {Array} data 2D array containing information about fill pattern: `[["1", "Ted"], ["1", "John"]]`.
* @param {Array} baseRange The coordinates of the base area for autofill.
*/
'beforeAutofill',
/**
* Fired before aligning the cell contents.
*
* @event Hooks#beforeCellAlignment
* @param stateBefore
* @param range
* @param {String} type Type of the alignment - either `horizontal` or `vertical`
* @param {String} alignmentClass String defining the alignment class added to the cell.
* Possible values:
* * `htLeft`,
* * `htCenter`,
* * `htRight`,
* * `htJustify`
* for horizontal alignment,
*
*
* * `htTop`,
* * `htMiddle`,
* * `htBottom`
* for vertical alignment.
*/
'beforeCellAlignment',
/**
* Callback fired before one or more cells is changed. Its main purpose is to alter changes silently before input.
*
* @event Hooks#beforeChange
* @param {Array} changes 2D array containing information about each of the edited cells.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
* @example
* ```js
* // To disregard a single change, set changes[i] to null or remove it from array using changes.splice(i, 1).
* ...
* new Handsontable(document.getElementById('example'), {
* beforeChange: function(changes, source) {
* // [[row, prop, oldVal, newVal], ...]
* changes[0] = null;
* }
* });
* ...
*
* // To alter a single change, overwrite the desired value to changes[i][3].
* ...
* new Handsontable(document.getElementById('example'), {
* beforeChange: function(changes, source) {
* // [[row, prop, oldVal, newVal], ...]
* changes[0][3] = 10;
* }
* });
* ...
*
* // To cancel all edit, return false from the callback or set array length to 0 (changes.length = 0).
* ...
* new Handsontable(document.getElementById('example'), {
* beforeChange: function(changes, source) {
* // [[row, prop, oldVal, newVal], ...]
* return false;
* }
* });
* ...
* ```
*/
'beforeChange',
/**
* Fired right before rendering the changes.
*
* @event Hooks#beforeChangeRender
* @since 0.11
* @param {Array} changes Array in form of [row, prop, oldValue, newValue].
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'beforeChangeRender',
/**
* Fired before drawing the borders.
*
* @event Hooks#beforeDrawBorders
* @param {Array} corners Array specifying the current selection borders.
* @param {String} borderClassName Specifies the border class name.
*/
'beforeDrawBorders',
/**
* Callback fired before getting cell settings.
*
* @event Hooks#beforeGetCellMeta
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {Object} cellProperties Object containing the cell's properties.
*/
'beforeGetCellMeta',
/**
* Called before cell meta is removed.
*
* @event Hooks#beforeRemoveCellMeta
* @since 0.33.1
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String} key The removed meta key.
* @param {*} value Value which is under removed key of cell meta.
*/
'beforeRemoveCellMeta',
/**
* @description
* Callback fired before Handsontable instance is initiated.
*
* @event Hooks#beforeInit
*/
'beforeInit',
/**
* Callback fired before Walkontable instance is initiated.
*
* @since 0.11
* @event Hooks#beforeInitWalkontable
* @param {Object} walkontableConfig Walkontable configuration object.
*/
'beforeInitWalkontable',
/**
* Callback fired before keydown event is handled. It can be used to overwrite default key bindings.
* Caution - in your `beforeKeyDown` handler you need to call `event.stopImmediatePropagation()` to prevent default key behavior.
*
* @event Hooks#beforeKeyDown
* @since 0.9.0
* @param {Event} event Original DOM event.
*/
'beforeKeyDown',
/**
* Fired after the user clicked a cell, but before all the calculations related with it.
*
* @event Hooks#beforeOnCellMouseDown
* @param {Event} event The `mousedown` event object.
* @param {CellCoords} coords Cell coords object containing the visual coordinates of the clicked cell.
* @param {Element} TD TD element.
*/
'beforeOnCellMouseDown',
/**
* Fired after the user moved cursor over a cell, but before all the calculations related with it.
*
* @event Hooks#beforeOnCellMouseOver
* @param {Event} event The `mouseover` event object.
* @param {CellCoords} coords CellCoords object containing the visual coordinates of the clicked cell.
* @param {Element} TD TD element.
* @param {Object} blockCalculations Contain keys 'row' and 'column' with boolean value.
*/
'beforeOnCellMouseOver',
/**
* Fired after the user moved cursor out from a cell, but before all the calculations related with it.
*
* @event Hooks#beforeOnCellMouseOut
* @since 0.31.1
* @param {Event} event The `mouseout` event object.
* @param {WalkontableCellCoords} coords WalkontableCellCoords object containing the visual coordinates of the leaved cell.
* @param {Element} TD TD element.
*/
'beforeOnCellMouseOut',
/**
* Callback is fired when one or more columns are about to be removed.
*
* @event Hooks#beforeRemoveCol
* @param {Number} index Visual index of starter column.
* @param {Number} amount Amount of columns to be removed.
* @param {Array} [visualCols] Consists of visual indexes of processed columns.
*/
'beforeRemoveCol',
/**
* Callback is fired when one or more rows are about to be removed.
*
* @event Hooks#beforeRemoveRow
* @param {Number} index Visual index of starter column.
* @param {Number} amount Amount of columns to be removed.
* @param {Array} [visualRows] Consists of visual indexes of processed rows.
*/
'beforeRemoveRow',
/**
* Callback fired before Handsontable table is rendered.
*
* @event Hooks#beforeRender
* @param {Boolean} isForced If `true` rendering was triggered by a change of settings or data; or `false` if
* rendering was triggered by scrolling or moving selection.
*/
'beforeRender',
/**
* Callback fired before setting range is started but not finished yet.
*
* @event Hooks#beforeSetRangeStartOnly
* @param {CellCoords} coords CellCoords instance.
*/
'beforeSetRangeStartOnly',
/**
* Callback fired before setting range is started.
*
* @event Hooks#beforeSetRangeStart
* @param {CellCoords} coords CellCoords instance.
*/
'beforeSetRangeStart',
/**
* Callback fired before setting range is ended.
*
* @event Hooks#beforeSetRangeEnd
* @param {CellCoords} coords CellCoords instance.
*/
'beforeSetRangeEnd',
/**
* Fired before the logic of handling a touch scroll, when user started scrolling on a touch-enabled device.
*
* @event Hooks#beforeTouchScroll
*/
'beforeTouchScroll',
/**
* @description
* A plugin hook executed before validator function, only if validator function is defined.
* This can be used to manipulate the value of changed cell before it is applied to the validator function.
*
* __Notice:__ this will not affect values of changes. This will change value ONLY for validation!
*
* @event Hooks#beforeValidate
* @since 0.9.5
* @param {*} value Value of the cell.
* @param {Number} row Row index.
* @param {String|Number} prop Property name / column index.
* @param {String} [source] String that identifies source of hook call
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
*/
'beforeValidate',
/**
* Callback fired before cell value is rendered into the DOM (through renderer function).
*
* @event Hooks#beforeValueRender
* @since 0.29.0
* @param {*} value Cell value to render.
*/
'beforeValueRender',
/**
* Callback fired after Handsontable instance is constructed (via `new` operator).
*
* @event Hooks#construct
* @since 0.16.1
*/
'construct',
/**
* Callback fired after Handsontable instance is initiated but before table is rendered.
*
* @event Hooks#init
* @since 0.16.1
*/
'init',
/**
* Fired when a column index is about to be modified by a callback function.
*
* @event Hooks#modifyCol
* @since 0.11
* @param {Number} col Visual column index.
*/
'modifyCol',
/**
* Fired when a column index is about to be de-modified by a callback function.
*
* @event Hooks#unmodifyCol
* @since 0.23.0
* @param {Number} col Physical column index.
*/
'unmodifyCol',
/**
* Fired when a physical row index is about to be de-modified by a callback function.
*
* @event Hooks#unmodifyRow
* @since 0.26.2
* @param {Number} row Physical row index.
*/
'unmodifyRow',
/**
* Fired when a column header index is about to be modified by a callback function.
*
* @event Hooks#modifyColHeader
* @since 0.20.0
* @param {Number} column Visual column header index.
*/
'modifyColHeader',
/**
* Fired when a column width is about to be modified by a callback function.
*
* @event Hooks#modifyColWidth
* @since 0.11
* @param {Number} width Current column width.
* @param {Number} col Column index.
*/
'modifyColWidth',
/**
* Fired when a row index is about to be modified by a callback function.
*
* @event Hooks#modifyRow
* @since 0.11
* @param {Number} row Row index.
*/
'modifyRow',
/**
* Fired when a row header index is about to be modified by a callback function.
*
* @event Hooks#modifyRowHeader
* @since 0.20.0
* @param {Number} row Row header index.
*/
'modifyRowHeader',
/**
* Fired when a row height is about to be modified by a callback function.
*
* @event Hooks#modifyRowHeight
* @since 0.11.0
* @param {Number} height Row height.
* @param {Number} row Row index.
*/
'modifyRowHeight',
/**
* Fired when a data was retrieved or modified.
*
* @event Hooks#modifyData
* @since 0.28.0
* @param {Number} row Row height.
* @param {Number} column Column index.
* @param {Object} valueHolder Object which contains original value which can be modified by overwriting `.value` property.
* @param {String} ioMode String which indicates for what operation hook is fired (`get` or `set`).
*/
'modifyData',
/**
* Fired when a data was retrieved or modified.
*
* @event Hooks#modifyRowData
* @since 0.28.0
* @param {Number} row Physical row index.
*/
'modifyRowData',
/**
* Used to modify the cell coordinates when using the `getCell` method.
*
* @event Hooks#modifyGetCellCoords
* @since 0.36.0
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {Boolean} topmost If set to true, it returns the TD element from the topmost overlay. For example,
* if the wanted cell is in the range of fixed rows, it will return a TD element from the `top` overlay.
*/
'modifyGetCellCoords',
/**
* Fired after loading data using the Persistent State plugin.
*
* @event Hooks#persistentStateLoad
* @param {String} key Key string.
* @param {Object} valuePlaceholder Object containing the loaded data.
*/
'persistentStateLoad',
/**
* Fired after resetting data using the Persistent State plugin.
*
* @event Hooks#persistentStateReset
* @param {String} key Key string.
*/
'persistentStateReset',
/**
* Fired after resetting data using the Persistent State plugin.
*
* @event Hooks#persistentStateSave
* @param {String} key Key string.
* @param {Mixed} value Value to save.
*/
'persistentStateSave',
/**
* Fired before sorting the column. If you return `false` value then sorting will be not applied by
* Handsontable (useful for server-side sorting).
*
* @event Hooks#beforeColumnSort
* @param {Number} column Sorted visual column index.
* @param {Boolean} order Soring order where:
* * `true` means ascending order,
* * `false` means descending order,
* * `undefined` means original order.
*/
'beforeColumnSort',
/**
* Fired after sorting the column.
*
* @event Hooks#afterColumnSort
* @param {Number} column Sorted visual column index.
* @param {Boolean} order Soring order where:
* * `true` means ascending order
* * `false` means descending order
* * `undefined` means original order
*/
'afterColumnSort',
/**
* @description
* Fired after setting range of autofill.
* Both arguments are provided in the following format:
* ```js
* [startRow, startColumn, endRow, endColumn]
* ```
*
* @event Hooks#modifyAutofillRange
* @param {Array} startArea Array of visual coordinates of the starting point for the drag-down operation.
* @param {Array} entireArea Array of visual coordinates of the entire area of the drag-down operation.
*/
'modifyAutofillRange',
/**
* Fired to allow modifying the copyable range with a callback function.
*
* @since 0.19.0
* @event Hooks#modifyCopyableRange
* @param {Array} copyableRanges Array of objects defining copyable cells.
*/
'modifyCopyableRange',
/**
* Called before copying the values into clipboard and before clearing values of the selected cells.
*
* @event Hooks#beforeCut
* @since 0.31.1
* @param {Array} data An array of arrays which contains data to cut.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* which will be cut out.
* @returns {*} If returns `false` then operation of the cutting out is cancelled.
*
* @example
* ```js
* // To disregard a single row, remove it from array using data.splice(i, 1).
* ...
* new Handsontable(document.getElementById('example'), {
* beforeCut: function(data, coords) {
* // data -> [[1, 2, 3], [4, 5, 6]]
* data.splice(0, 1);
* // data -> [[4, 5, 6]]
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
* }
* });
* ...
*
* // To cancel cutting out, return false from the callback.
* ...
* new Handsontable(document.getElementById('example'), {
* beforeCut: function(data, coords) {
* return false;
* }
* });
* ...
* ```
*/
'beforeCut',
/**
* Fired after data are cutted out from the table.
*
* @event Hooks#afterCut
* @since 0.31.1
* @param {Array} data An array of arrays which contains the cutted out data.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* which was cut out.
*/
'afterCut',
/**
* Fired before values are copied into clipboard.
*
* @event Hooks#beforeCopy
* @since 0.31.1
* @param {Array} data An array of arrays which contains data to copied.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* which will copied.
* @returns {*} If returns `false` then copying is cancelled.
*
* @example
* ```js
* // To disregard a single row, remove it from array using data.splice(i, 1).
* ...
* new Handsontable(document.getElementById('example'), {
* beforeCopy: function(data, coords) {
* // data -> [[1, 2, 3], [4, 5, 6]]
* data.splice(0, 1);
* // data -> [[4, 5, 6]]
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
* }
* });
* ...
*
* // To cancel copying, return false from the callback.
* ...
* new Handsontable(document.getElementById('example'), {
* beforeCopy: function(data, coords) {
* return false;
* }
* });
* ...
* ```
*/
'beforeCopy',
/**
* Fired after data are pasted into table.
*
* @event Hooks#afterCopy
* @since 0.31.1
* @param {Array} data An array of arrays which contains the copied data.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* which was copied.
*/
'afterCopy',
/**
* Fired before values are pasted into table.
*
* @event Hooks#beforePaste
* @since 0.31.1
* @param {Array} data An array of arrays which contains data to paste.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* that correspond to the previously selected area.
* @returns {*} If returns `false` then pasting is cancelled.
*
* @example
* ```js
* // To disregard a single row, remove it from array using data.splice(i, 1).
* ...
* new Handsontable(document.getElementById('example'), {
* beforePaste: function(data, coords) {
* // data -> [[1, 2, 3], [4, 5, 6]]
* data.splice(0, 1);
* // data -> [[4, 5, 6]]
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
* }
* });
* ...
*
* // To cancel pasting, return false from the callback.
* ...
* new Handsontable(document.getElementById('example'), {
* beforePaste: function(data, coords) {
* return false;
* }
* });
* ...
* ```
*/
'beforePaste',
/**
* Fired after values are pasted into table.
*
* @event Hooks#afterPaste
* @since 0.31.1
* @param {Array} data An array of arrays which contains the pasted data.
* @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
* that correspond to the previously selected area.
*/
'afterPaste',
/**
* Fired before change order of the visual indexes.
*
* @event Hooks#beforeColumnMove
* @param {Array} columns Array of visual column indexes to be moved.
* @param {Number} target Visual column index being a target for moved columns.
*/
'beforeColumnMove',
/**
* Fired after change order of the visual indexes.
*
* @event Hooks#afterColumnMove
* @param {Array} columns Array of visual column indexes that were moved.
* @param {Number} target Visual column index being a target for moved columns.
*/
'afterColumnMove',
/**
* Fired before change order of the visual indexes.
*
* @event Hooks#beforeRowMove
* @param {Array} rows Array of visual row indexes to be moved.
* @param {Number} target Visual row index being a target for moved rows.
*/
'beforeRowMove',
/**
* Fired after change order of the visual indexes.
*
* @event Hooks#afterRowMove
* @param {Array} rows Array of visual row indexes that were moved.
* @param {Number} target Visual row index being a target for moved rows.
*/
'afterRowMove',
/**
* Fired before rendering the table with modified column sizes.
*
* @event Hooks#beforeColumnResize
* @param {Number} currentColumn Visual index of the resized column.
* @param {Number} newSize Calculated new column width.
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
* @returns {Number} Returns a new column size or `undefined`, if column size should be calculated automatically.
*/
'beforeColumnResize',
/**
* Fired after rendering the table with modified column sizes.
*
* @event Hooks#afterColumnResize
* @param {Number} currentColumn Visual index of the resized column.
* @param {Number} newSize Calculated new column width.
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
*/
'afterColumnResize',
/**
* Fired before rendering the table with modified row sizes.
*
* @event Hooks#beforeRowResize
* @param {Number} currentRow Visual index of the resized row.
* @param {Number} newSize Calculated new row height.
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
* @returns {Number} Returns the new row size or `undefined` if row size should be calculated automatically.
*/
'beforeRowResize',
/**
* Fired after rendering the table with modified row sizes.
*
* @event Hooks#afterRowResize
* @param {Number} currentRow Visual index of the resized row.
* @param {Number} newSize Calculated new row height.
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
*/
'afterRowResize',
/**
* Fired after getting the column header renderers.
*
* @event Hooks#afterGetColumnHeaderRenderers
* @param {Array} array Array of the column header renderers.
*/
'afterGetColumnHeaderRenderers',
/**
* Fired after getting the row header renderers.
*
* @event Hooks#afterGetRowHeaderRenderers
* @param {Array} array Array of the row header renderers.
*/
'afterGetRowHeaderRenderers',
/**
* Fired before applying stretched column width to column.
*
* @event Hooks#beforeStretchingColumnWidth
* @param {Number} stretchedWidth Calculated width.
* @param {Number} column Visual column index.
* @returns {Number} Returns new width which will be applied to the column element.
*/
'beforeStretchingColumnWidth',
/**
* Fired before applying [filtering]{@link http://docs.handsontable.com/pro/demo-filtering.html}.
*
* @pro
* @event Hooks#beforeFilter
* @param {Array} conditionsStack An array of objects with added formulas.
* @returns {Boolean} If hook returns `false` value then filtering won't be applied on the UI side (server-side filtering).
*/
'beforeFilter',
/**
* Fired after applying [filtering]{@link http://docs.handsontable.com/pro/demo-filtering.html}.
*
* @pro
* @event Hooks#afterFilter
* @param {Array} conditionsStack An array of objects with added formulas.
*/
'afterFilter',
/**
* Used to modify the column header height.
*
* @event Hooks#modifyColumnHeaderHeight
* @since 0.25.0
* @param {Number} col Visual column index.
*/
'modifyColumnHeaderHeight',
/**
* Fired before the undo action. Contains information about the action that is being undone.
*
* @event Hooks#beforeUndo
* @since 0.26.2
* @param {Object} action The action object. Contains information about the action being undone. The `actionType`
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
*/
'beforeUndo',
/**
* Fired after the undo action. Contains information about the action that is being undone.
*
* @event Hooks#afterUndo
* @since 0.26.2
* @param {Object} action The action object. Contains information about the action being undone. The `actionType`
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
*/
'afterUndo',
/**
* Fired before the redo action. Contains information about the action that is being redone.
*
* @event Hooks#beforeRedo
* @since 0.26.2
* @param {Object} action The action object. Contains information about the action being redone. The `actionType`
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
*/
'beforeRedo',
/**
* Fired after the redo action. Contains information about the action that is being redone.
*
* @event Hooks#afterRedo
* @since 0.26.2
* @param {Object} action The action object. Contains information about the action being redone. The `actionType`
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
*/
'afterRedo',
/**
* Used to modify the row header width.
*
* @event Hooks#modifyRowHeaderWidth
* @param {Number} rowHeaderWidth Row header width.
*/
'modifyRowHeaderWidth',
/**
* Fired from the `populateFromArray` method during the `autofill` process. Fired for each "autofilled" cell individually.
*
* @event Hooks#beforeAutofillInsidePopulate
* @param {Object} index Object containing `row` and `col` properties, defining the number of rows/columns from the initial cell of the autofill.
* @param {String} direction Declares the direction of the autofill. Possible values: `up`, `down`, `left`, `right`.
* @param {Array} input Array of arrays. Contains an array of rows with data being used in the autofill.
* @param {Array} deltas The deltas array passed to the `populateFromArray` method.
*/
'beforeAutofillInsidePopulate',
/**
* Fired when the start of the selection is being modified. (e.g. moving the selection with the arrow keys).
*
* @event Hooks#modifyTransformStart
* @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one.
*/
'modifyTransformStart',
/**
* Fired when the end of the selection is being modified. (e.g. moving the selection with the arrow keys).
*
* @event Hooks#modifyTransformEnd
* @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one.
*/
'modifyTransformEnd',
/**
* Fired after the start of the selection is being modified. (e.g. moving the selection with the arrow keys).
*
* @event Hooks#afterModifyTransformStart
* @param {CellCoords} coords Coords of the freshly selected cell.
* @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise.
* @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise.
*/
'afterModifyTransformStart',
/**
* Fired after the end of the selection is being modified. (e.g. moving the selection with the arrow keys).
*
* @event Hooks#afterModifyTransformEnd
* @param {CellCoords} coords Visual coords of the freshly selected cell.
* @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise.
* @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise.
*/
'afterModifyTransformEnd',
/**
* Fired inside the `viewportRowCalculatorOverride` method. Allows modifying the row calculator parameters.
*
* @event Hooks#afterViewportRowCalculatorOverride
* @param {Object} calc The row calculator.
*/
'afterViewportRowCalculatorOverride',
/**
* Fired inside the `viewportColumnCalculatorOverride` method. Allows modifying the row calculator parameters.
*
* @event Hooks#afterViewportColumnCalculatorOverride
* @param {Object} calc The row calculator.
*/
'afterViewportColumnCalculatorOverride',
/**
* Fired after initializing all the plugins.
*
* @event Hooks#afterPluginsInitialized
*/
'afterPluginsInitialized',
/**
* Used when saving/loading the manual row heights state.
*
* @event Hooks#manualRowHeights
* @param {Array} state The current manual row heights state.
*/
'manualRowHeights',
/**
* Used to skip the length cache calculation for a defined period of time.
*
* @event Hooks#skipLengthCache
* @param {Number} delay The delay in milliseconds.
*/
'skipLengthCache',
/**
* Fired after trimming rows in the TrimRows plugin.
*
* @pro
* @event Hooks#afterTrimRow
* @param {Array} rows Physical indexes of trimmed rows.
*/
'afterTrimRow',
/**
* Fired after untrimming rows in the TrimRows plugin.
*
* @pro
* @event Hooks#afterUntrimRow
* @param {Array} rows Physical indexes of untrimmed rows.
*/
'afterUntrimRow',
/**
* Fired after opening the dropdown menu.
*
* @pro
* @event Hooks#afterDropdownMenuShow
* @param {DropdownMenu} instance The DropdownMenu instance.
*/
'afterDropdownMenuShow',
/**
* Fired after hiding the dropdown menu.
*
* @pro
* @event Hooks#afterDropdownMenuHide
* @param {DropdownMenu} instance The DropdownMenu instance.
*/
'afterDropdownMenuHide',
/**
* Used to check whether the provided row index is hidden.
*
* @pro
* @event Hooks#hiddenRow
* @param {Number} row The visual row index in question.
*/
'hiddenRow',
/**
* Used to check whether the provided column index is hidden.
*
* @pro
* @event Hooks#hiddenColumn
* @param {Number} column The visual column index in question.
*/
'hiddenColumn',
/**
* Fired before adding a children to the NestedRows structure.
*
* @pro
* @event Hooks#beforeAddChild
* @param {Object} parent The parent object.
* @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added.
* @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child.
*/
'beforeAddChild',
/**
* Fired after adding a children to the NestedRows structure.
*
* @pro
* @event Hooks#afterAddChild
* @param {Object} parent The parent object.
* @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added.
* @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child.
*/
'afterAddChild',
/**
* Fired before detaching a child from its parent in the NestedRows plugin.
*
* @pro
* @event Hooks#beforeDetachChild
* @param {Object} parent An object representing the parent from which the element is to be detached.
* @param {Object} element The detached element.
*/
'beforeDetachChild',
/**
* Fired after detaching a child from its parent in the NestedRows plugin.
*
* @pro
* @event Hooks#afterDetachChild
* @param {Object} parent An object representing the parent from which the element was detached.
* @param {Object} element The detached element.
*/
'afterDetachChild',
/**
* Fired after the editor is opened and rendered.
*
* @event Hooks#afterBeginEditing
* @param {Number} row Row index of the edited cell.
* @param {Number} column Column index of the edited cell.
*/
'afterBeginEditing',
/**
* Fired before cell merging.
*
* @event Hooks#beforeMergeCells
* @param {CellRange} cellRange Selection cell range.
* @param {Boolean} [auto=false] `true` if called automatically by the plugin.
*/
'beforeMergeCells',
/**
* Fired after cell merging.
*
* @event Hooks#afterMergeCells
* @param {CellRange} cellRange Selection cell range.
* @param {Object} mergeParent The parent collection of the provided cell range.
* @param {Boolean} [auto=false] `true` if called automatically by the plugin.
*/
'afterMergeCells',
/**
* Fired before unmerging the cells.
*
* @event Hooks#beforeUnmergeCells
* @param {CellRange} cellRange Selection cell range.
* @param {Boolean} [auto=false] `true` if called automatically by the plugin.
*/
'beforeUnmergeCells',
/**
* Fired after unmerging the cells.
*
* @event Hooks#beforeUnmergeCells
* @param {CellRange} cellRange Selection cell range.
* @param {Boolean} [auto=false] `true` if called automatically by the plugin.
*/
'afterUnmergeCells',
/**
* Fired after the listening is turned on.
*
* @event Hooks#afterListen
* @since 0.34.5
*/
'afterListen',
/**
* Fired after the listening is turned off.
*
* @event Hooks#afterUnlisten
* @since 0.34.5
*/
'afterUnlisten'];
var Hooks = function () {
_createClass(Hooks, null, [{
key: 'getSingleton',
value: function getSingleton() {
return globalSingleton;
}
/**
*
*/
}]);
function Hooks() {
_classCallCheck(this, Hooks);
this.globalBucket = this.createEmptyBucket();
}
/**
* Returns a new object with empty handlers related to every registered hook name.
*
* @returns {Object} The empty bucket object.
*
* @example
* ```js
* Handsontable.hooks.createEmptyBucket();
* // Results:
* {
* ...
* afterCreateCol: [],
* afterCreateRow: [],
* beforeInit: [],
* ...
* }
* ```
*/
_createClass(Hooks, [{
key: 'createEmptyBucket',
value: function createEmptyBucket() {
var bucket = Object.create(null);
// eslint-disable-next-line no-return-assign
(0, _array.arrayEach)(REGISTERED_HOOKS, function (hook) {
return bucket[hook] = [];
});
return bucket;
}
/**
* Get hook bucket based on the context of the object or if argument is `undefined`, get the global hook bucket.
*
* @param {Object} [context=null] A Handsontable instance.
* @returns {Object} Returns a global or Handsontable instance bucket.
*/
}, {
key: 'getBucket',
value: function getBucket() {
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
if (context) {
if (!context.pluginHookBucket) {
context.pluginHookBucket = this.createEmptyBucket();
}
return context.pluginHookBucket;
}
return this.globalBucket;
}
/**
* Adds a listener (globally or locally) to a specified hook name.
* If the `context` parameter is provided, the hook will be added only to the instance it references.
* Otherwise, the callback will be used everytime the hook fires on any Handsontable instance.
* You can provide an array of callback functions as the `callback` argument, this way they will all be fired
* once the hook is triggered.
*
* @see Core#addHook
* @param {String} key Hook name.
* @param {Function|Array} callback Callback function or an array of functions.
* @param {Object} [context=null] The context for the hook callback to be added - a Handsontable instance or leave empty.
* @returns {Hooks} Instance of Hooks.
*
* @example
* ```js
* // single callback, added locally
* Handsontable.hooks.add('beforeInit', myCallback, hotInstance);
*
* // single callback, added globally
* Handsontable.hooks.add('beforeInit', myCallback);
*
* // multiple callbacks, added locally
* Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback], hotInstance);
*
* // multiple callbacks, added globally
* Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback]);
* ```
*/
}, {
key: 'add',
value: function add(key, callback) {
var _this = this;
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (Array.isArray(callback)) {
(0, _array.arrayEach)(callback, function (c) {
return _this.add(key, c, context);
});
} else {
var bucket = this.getBucket(context);
if (typeof bucket[key] === 'undefined') {
this.register(key);
bucket[key] = [];
}
callback.skip = false;
if (bucket[key].indexOf(callback) === -1) {
// only add a hook if it has not already been added (adding the same hook twice is now silently ignored)
var foundInitialHook = false;
if (callback.initialHook) {
(0, _array.arrayEach)(bucket[key], function (cb, i) {
if (cb.initialHook) {
bucket[key][i] = callback;
foundInitialHook = true;
return false;
}
});
}
if (!foundInitialHook) {
bucket[key].push(callback);
}
}
}
return this;
}
/**
* Adds a listener to a specified hook. After the hook runs this listener will be automatically removed from the bucket.
*
* @see Core#addHookOnce
* @param {String} key Hook/Event name.
* @param {Function|Array} callback Callback function.
* @param {Object} [context=null] A Handsontable instance.
*
* @example
* ```js
* Handsontable.hooks.once('beforeInit', myCallback, hotInstance);
* ```
*/
}, {
key: 'once',
value: function once(key, callback) {
var _this2 = this;
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (Array.isArray(callback)) {
(0, _array.arrayEach)(callback, function (c) {
return _this2.once(key, c, context);
});
} else {
callback.runOnce = true;
this.add(key, callback, context);
}
}
/**
* Removes a listener from a hook with a given name. If the `context` argument is provided, it removes a listener from a local hook assigned to the given Handsontable instance.
*
* @see Core#removeHook
* @param {String} key Hook/Event name.
* @param {Function} callback Callback function (needs the be the function that was previously added to the hook).
* @param {Object} [context=null] Handsontable instance.
* @return {Boolean} Returns `true` if hook was removed, `false` otherwise.
*
* @example
* ```js
* Handsontable.hooks.remove('beforeInit', myCallback);
* ```
*/
}, {
key: 'remove',
value: function remove(key, callback) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var bucket = this.getBucket(context);
if (typeof bucket[key] !== 'undefined') {
if (bucket[key].indexOf(callback) >= 0) {
callback.skip = true;
return true;
}
}
return false;
}
/**
* Checks whether there are any registered listeners for the provided hook name.
* If the `context` parameter is provided, it only checks for listeners assigned to the given Handsontable instance.
*
* @param {String} key Hook name.
* @param {Object} [context=null] A Handsontable instance.
* @returns {Boolean} `true` for success, `false` otherwise.
*/
}, {
key: 'has',
value: function has(key) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var bucket = this.getBucket(context);
return !!(bucket[key] !== void 0 && bucket[key].length);
}
/**
* Runs all local and global callbacks assigned to the hook identified by the `key` parameter.
* It returns either a return value from the last called callback or the first parameter (`p1`) passed to the `run` function.
*
* @see Core#runHooks
* @param {Object} context Handsontable instance.
* @param {String} key Hook/Event name.
* @param {*} [p1] Parameter to be passed as an argument to the callback function.
* @param {*} [p2] Parameter to be passed as an argument to the callback function.
* @param {*} [p3] Parameter to be passed as an argument to the callback function.
* @param {*} [p4] Parameter to be passed as an argument to the callback function.
* @param {*} [p5] Parameter to be passed as an argument to the callback function.
* @param {*} [p6] Parameter to be passed as an argument to the callback function.
* @returns {*} Either a return value from the last called callback or `p1`.
*
* @example
* ```js
* Handsontable.hooks.run(hot, 'beforeInit');
* ```
*/
}, {
key: 'run',
value: function run(context, key, p1, p2, p3, p4, p5, p6) {
{
var globalHandlers = this.globalBucket[key];
var index = -1;
var length = globalHandlers ? globalHandlers.length : 0;
if (length) {
// Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC.
while (++index < length) {
if (!globalHandlers[index] || globalHandlers[index].skip) {
/* eslint-disable no-continue */
continue;
}
// performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
var res = globalHandlers[index].call(context, p1, p2, p3, p4, p5, p6);
if (res !== void 0) {
p1 = res;
}
if (globalHandlers[index] && globalHandlers[index].runOnce) {
this.remove(key, globalHandlers[index]);
}
}
}
}
{
var localHandlers = this.getBucket(context)[key];
var _index = -1;
var _length = localHandlers ? localHandlers.length : 0;
if (_length) {
// Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC.
while (++_index < _length) {
if (!localHandlers[_index] || localHandlers[_index].skip) {
/* eslint-disable no-continue */
continue;
}
// performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
var _res = localHandlers[_index].call(context, p1, p2, p3, p4, p5, p6);
if (_res !== void 0) {
p1 = _res;
}
if (localHandlers[_index] && localHandlers[_index].runOnce) {
this.remove(key, localHandlers[_index], context);
}
}
}
}
return p1;
}
/**
* Destroy all listeners connected to the context. If no context is provided, the global listeners will be destroyed.
*
* @param {Object} [context=null] A Handsontable instance.
* @example
* ```js
* // destroy the global listeners
* Handsontable.hooks.destroy();
*
* // destroy the local listeners
* Handsontable.hooks.destroy(hotInstance);
* ```
*/
}, {
key: 'destroy',
value: function destroy() {
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
// eslint-disable-next-line no-return-assign
(0, _object.objectEach)(this.getBucket(context), function (value, key, bucket) {
return bucket[key].length = 0;
});
}
/**
* Registers a hook name (adds it to the list of the known hook names). Used by plugins.
* It is not necessary to call register, but if you use it, your plugin hook will be used returned by
* the `getRegistered` method. (which itself is used in the demo http://docs.handsontable.com/tutorial-callbacks.html).
*
* @param key {String} The hook name.
*
* @example
* ```js
* Handsontable.hooks.register('myHook');
* ```
*/
}, {
key: 'register',
value: function register(key) {
if (!this.isRegistered(key)) {
REGISTERED_HOOKS.push(key);
}
}
/**
* Deregisters a hook name (removes it from the list of known hook names).
*
* @param key {String} Hook name.
*
* @example
* ```js
* Handsontable.hooks.deregister('myHook');
* ```
*/
}, {
key: 'deregister',
value: function deregister(key) {
if (this.isRegistered(key)) {
REGISTERED_HOOKS.splice(REGISTERED_HOOKS.indexOf(key), 1);
}
}
/**
* Returns a boolean depending on if a hook by such name has been registered.
*
* @param key {String} Hook name.
* @returns {Boolean} `true` for success, `false` otherwise.
*
* @example
* ```js
* Handsontable.hooks.isRegistered('beforeInit');
*
* // Results:
* true
* ```
*/
}, {
key: 'isRegistered',
value: function isRegistered(key) {
return REGISTERED_HOOKS.indexOf(key) >= 0;
}
/**
* Returns an array of registered hooks.
*
* @returns {Array} An array of registered hooks.
*
* @example
* ```js
* Handsontable.hooks.getRegistered();
*
* // Results:
* [
* ...
* 'beforeInit',
* 'beforeRender',
* 'beforeSetRangeEnd',
* 'beforeDrawBorders',
* 'beforeChange',
* ...
* ]
* ```
*/
}, {
key: 'getRegistered',
value: function getRegistered() {
return REGISTERED_HOOKS;
}
}]);
return Hooks;
}();
var globalSingleton = new Hooks();
exports.default = Hooks;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getRegisteredRenderers = exports.getRegisteredRendererNames = exports.hasRenderer = exports.getRenderer = exports.registerRenderer = undefined;
var _staticRegister2 = __webpack_require__(48);
var _staticRegister3 = _interopRequireDefault(_staticRegister2);
var _cellDecorator = __webpack_require__(516);
var _cellDecorator2 = _interopRequireDefault(_cellDecorator);
var _autocompleteRenderer = __webpack_require__(517);
var _autocompleteRenderer2 = _interopRequireDefault(_autocompleteRenderer);
var _checkboxRenderer = __webpack_require__(518);
var _checkboxRenderer2 = _interopRequireDefault(_checkboxRenderer);
var _htmlRenderer = __webpack_require__(519);
var _htmlRenderer2 = _interopRequireDefault(_htmlRenderer);
var _numericRenderer = __webpack_require__(520);
var _numericRenderer2 = _interopRequireDefault(_numericRenderer);
var _passwordRenderer = __webpack_require__(522);
var _passwordRenderer2 = _interopRequireDefault(_passwordRenderer);
var _textRenderer = __webpack_require__(523);
var _textRenderer2 = _interopRequireDefault(_textRenderer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _staticRegister = (0, _staticRegister3.default)('renderers'),
register = _staticRegister.register,
getItem = _staticRegister.getItem,
hasItem = _staticRegister.hasItem,
getNames = _staticRegister.getNames,
getValues = _staticRegister.getValues;
register('base', _cellDecorator2.default);
register('autocomplete', _autocompleteRenderer2.default);
register('checkbox', _checkboxRenderer2.default);
register('html', _htmlRenderer2.default);
register('numeric', _numericRenderer2.default);
register('password', _passwordRenderer2.default);
register('text', _textRenderer2.default);
/**
* Retrieve renderer function.
*
* @param {String} name Renderer identification.
* @returns {Function} Returns renderer function.
*/
function _getItem(name) {
if (typeof name === 'function') {
return name;
}
if (!hasItem(name)) {
throw Error('No registered renderer found under "' + name + '" name');
}
return getItem(name);
}
exports.registerRenderer = register;
exports.getRenderer = _getItem;
exports.hasRenderer = hasItem;
exports.getRegisteredRendererNames = getNames;
exports.getRegisteredRenderers = getValues;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(90)('wks');
var uid = __webpack_require__(55);
var Symbol = __webpack_require__(17).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 17 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.KEY_CODES = undefined;
exports.isPrintableChar = isPrintableChar;
exports.isMetaKey = isMetaKey;
exports.isCtrlKey = isCtrlKey;
exports.isCtrlMetaKey = isCtrlMetaKey;
exports.isKey = isKey;
var _array = __webpack_require__(0);
var KEY_CODES = exports.KEY_CODES = {
MOUSE_LEFT: 1,
MOUSE_RIGHT: 3,
MOUSE_MIDDLE: 2,
BACKSPACE: 8,
COMMA: 188,
INSERT: 45,
DELETE: 46,
END: 35,
ENTER: 13,
ESCAPE: 27,
CONTROL: 17,
COMMAND_LEFT: 91,
COMMAND_RIGHT: 93,
COMMAND_FIREFOX: 224,
ALT: 18,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
SPACE: 32,
SHIFT: 16,
CAPS_LOCK: 20,
TAB: 9,
ARROW_RIGHT: 39,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_DOWN: 40,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
A: 65,
X: 88,
C: 67,
V: 86
};
/**
* Returns true if keyCode represents a printable character.
*
* @param {Number} keyCode
* @returns {Boolean}
*/
function isPrintableChar(keyCode) {
return keyCode == 32 || // space
keyCode >= 48 && keyCode <= 57 || // 0-9
keyCode >= 96 && keyCode <= 111 || // numpad
keyCode >= 186 && keyCode <= 192 || // ;=,-./`
keyCode >= 219 && keyCode <= 222 || // []{}\|"'
keyCode >= 226 || // special chars (229 for Asian chars)
keyCode >= 65 && keyCode <= 90; // a-z
}
/**
* @param {Number} keyCode
* @returns {Boolean}
*/
function isMetaKey(keyCode) {
var metaKeys = [KEY_CODES.ARROW_DOWN, KEY_CODES.ARROW_UP, KEY_CODES.ARROW_LEFT, KEY_CODES.ARROW_RIGHT, KEY_CODES.HOME, KEY_CODES.END, KEY_CODES.DELETE, KEY_CODES.BACKSPACE, KEY_CODES.F1, KEY_CODES.F2, KEY_CODES.F3, KEY_CODES.F4, KEY_CODES.F5, KEY_CODES.F6, KEY_CODES.F7, KEY_CODES.F8, KEY_CODES.F9, KEY_CODES.F10, KEY_CODES.F11, KEY_CODES.F12, KEY_CODES.TAB, KEY_CODES.PAGE_DOWN, KEY_CODES.PAGE_UP, KEY_CODES.ENTER, KEY_CODES.ESCAPE, KEY_CODES.SHIFT, KEY_CODES.CAPS_LOCK, KEY_CODES.ALT];
return metaKeys.indexOf(keyCode) !== -1;
}
/**
* Checks if passed key code is ctrl or cmd key. Depends on what OS the code runs it check key code based on
* different meta key codes.
*
* @param {Number} keyCode Key code to check.
* @returns {Boolean}
*/
function isCtrlKey(keyCode) {
var keys = [];
if (window.navigator.platform.includes('Mac')) {
keys.push(KEY_CODES.COMMAND_LEFT, KEY_CODES.COMMAND_RIGHT, KEY_CODES.COMMAND_FIREFOX);
} else {
keys.push(KEY_CODES.CONTROL);
}
return keys.includes(keyCode);
}
/**
* Checks if passed key code is ctrl or cmd key. This helper checks if the key code matches to meta keys
* regardless of the OS on which it is running.
*
* @param {Number} keyCode Key code to check.
* @returns {Boolean}
*/
function isCtrlMetaKey(keyCode) {
return [KEY_CODES.CONTROL, KEY_CODES.COMMAND_LEFT, KEY_CODES.COMMAND_RIGHT, KEY_CODES.COMMAND_FIREFOX].includes(keyCode);
}
/**
* @param {Number} keyCode
* @param {String} baseCode
* @returns {Boolean}
*/
function isKey(keyCode, baseCode) {
var keys = baseCode.split('|');
var result = false;
(0, _array.arrayEach)(keys, function (key) {
if (keyCode === KEY_CODES[key]) {
result = true;
return false;
}
});
return result;
}
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getRegisteredEditors = exports.getRegisteredEditorNames = exports.hasEditor = exports.getEditorInstance = exports.getEditor = exports.registerEditor = undefined;
exports.RegisteredEditor = RegisteredEditor;
exports._getEditorInstance = _getEditorInstance;
var _staticRegister2 = __webpack_require__(48);
var _staticRegister3 = _interopRequireDefault(_staticRegister2);
var _pluginHooks = __webpack_require__(14);
var _pluginHooks2 = _interopRequireDefault(_pluginHooks);
var _baseEditor = __webpack_require__(60);
var _baseEditor2 = _interopRequireDefault(_baseEditor);
var _autocompleteEditor = __webpack_require__(322);
var _autocompleteEditor2 = _interopRequireDefault(_autocompleteEditor);
var _checkboxEditor = __webpack_require__(506);
var _checkboxEditor2 = _interopRequireDefault(_checkboxEditor);
var _dateEditor = __webpack_require__(507);
var _dateEditor2 = _interopRequireDefault(_dateEditor);
var _dropdownEditor = __webpack_require__(512);
var _dropdownEditor2 = _interopRequireDefault(_dropdownEditor);
var _handsontableEditor = __webpack_require__(323);
var _handsontableEditor2 = _interopRequireDefault(_handsontableEditor);
var _numericEditor = __webpack_require__(513);
var _numericEditor2 = _interopRequireDefault(_numericEditor);
var _passwordEditor = __webpack_require__(514);
var _passwordEditor2 = _interopRequireDefault(_passwordEditor);
var _selectEditor = __webpack_require__(515);
var _selectEditor2 = _interopRequireDefault(_selectEditor);
var _textEditor = __webpack_require__(62);
var _textEditor2 = _interopRequireDefault(_textEditor);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
var registeredEditorClasses = new WeakMap();
var _staticRegister = (0, _staticRegister3.default)('editors'),
register = _staticRegister.register,
getItem = _staticRegister.getItem,
hasItem = _staticRegister.hasItem,
getNames = _staticRegister.getNames,
getValues = _staticRegister.getValues;
_register('base', _baseEditor2.default);
_register('autocomplete', _autocompleteEditor2.default);
_register('checkbox', _checkboxEditor2.default);
_register('date', _dateEditor2.default);
_register('dropdown', _dropdownEditor2.default);
_register('handsontable', _handsontableEditor2.default);
_register('numeric', _numericEditor2.default);
_register('password', _passwordEditor2.default);
_register('select', _selectEditor2.default);
_register('text', _textEditor2.default);
function RegisteredEditor(editorClass) {
var instances = {};
var Clazz = editorClass;
this.getConstructor = function () {
return editorClass;
};
this.getInstance = function (hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new Clazz(hotInstance);
}
return instances[hotInstance.guid];
};
_pluginHooks2.default.getSingleton().add('afterDestroy', function () {
instances = {};
});
}
/**
* Returns instance (singleton) of editor class.
*
* @param {String} name Name of an editor under which it has been stored.
* @param {Object} hotInstance Instance of Handsontable.
* @returns {Function} Returns instance of editor.
*/
function _getEditorInstance(name, hotInstance) {
var editor = void 0;
if (typeof name === 'function') {
if (!registeredEditorClasses.get(name)) {
_register(null, name);
}
editor = registeredEditorClasses.get(name);
} else if (typeof name === 'string') {
editor = getItem(name);
} else {
throw Error('Only strings and functions can be passed as "editor" parameter');
}
if (!editor) {
throw Error('No editor registered under name "' + name + '"');
}
return editor.getInstance(hotInstance);
}
/**
* Retrieve editor class.
*
* @param {String} name Editor identification.
* @returns {Function} Returns editor class.
*/
function _getItem(name) {
if (!hasItem(name)) {
throw Error('No registered editor found under "' + name + '" name');
}
return getItem(name).getConstructor();
}
/**
* Register editor class under specified name.
*
* @param {String} name Editor identification.
* @param {Function} editorClass Editor class.
*/
function _register(name, editorClass) {
var editorWrapper = new RegisteredEditor(editorClass);
if (typeof name === 'string') {
register(name, editorWrapper);
}
registeredEditorClasses.set(editorClass, editorWrapper);
}
exports.registerEditor = _register;
exports.getEditor = _getItem;
exports.getEditorInstance = _getEditorInstance;
exports.hasEditor = hasItem;
exports.getRegisteredEditorNames = getNames;
exports.getRegisteredEditors = getValues;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(12);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _array = __webpack_require__(0);
var _object = __webpack_require__(1);
var MIXIN_NAME = 'localHooks';
/**
* Mixin object to extend objects functionality for local hooks.
*
* @type {Object}
*/
var localHooks = {
/**
* Internal hooks storage.
*/
_localHooks: Object.create(null),
/**
* Add hook to the collection.
*
* @param {String} key Hook name.
* @param {Function} callback Hook callback
*/
addLocalHook: function addLocalHook(key, callback) {
if (!this._localHooks[key]) {
this._localHooks[key] = [];
}
this._localHooks[key].push(callback);
},
/**
* Run hooks.
*
* @param {String} key Hook name.
* @param {*} params
*/
runLocalHooks: function runLocalHooks(key) {
var _this = this;
for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
if (this._localHooks[key]) {
(0, _array.arrayEach)(this._localHooks[key], function (callback) {
return callback.apply(_this, params);
});
}
},
/**
* Clear all added hooks.
*/
clearLocalHooks: function clearLocalHooks() {
this._localHooks = {};
}
};
(0, _object.defineGetter)(localHooks, 'MIXIN_NAME', MIXIN_NAME, {
writable: false,
enumerable: false
});
exports.default = localHooks;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(20);
var IE8_DOM_DEFINE = __webpack_require__(164);
var toPrimitive = __webpack_require__(86);
var dP = Object.defineProperty;
exports.f = __webpack_require__(25) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js
//! version : 2.20.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
;(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.moment = factory()
}(this, (function () { 'use strict';
var hookCallback;
function hooks () {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback (callback) {
hookCallback = callback;
}
function isArray(input) {
return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return input != null && Object.prototype.toString.call(input) === '[object Object]';
}
function isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return (Object.getOwnPropertyNames(obj).length === 0);
} else {
var k;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
}
function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}
function map(arr, fn) {
var res = [], i;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function createUTC (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty : false,
unusedTokens : [],
unusedInput : [],
overflow : -2,
charsLeftOver : 0,
nullInput : false,
invalidMonth : null,
invalidFormat : false,
userInvalidated : false,
iso : false,
parsedDateParts : [],
meridiem : null,
rfc2822 : false,
weekdayMismatch : false
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m);
var parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
});
var isNowValid = !isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
isNowValid = isNowValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
}
else {
return isNowValid;
}
}
return m._isValid;
}
function createInvalid (flags) {
var m = createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
}
else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];
function copyConfig(to, from) {
var i, prop, val;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i = 0; i < momentProperties.length; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
var updateInProgress = false;
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (!this.isValid()) {
this._d = new Date(NaN);
}
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment (obj) {
return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
function absFloor (number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
function warn(msg) {
if (hooks.suppressDeprecationWarnings === false &&
(typeof console !== 'undefined') && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
var args = [];
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = '';
if (typeof arguments[i] === 'object') {
arg += '\n[' + i + '] ';
for (var key in arguments[0]) {
arg += key + ': ' + arguments[0][key] + ', ';
}
arg = arg.slice(0, -2); // Remove trailing comma and space
} else {
arg = arguments[i];
}
args.push(arg);
}
warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
function set (config) {
var prop, i;
for (i in config) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
'|' + (/\d{1,2}/).source);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig), prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (hasOwnProp(parentConfig, prop) &&
!hasOwnProp(childConfig, prop) &&
isObject(parentConfig[prop])) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i, res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
};
function calendar (key, mom, now) {
var output = this._calendar[key] || this._calendar['sameElse'];
return isFunction(output) ? output.call(mom, now) : output;
}
var defaultLongDateFormat = {
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
};
function longDateFormat (key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
return val.slice(1);
});
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate () {
return this._invalidDate;
}
var defaultOrdinal = '%d';
var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal (number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
ss : '%d seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
};
function relativeTime (number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return (isFunction(output)) ?
output(number, withoutSuffix, string, isFuture) :
output.replace(/%d/i, number);
}
function pastFuture (diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias (unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [];
for (var u in unitsObj) {
units.push({unit: u, priority: priorities[u]});
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
var formatFunctions = {};
var formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken (token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(func.apply(this, arguments), token);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens), i, length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '', i;
for (i = 0; i < length; i++) {
output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match6 = /[+-]?\d{6}/; // -999999 - 999999
var match1to2 = /\d\d?/; // 0 - 99
var match3to4 = /\d\d\d\d?/; // 999 - 9999
var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
var match1to3 = /\d{1,3}/; // 0 - 999
var match1to4 = /\d{1,4}/; // 0 - 9999
var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
var matchUnsigned = /\d+/; // 0 - inf
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
var regexes = {};
function addRegexToken (token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
return (isStrict && strictRegex) ? strictRegex : regex;
};
}
function getParseRegexForToken (token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}));
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken (token, callback) {
var i, func = callback;
if (typeof token === 'string') {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
for (i = 0; i < token.length; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken (token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
var WEEK = 7;
var WEEKDAY = 8;
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? '' + y : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear () {
return isLeapYear(this.year());
}
function makeGetSet (unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get (mom, unit) {
return mom.isValid() ?
mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}
function set$1 (mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
}
else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}
// MOMENTS
function stringGet (units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet (units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units);
for (var i = 0; i < prioritized.length; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
function mod(n, x) {
return ((n % x) + x) % x;
}
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
function localeMonths (m, format) {
if (!m) {
return isArray(this._months) ? this._months :
this._months['standalone'];
}
return isArray(this._months) ? this._months[m.month()] :
this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
function localeMonthsShort (m, format) {
if (!m) {
return isArray(this._monthsShort) ? this._monthsShort :
this._monthsShort['standalone'];
}
return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse (monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth (mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth (value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, 'Month');
}
}
function getDaysInMonth () {
return daysInMonth(this.year(), this.month());
}
var defaultMonthsShortRegex = matchWord;
function monthsShortRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict ?
this._monthsShortStrictRegex : this._monthsShortRegex;
}
}
var defaultMonthsRegex = matchWord;
function monthsRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict ?
this._monthsStrictRegex : this._monthsRegex;
}
}
function computeMonthsParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [], longPieces = [], mixedPieces = [],
i, mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}
function createDate (y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date = new Date(y, m, d, h, M, s, ms);
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
date.setFullYear(y);
}
return date;
}
function createUTCDate (y) {
var date = new Date(Date.UTC.apply(null, arguments));
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear, resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek, resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
});
// HELPERS
// LOCALES
function localeWeek (mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
};
function localeFirstDayOfWeek () {
return this._week.dow;
}
function localeFirstDayOfYear () {
return this._week.doy;
}
// MOMENTS
function getSetWeek (input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek (input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays (m, format) {
if (!m) {
return isArray(this._weekdays) ? this._weekdays :
this._weekdays['standalone'];
}
return isArray(this._weekdays) ? this._weekdays[m.day()] :
this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
}
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin (m) {
return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse (weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
}
if (!this._weekdaysParse[i]) {
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
var defaultWeekdaysRegex = matchWord;
function weekdaysRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict ?
this._weekdaysStrictRegex : this._weekdaysRegex;
}
}
var defaultWeekdaysShortRegex = matchWord;
function weekdaysShortRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict ?
this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
}
}
var defaultWeekdaysMinRegex = matchWord;
function weekdaysMinRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict ?
this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
}
}
function computeWeekdaysParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
i, mom, minp, shortp, longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = this.weekdaysMin(mom, '');
shortp = this.weekdaysShort(mom, '');
longp = this.weekdays(mom, '');
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 7; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);
addFormatToken('hmm', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken('hmmss', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2);
});
addFormatToken('Hmm', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken('Hmmss', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2);
});
function meridiem (token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem (isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('k', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
var pos1 = input.length - 4;
var pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
var pos1 = input.length - 4;
var pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM (input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return ((input + '').toLowerCase().charAt(0) === 'p');
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
function localeMeridiem (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
// MOMENTS
// Setting the hour should keep the time, because the user explicitly
// specified which hour he wants. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
var getSetHour = makeGetSet('Hours', true);
// months
// week
// weekdays
// meridiem
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse
};
// internal storage for locale config files
var locales = {};
var localeFamilies = {};
var globalLocale;
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0, j, next, locale, split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return null;
}
function loadLocale(name) {
var oldLocale = null;
// TODO: Find a better way to register and load all the locales in Node
if (!locales[name] && (typeof module !== 'undefined') &&
module && module.exports) {
try {
oldLocale = globalLocale._abbr;
var aliasedRequire = require;
__webpack_require__(500)("./" + name);
getSetGlobalLocale(oldLocale);
} catch (e) {}
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale (key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = getLocale(key);
}
else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
}
}
return globalLocale._abbr;
}
function defineLocale (name, config) {
if (config !== null) {
var parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple('defineLocaleOverride',
'use moment.updateLocale(localeName, config) to change ' +
'an existing locale. moment.defineLocale(localeName, ' +
'config) should only be used for creating a new locale ' +
'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
if (!localeFamilies[config.parentLocale]) {
localeFamilies[config.parentLocale] = [];
}
localeFamilies[config.parentLocale].push({
name: name,
config: config
});
return null;
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
if (localeFamilies[name]) {
localeFamilies[name].forEach(function (x) {
defineLocale(x.name, x.config);
});
}
// backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale, tmpLocale, parentConfig = baseConfig;
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
// backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function listLocales() {
return keys(locales);
}
function checkOverflow (m) {
var overflow;
var a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
-1;
if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(hooks.now());
if (config._useUTC) {
return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
}
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray (config) {
var i, date, input = [], currentDate, expectedWeekday, yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
// check for mismatching day of week
if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
getParsingFlags(config).weekdayMismatch = true;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
var curWeek = weekOfYear(createLocal(), dow, doy);
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
// Default to current week.
week = defaults(w.w, curWeek.week);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from begining of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to begining of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
var isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
['GGGG-[W]WW', /\d{4}-W\d\d/, false],
['YYYY-DDD', /\d{4}-\d{3}/],
['YYYY-MM', /\d{4}-\d\d/, false],
['YYYYYYMMDD', /[+-]\d{10}/],
['YYYYMMDD', /\d{8}/],
// YYYYMM is NOT allowed by the standard
['GGGG[W]WWE', /\d{4}W\d{3}/],
['GGGG[W]WW', /\d{4}W\d{2}/, false],
['YYYYDDD', /\d{7}/]
];
// iso time formats and regexes
var isoTimes = [
['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
['HH:mm:ss', /\d\d:\d\d:\d\d/],
['HH:mm', /\d\d:\d\d/],
['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
['HHmmss', /\d\d\d\d\d\d/],
['HHmm', /\d\d\d\d/],
['HH', /\d\d/]
];
var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
// date from iso format
function configFromISO(config) {
var i, l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime, dateFormat, timeFormat, tzFormat;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDates.length; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimes.length; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = 'Z';
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
var result = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10)
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim();
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
var obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60
};
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10);
var m = hm % 100, h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i));
if (match) {
var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
}
// date from iso format or fallback
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
hooks.createFromInputFallback = deprecate(
'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
'discouraged and will be removed in an upcoming major release. Please refer to ' +
'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i, parsedInput, tokens, token, skipped,
stringLength = string.length,
totalParsedInputLength = 0;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
// console.log('token', token, 'parsedInput', parsedInput,
// 'regex', getParseRegexForToken(token, config));
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
}
else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
}
else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (config._a[HOUR] <= 12 &&
getParsingFlags(config).bigHour === true &&
config._a[HOUR] > 0) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap (locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore;
if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (!isValid(tempConfig)) {
continue;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i);
config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
return obj && parseInt(obj, 10);
});
configFromArray(config);
}
function createFromConfig (config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig (config) {
var input = config._i,
format = config._f;
config._locale = config._locale || getLocale(config._l);
if (input === null || (format === undefined && input === '')) {
return createInvalid({nullInput: true});
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isDate(input)) {
config._d = input;
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
// from milliseconds
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC (input, format, locale, strict, isUTC) {
var c = {};
if (locale === true || locale === false) {
strict = locale;
locale = undefined;
}
if ((isObject(input) && isObjectEmpty(input)) ||
(isArray(input) && input.length === 0)) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function createLocal (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
);
var prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
var now = function () {
return Date.now ? Date.now() : +(new Date());
};
var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
function isDurationValid(m) {
for (var key in m) {
if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
return false;
}
}
var unitHasDecimal = false;
for (var i = 0; i < ordering.length; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration (duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// representation for dateAddRemove
this._milliseconds = +milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days +
weeks * 7;
// It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months +
quarters * 3 +
years * 12;
this._data = {};
this._locale = getLocale();
this._bubble();
}
function isDuration (obj) {
return obj instanceof Duration;
}
function absRound (number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// FORMATTING
function offset (token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset();
var sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = (string || '').match(matcher);
if (matches === null) {
return null;
}
var chunk = matches[matches.length - 1] || [];
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
var minutes = +(parts[1] * 60) + toInt(parts[2]);
return minutes === 0 ?
0 :
parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
}
function getDateOffset (m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset (input, keepLocalTime, keepMinutes) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(matchShortOffset, input);
if (input === null) {
return this;
}
} else if (Math.abs(input) < 16 && !keepMinutes) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(this, createDuration(input - offset, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone (input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC (keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal (keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset () {
if (this._tzm != null) {
this.utcOffset(this._tzm, false, true);
} else if (typeof this._i === 'string') {
var tZone = offsetFromString(matchOffset, this._i);
if (tZone != null) {
this.utcOffset(tZone);
}
else {
this.utcOffset(0, true);
}
}
return this;
}
function hasAlignedHourOffset (input) {
if (!this.isValid()) {
return false;
}
input = input ? createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime () {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted () {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {};
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
this._isDSTShifted = this.isValid() &&
compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal () {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset () {
return this.isValid() ? this._isUTC : false;
}
function isUtc () {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration (input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms : input._milliseconds,
d : input._days,
M : input._months
};
} else if (isNumber(input)) {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : 0,
d : toInt(match[DATE]) * sign,
h : toInt(match[HOUR]) * sign,
m : toInt(match[MINUTE]) * sign,
s : toInt(match[SECOND]) * sign,
ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
};
} else if (!!(match = isoRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1;
duration = {
y : parseIso(match[2], sign),
M : parseIso(match[3], sign),
w : parseIso(match[4], sign),
d : parseIso(match[5], sign),
h : parseIso(match[6], sign),
m : parseIso(match[7], sign),
s : parseIso(match[8], sign)
};
} else if (duration == null) {// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
}
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;
function parseIso (inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return {milliseconds: 0, months: 0};
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
tmp = val; val = period; period = tmp;
}
val = typeof val === 'string' ? +val : val;
dur = createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract (mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months) {
setMonth(mom, get(mom, 'Month') + months * isAdding);
}
if (days) {
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (updateOffset) {
hooks.updateOffset(mom, days || months);
}
}
var add = createAdder(1, 'add');
var subtract = createAdder(-1, 'subtract');
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, 'days', true);
return diff < -6 ? 'sameElse' :
diff < -1 ? 'lastWeek' :
diff < 0 ? 'lastDay' :
diff < 1 ? 'sameDay' :
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : 'sameElse';
}
function calendar$1 (time, formats) {
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
format = hooks.calendarFormat(this, sod) || 'sameElse';
var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}
function clone () {
return new Moment(this);
}
function isAfter (input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
if (units === 'millisecond') {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore (input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
if (units === 'millisecond') {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween (from, to, units, inclusivity) {
inclusivity = inclusivity || '()';
return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
(inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
}
function isSame (input, units) {
var localInput = isMoment(input) ? input : createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units || 'millisecond');
if (units === 'millisecond') {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
}
}
function isSameOrAfter (input, units) {
return this.isSame(input, units) || this.isAfter(input,units);
}
function isSameOrBefore (input, units) {
return this.isSame(input, units) || this.isBefore(input,units);
}
function diff (input, units, asFloat) {
var that,
zoneDelta,
delta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case 'year': output = monthDiff(this, that) / 12; break;
case 'month': output = monthDiff(this, that); break;
case 'quarter': output = monthDiff(this, that) / 3; break;
case 'second': output = (this - that) / 1e3; break; // 1000
case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
default: output = this - that;
}
return asFloat ? output : absFloor(output);
}
function monthDiff (a, b) {
// difference in months
var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2, adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
function toString () {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function toISOString(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true;
var m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this._d.valueOf()).toISOString().replace('Z', formatMoment(m, 'Z'));
}
}
return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
/**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/
function inspect () {
if (!this.isValid()) {
return 'moment.invalid(/* ' + this._i + ' */)';
}
var func = 'moment';
var zone = '';
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
zone = 'Z';
}
var prefix = '[' + func + '("]';
var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
var datetime = '-MM-DD[T]HH:mm:ss.SSS';
var suffix = zone + '[")]';
return this.format(prefix + year + datetime + suffix);
}
function format (inputString) {
if (!inputString) {
inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from (time, withoutSuffix) {
if (this.isValid() &&
((isMoment(time) && time.isValid()) ||
createLocal(time).isValid())) {
return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow (withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}
function to (time, withoutSuffix) {
if (this.isValid() &&
((isMoment(time) && time.isValid()) ||
createLocal(time).isValid())) {
return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow (withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale (key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData () {
return this._locale;
}
function startOf (units) {
units = normalizeUnits(units);
// the following switch intentionally omits break keywords
// to utilize falling through the cases.
switch (units) {
case 'year':
this.month(0);
/* falls through */
case 'quarter':
case 'month':
this.date(1);
/* falls through */
case 'week':
case 'isoWeek':
case 'day':
case 'date':
this.hours(0);
/* falls through */
case 'hour':
this.minutes(0);
/* falls through */
case 'minute':
this.seconds(0);
/* falls through */
case 'second':
this.milliseconds(0);
}
// weeks are a special case
if (units === 'week') {
this.weekday(0);
}
if (units === 'isoWeek') {
this.isoWeekday(1);
}
// quarters are also special
if (units === 'quarter') {
this.month(Math.floor(this.month() / 3) * 3);
}
return this;
}
function endOf (units) {
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond') {
return this;
}
// 'date' is an alias for 'day', so it should be considered as such.
if (units === 'date') {
units = 'day';
}
return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
}
function valueOf () {
return this._d.valueOf() - ((this._offset || 0) * 60000);
}
function unix () {
return Math.floor(this.valueOf() / 1000);
}
function toDate () {
return new Date(this.valueOf());
}
function toArray () {
var m = this;
return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}
function toObject () {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds()
};
}
function toJSON () {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function isValid$2 () {
return isValid(this);
}
function parsingFlags () {
return extend({}, getParsingFlags(this));
}
function invalidAt () {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict
};
}
// FORMATTING
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken (token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
});
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear (input) {
return getSetWeekYearHelper.call(this,
input,
this.week(),
this.weekday(),
this.localeData()._week.dow,
this.localeData()._week.doy);
}
function getSetISOWeekYear (input) {
return getSetWeekYearHelper.call(this,
input, this.isoWeek(), this.isoWeekday(), 1, 4);
}
function getISOWeeksInYear () {
return weeksInYear(this.year(), 1, 4);
}
function getWeeksInYear () {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter (input) {
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIOROITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ?
(locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', true);
// FORMATTING
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear (input) {
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
}
// FORMATTING
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', false);
// FORMATTING
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', false);
// FORMATTING
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
// MOMENTS
var getSetMillisecond = makeGetSet('Milliseconds', false);
// FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
// MOMENTS
function getZoneAbbr () {
return this._isUTC ? 'UTC' : '';
}
function getZoneName () {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var proto = Moment.prototype;
proto.add = add;
proto.calendar = calendar$1;
proto.clone = clone;
proto.diff = diff;
proto.endOf = endOf;
proto.format = format;
proto.from = from;
proto.fromNow = fromNow;
proto.to = to;
proto.toNow = toNow;
proto.get = stringGet;
proto.invalidAt = invalidAt;
proto.isAfter = isAfter;
proto.isBefore = isBefore;
proto.isBetween = isBetween;
proto.isSame = isSame;
proto.isSameOrAfter = isSameOrAfter;
proto.isSameOrBefore = isSameOrBefore;
proto.isValid = isValid$2;
proto.lang = lang;
proto.locale = locale;
proto.localeData = localeData;
proto.max = prototypeMax;
proto.min = prototypeMin;
proto.parsingFlags = parsingFlags;
proto.set = stringSet;
proto.startOf = startOf;
proto.subtract = subtract;
proto.toArray = toArray;
proto.toObject = toObject;
proto.toDate = toDate;
proto.toISOString = toISOString;
proto.inspect = inspect;
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
// Year
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
// Week Year
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
// Quarter
proto.quarter = proto.quarters = getSetQuarter;
// Month
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
// Week
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.isoWeeksInYear = getISOWeeksInYear;
// Day
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
// Hour
proto.hour = proto.hours = getSetHour;
// Minute
proto.minute = proto.minutes = getSetMinute;
// Second
proto.second = proto.seconds = getSetSecond;
// Millisecond
proto.millisecond = proto.milliseconds = getSetMillisecond;
// Offset
proto.utcOffset = getSetOffset;
proto.utc = setOffsetToUTC;
proto.local = setOffsetToLocal;
proto.parseZone = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST = isDaylightSavingTime;
proto.isLocal = isLocal;
proto.isUtcOffset = isUtcOffset;
proto.isUtc = isUtc;
proto.isUTC = isUtc;
// Timezone
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
// Deprecations
proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
function createUnix (input) {
return createLocal(input * 1000);
}
function createInZone () {
return createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat (string) {
return string;
}
var proto$1 = Locale.prototype;
proto$1.calendar = calendar;
proto$1.longDateFormat = longDateFormat;
proto$1.invalidDate = invalidDate;
proto$1.ordinal = ordinal;
proto$1.preparse = preParsePostFormat;
proto$1.postformat = preParsePostFormat;
proto$1.relativeTime = relativeTime;
proto$1.pastFuture = pastFuture;
proto$1.set = set;
// Month
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
// Week
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
// Day of Week
proto$1.weekdays = localeWeekdays;
proto$1.weekdaysMin = localeWeekdaysMin;
proto$1.weekdaysShort = localeWeekdaysShort;
proto$1.weekdaysParse = localeWeekdaysParse;
proto$1.weekdaysRegex = weekdaysRegex;
proto$1.weekdaysShortRegex = weekdaysShortRegex;
proto$1.weekdaysMinRegex = weekdaysMinRegex;
// Hours
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;
function get$1 (format, index, field, setter) {
var locale = getLocale();
var utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl (format, index, field) {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return get$1(format, index, field, 'month');
}
var i;
var out = [];
for (i = 0; i < 12; i++) {
out[i] = get$1(format, i, field, 'month');
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl (localeSorted, format, index, field) {
if (typeof localeSorted === 'boolean') {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
}
var locale = getLocale(),
shift = localeSorted ? locale._week.dow : 0;
if (index != null) {
return get$1(format, (index + shift) % 7, field, 'day');
}
var i;
var out = [];
for (i = 0; i < 7; i++) {
out[i] = get$1(format, (i + shift) % 7, field, 'day');
}
return out;
}
function listMonths (format, index) {
return listMonthsImpl(format, index, 'months');
}
function listMonthsShort (format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}
function listWeekdays (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}
function listWeekdaysShort (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}
function listWeekdaysMin (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}
getSetGlobalLocale('en', {
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal : function (number) {
var b = number % 10,
output = (toInt(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
// Side effect imports
hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
var mathAbs = Math.abs;
function abs () {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function addSubtract$1 (duration, input, value, direction) {
var other = createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function add$1 (input, value) {
return addSubtract$1(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1 (input, value) {
return addSubtract$1(this, input, value, -1);
}
function absCeil (number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble () {
var milliseconds = this._milliseconds;
var days = this._days;
var months = this._months;
var data = this._data;
var seconds, minutes, hours, years, monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0))) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths (days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return days * 4800 / 146097;
}
function monthsToDays (months) {
// the reverse of daysToMonths
return months * 146097 / 4800;
}
function as (units) {
if (!this.isValid()) {
return NaN;
}
var days;
var months;
var milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
return units === 'month' ? months : months / 12;
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week' : return days / 7 + milliseconds / 6048e5;
case 'day' : return days + milliseconds / 864e5;
case 'hour' : return days * 24 + milliseconds / 36e5;
case 'minute' : return days * 1440 + milliseconds / 6e4;
case 'second' : return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
default: throw new Error('Unknown unit ' + units);
}
}
}
// TODO: Use this.as('ms')?
function valueOf$1 () {
if (!this.isValid()) {
return NaN;
}
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs (alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms');
var asSeconds = makeAs('s');
var asMinutes = makeAs('m');
var asHours = makeAs('h');
var asDays = makeAs('d');
var asWeeks = makeAs('w');
var asMonths = makeAs('M');
var asYears = makeAs('y');
function clone$1 () {
return createDuration(this);
}
function get$2 (units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + 's']() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter('milliseconds');
var seconds = makeGetter('seconds');
var minutes = makeGetter('minutes');
var hours = makeGetter('hours');
var days = makeGetter('days');
var months = makeGetter('months');
var years = makeGetter('years');
function weeks () {
return absFloor(this.days() / 7);
}
var round = Math.round;
var thresholds = {
ss: 44, // a few seconds to seconds
s : 45, // seconds to minute
m : 45, // minutes to hour
h : 22, // hours to day
d : 26, // days to month
M : 11 // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
var duration = createDuration(posNegDuration).abs();
var seconds = round(duration.as('s'));
var minutes = round(duration.as('m'));
var hours = round(duration.as('h'));
var days = round(duration.as('d'));
var months = round(duration.as('M'));
var years = round(duration.as('y'));
var a = seconds <= thresholds.ss && ['s', seconds] ||
seconds < thresholds.s && ['ss', seconds] ||
minutes <= 1 && ['m'] ||
minutes < thresholds.m && ['mm', minutes] ||
hours <= 1 && ['h'] ||
hours < thresholds.h && ['hh', hours] ||
days <= 1 && ['d'] ||
days < thresholds.d && ['dd', days] ||
months <= 1 && ['M'] ||
months < thresholds.M && ['MM', months] ||
years <= 1 && ['y'] || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding (roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof(roundingFunction) === 'function') {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold (threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
if (threshold === 's') {
thresholds.ss = limit - 1;
}
return true;
}
function humanize (withSuffix) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var locale = this.localeData();
var output = relativeTime$1(this, !withSuffix, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var abs$1 = Math.abs;
function sign(x) {
return ((x > 0) - (x < 0)) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var seconds = abs$1(this._milliseconds) / 1000;
var days = abs$1(this._days);
var months = abs$1(this._months);
var minutes, hours, years;
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
var Y = years;
var M = months;
var D = days;
var h = hours;
var m = minutes;
var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
var total = this.asSeconds();
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
var totalSign = total < 0 ? '-' : '';
var ymSign = sign(this._months) !== sign(total) ? '-' : '';
var daysSign = sign(this._days) !== sign(total) ? '-' : '';
var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return totalSign + 'P' +
(Y ? ymSign + Y + 'Y' : '') +
(M ? ymSign + M + 'M' : '') +
(D ? daysSign + D + 'D' : '') +
((h || m || s) ? 'T' : '') +
(h ? hmsSign + h + 'H' : '') +
(m ? hmsSign + m + 'M' : '') +
(s ? hmsSign + s + 'S' : '');
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
proto$2.abs = abs;
proto$2.add = add$1;
proto$2.subtract = subtract$1;
proto$2.as = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds = asSeconds;
proto$2.asMinutes = asMinutes;
proto$2.asHours = asHours;
proto$2.asDays = asDays;
proto$2.asWeeks = asWeeks;
proto$2.asMonths = asMonths;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
proto$2.get = get$2;
proto$2.milliseconds = milliseconds;
proto$2.seconds = seconds;
proto$2.minutes = minutes;
proto$2.hours = hours;
proto$2.days = days;
proto$2.weeks = weeks;
proto$2.months = months;
proto$2.years = years;
proto$2.humanize = humanize;
proto$2.toISOString = toISOString$1;
proto$2.toString = toISOString$1;
proto$2.toJSON = toISOString$1;
proto$2.locale = locale;
proto$2.localeData = localeData;
// Deprecations
proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
proto$2.lang = lang;
// Side effect imports
// FORMATTING
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
// PARSING
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
// Side effect imports
hooks.version = '2.20.1';
setHookCallback(createLocal);
hooks.fn = proto;
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
hooks.prototype = proto;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', //
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', //
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', //
DATE: 'YYYY-MM-DD', //
TIME: 'HH:mm', //
TIME_SECONDS: 'HH:mm:ss', //
TIME_MS: 'HH:mm:ss.SSS', //
WEEK: 'YYYY-[W]WW', //
MONTH: 'YYYY-MM' //
};
return hooks;
})));
/*** EXPORTS FROM exports-to-window-loader ***/
window['moment'] = __webpack_require__(23);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(194)(module)))
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.normalizeSelection = normalizeSelection;
exports.isSeparator = isSeparator;
exports.hasSubMenu = hasSubMenu;
exports.isDisabled = isDisabled;
exports.isSelectionDisabled = isSelectionDisabled;
exports.getValidSelection = getValidSelection;
exports.prepareVerticalAlignClass = prepareVerticalAlignClass;
exports.prepareHorizontalAlignClass = prepareHorizontalAlignClass;
exports.getAlignmentClasses = getAlignmentClasses;
exports.align = align;
exports.checkSelectionConsistency = checkSelectionConsistency;
exports.markLabelAsSelected = markLabelAsSelected;
exports.isItemHidden = isItemHidden;
exports.filterSeparators = filterSeparators;
var _array = __webpack_require__(0);
var _number = __webpack_require__(4);
var _element = __webpack_require__(2);
var _separator = __webpack_require__(156);
function normalizeSelection(selRanges) {
return (0, _array.arrayMap)(selRanges, function (range) {
return {
start: range.getTopLeftCorner(),
end: range.getBottomRightCorner()
};
});
}
function isSeparator(cell) {
return (0, _element.hasClass)(cell, 'htSeparator');
}
function hasSubMenu(cell) {
return (0, _element.hasClass)(cell, 'htSubmenu');
}
function isDisabled(cell) {
return (0, _element.hasClass)(cell, 'htDisabled');
}
function isSelectionDisabled(cell) {
return (0, _element.hasClass)(cell, 'htSelectionDisabled');
}
function getValidSelection(hot) {
var selected = hot.getSelected();
if (!selected) {
return null;
}
if (selected[0] < 0) {
return null;
}
return selected;
}
function prepareVerticalAlignClass(className, alignment) {
if (className.indexOf(alignment) != -1) {
return className;
}
className = className.replace('htTop', '').replace('htMiddle', '').replace('htBottom', '').replace(' ', '');
className += ' ' + alignment;
return className;
}
function prepareHorizontalAlignClass(className, alignment) {
if (className.indexOf(alignment) != -1) {
return className;
}
className = className.replace('htLeft', '').replace('htCenter', '').replace('htRight', '').replace('htJustify', '').replace(' ', '');
className += ' ' + alignment;
return className;
}
function getAlignmentClasses(ranges, callback) {
var classes = {};
(0, _array.arrayEach)(ranges, function (_ref) {
var from = _ref.from,
to = _ref.to;
for (var row = from.row; row <= to.row; row++) {
for (var col = from.col; col <= to.col; col++) {
if (!classes[row]) {
classes[row] = [];
}
classes[row][col] = callback(row, col);
}
}
});
return classes;
}
function align(ranges, type, alignment, cellDescriptor, propertySetter) {
(0, _array.arrayEach)(ranges, function (_ref2) {
var from = _ref2.from,
to = _ref2.to;
if (from.row == to.row && from.col == to.col) {
applyAlignClassName(from.row, from.col, type, alignment, cellDescriptor, propertySetter);
} else {
for (var row = from.row; row <= to.row; row++) {
for (var col = from.col; col <= to.col; col++) {
applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter);
}
}
}
});
}
function applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter) {
var cellMeta = cellDescriptor(row, col);
var className = alignment;
if (cellMeta.className) {
if (type === 'vertical') {
className = prepareVerticalAlignClass(cellMeta.className, alignment);
} else {
className = prepareHorizontalAlignClass(cellMeta.className, alignment);
}
}
propertySetter(row, col, 'className', className);
}
function checkSelectionConsistency(ranges, comparator) {
var result = false;
if (Array.isArray(ranges)) {
(0, _array.arrayEach)(ranges, function (range) {
range.forAll(function (row, col) {
if (comparator(row, col)) {
result = true;
return false;
}
});
return result;
});
}
return result;
}
function markLabelAsSelected(label) {
// workaround for https://github.com/handsontable/handsontable/issues/1946
return '' + String.fromCharCode(10003) + '' + label;
}
function isItemHidden(item, instance) {
return !item.hidden || !(typeof item.hidden == 'function' && item.hidden.call(instance));
}
function shiftSeparators(items, separator) {
var result = items.slice(0);
for (var i = 0; i < result.length;) {
if (result[i].name === separator) {
result.shift();
} else {
break;
}
}
return result;
}
function popSeparators(items, separator) {
var result = items.slice(0);
result.reverse();
result = shiftSeparators(result, separator);
result.reverse();
return result;
}
function removeDuplicatedSeparators(items) {
var result = [];
(0, _array.arrayEach)(items, function (value, index) {
if (index > 0) {
if (result[result.length - 1].name !== value.name) {
result.push(value);
}
} else {
result.push(value);
}
});
return result;
}
function filterSeparators(items) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _separator.KEY;
var result = items.slice(0);
result = shiftSeparators(result, separator);
result = popSeparators(result, separator);
result = removeDuplicatedSeparators(result);
return result;
}
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(26)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 26 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(88);
var defined = __webpack_require__(47);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(68);
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(5);
var core = __webpack_require__(50);
var fails = __webpack_require__(26);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _object = __webpack_require__(1);
var _array = __webpack_require__(0);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _core = __webpack_require__(193);
var _core2 = _interopRequireDefault(_core);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var registeredOverlays = {};
/**
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
* and (optionally) implements behavior needed for native horizontal and vertical scrolling.
*
* @class Overlay
*/
var Overlay = function () {
_createClass(Overlay, null, [{
key: 'registerOverlay',
/**
* Register overlay class.
*
* @param {String} type Overlay type, one of the CLONE_TYPES value
* @param {Overlay} overlayClass Overlay class extended from base overlay class {@link Overlay}
*/
value: function registerOverlay(type, overlayClass) {
if (Overlay.CLONE_TYPES.indexOf(type) === -1) {
throw new Error('Unsupported overlay (' + type + ').');
}
registeredOverlays[type] = overlayClass;
}
/**
* Create new instance of overlay type.
*
* @param {String} type Overlay type, one of the CLONE_TYPES value
* @param {Walkontable} wot Walkontable instance
*/
}, {
key: 'createOverlay',
value: function createOverlay(type, wot) {
return new registeredOverlays[type](wot);
}
/**
* Check if specified overlay was registered.
*
* @param {String} type Overlay type, one of the CLONE_TYPES value
* @returns {Boolean}
*/
}, {
key: 'hasOverlay',
value: function hasOverlay(type) {
return registeredOverlays[type] !== void 0;
}
/**
* Checks if overlay object (`overlay`) is instance of overlay type (`type`).
*
* @param {Overlay} overlay Overlay object
* @param {String} type Overlay type, one of the CLONE_TYPES value
* @returns {Boolean}
*/
}, {
key: 'isOverlayTypeOf',
value: function isOverlayTypeOf(overlay, type) {
if (!overlay || !registeredOverlays[type]) {
return false;
}
return overlay instanceof registeredOverlays[type];
}
/**
* @param {Walkontable} wotInstance
*/
}, {
key: 'CLONE_TOP',
/**
* @type {String}
*/
get: function get() {
return 'top';
}
/**
* @type {String}
*/
}, {
key: 'CLONE_BOTTOM',
get: function get() {
return 'bottom';
}
/**
* @type {String}
*/
}, {
key: 'CLONE_LEFT',
get: function get() {
return 'left';
}
/**
* @type {String}
*/
}, {
key: 'CLONE_TOP_LEFT_CORNER',
get: function get() {
return 'top_left_corner';
}
/**
* @type {String}
*/
}, {
key: 'CLONE_BOTTOM_LEFT_CORNER',
get: function get() {
return 'bottom_left_corner';
}
/**
* @type {String}
*/
}, {
key: 'CLONE_DEBUG',
get: function get() {
return 'debug';
}
/**
* List of all availables clone types
*
* @type {Array}
*/
}, {
key: 'CLONE_TYPES',
get: function get() {
return [Overlay.CLONE_TOP, Overlay.CLONE_BOTTOM, Overlay.CLONE_LEFT, Overlay.CLONE_TOP_LEFT_CORNER, Overlay.CLONE_BOTTOM_LEFT_CORNER, Overlay.CLONE_DEBUG];
}
}]);
function Overlay(wotInstance) {
_classCallCheck(this, Overlay);
(0, _object.defineGetter)(this, 'wot', wotInstance, {
writable: false
});
// legacy support, deprecated in the future
this.instance = this.wot;
this.type = '';
this.mainTableScrollableElement = null;
this.TABLE = this.wot.wtTable.TABLE;
this.hider = this.wot.wtTable.hider;
this.spreader = this.wot.wtTable.spreader;
this.holder = this.wot.wtTable.holder;
this.wtRootElement = this.wot.wtTable.wtRootElement;
this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode);
this.areElementSizesAdjusted = false;
this.updateStateOfRendering();
}
/**
* Update internal state of object with an information about the need of full rendering of the overlay.
*
* @returns {Boolean} Returns `true` if the state has changed since the last check.
*/
_createClass(Overlay, [{
key: 'updateStateOfRendering',
value: function updateStateOfRendering() {
var previousState = this.needFullRender;
this.needFullRender = this.shouldBeRendered();
var changed = previousState !== this.needFullRender;
if (changed && !this.needFullRender) {
this.reset();
}
return changed;
}
/**
* Checks if overlay should be fully rendered
*
* @returns {Boolean}
*/
}, {
key: 'shouldBeRendered',
value: function shouldBeRendered() {
return true;
}
/**
* Update the trimming container.
*/
}, {
key: 'updateTrimmingContainer',
value: function updateTrimmingContainer() {
this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode);
}
/**
* Update the main scrollable element.
*/
}, {
key: 'updateMainScrollableElement',
value: function updateMainScrollableElement() {
this.mainTableScrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
}
/**
* Make a clone of table for overlay
*
* @param {String} direction Can be `Overlay.CLONE_TOP`, `Overlay.CLONE_LEFT`,
* `Overlay.CLONE_TOP_LEFT_CORNER`, `Overlay.CLONE_DEBUG`
* @returns {Walkontable}
*/
}, {
key: 'makeClone',
value: function makeClone(direction) {
if (Overlay.CLONE_TYPES.indexOf(direction) === -1) {
throw new Error('Clone type "' + direction + '" is not supported.');
}
var clone = document.createElement('DIV');
var clonedTable = document.createElement('TABLE');
clone.className = 'ht_clone_' + direction + ' handsontable';
clone.style.position = 'absolute';
clone.style.top = 0;
clone.style.left = 0;
clone.style.overflow = 'hidden';
clonedTable.className = this.wot.wtTable.TABLE.className;
clone.appendChild(clonedTable);
this.type = direction;
this.wot.wtTable.wtRootElement.parentNode.appendChild(clone);
var preventOverflow = this.wot.getSetting('preventOverflow');
if (preventOverflow === true || preventOverflow === 'horizontal' && this.type === Overlay.CLONE_TOP || preventOverflow === 'vertical' && this.type === Overlay.CLONE_LEFT) {
this.mainTableScrollableElement = window;
} else {
this.mainTableScrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
}
return new _core2.default({
cloneSource: this.wot,
cloneOverlay: this,
table: clonedTable
});
}
/**
* Refresh/Redraw overlay
*
* @param {Boolean} [fastDraw=false]
*/
}, {
key: 'refresh',
value: function refresh() {
var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
// When hot settings are changed we allow to refresh overlay once before blocking
var nextCycleRenderFlag = this.shouldBeRendered();
if (this.clone && (this.needFullRender || nextCycleRenderFlag)) {
this.clone.draw(fastDraw);
}
this.needFullRender = nextCycleRenderFlag;
}
/**
* Reset overlay styles to initial values.
*/
}, {
key: 'reset',
value: function reset() {
if (!this.clone) {
return;
}
var holder = this.clone.wtTable.holder;
var hider = this.clone.wtTable.hider;
var holderStyle = holder.style;
var hidderStyle = hider.style;
var rootStyle = holder.parentNode.style;
(0, _array.arrayEach)([holderStyle, hidderStyle, rootStyle], function (style) {
style.width = '';
style.height = '';
});
}
/**
* Destroy overlay instance
*/
}, {
key: 'destroy',
value: function destroy() {
new _eventManager2.default(this.clone).destroy();
}
}]);
return Overlay;
}();
exports.default = Overlay;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.toUpperCaseFirst = toUpperCaseFirst;
exports.equalsIgnoreCase = equalsIgnoreCase;
exports.randomString = randomString;
exports.isPercentValue = isPercentValue;
exports.substitute = substitute;
exports.stripTags = stripTags;
var _mixed = __webpack_require__(13);
var _number = __webpack_require__(4);
/**
* Convert string to upper case first letter.
*
* @param {String} string String to convert.
* @returns {String}
*/
function toUpperCaseFirst(string) {
return string[0].toUpperCase() + string.substr(1);
}
/**
* Compare strings case insensitively.
*
* @param {...String} strings Strings to compare.
* @returns {Boolean}
*/
function equalsIgnoreCase() {
var unique = [];
for (var _len = arguments.length, strings = Array(_len), _key = 0; _key < _len; _key++) {
strings[_key] = arguments[_key];
}
var length = strings.length;
while (length--) {
var string = (0, _mixed.stringify)(strings[length]).toLowerCase();
if (unique.indexOf(string) === -1) {
unique.push(string);
}
}
return unique.length === 1;
}
/**
* Generates a random hex string. Used as namespace for Handsontable instance events.
*
* @return {String} Returns 16-long character random string (eq. `'92b1bfc74ec4'`).
*/
function randomString() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + s4() + s4();
}
/**
* Checks if value is valid percent.
*
* @param {String} value
* @returns {Boolean}
*/
function isPercentValue(value) {
return (/^([0-9][0-9]?%$)|(^100%$)/.test(value)
);
}
/**
* Substitute strings placed beetwen square brackets into value defined in `variables` object. String names defined in
* square brackets must be the same as property name of `variables` object.
*
* @param {String} template Template string.
* @param {Object} variables Object which contains all available values which can be injected into template.
* @returns {String}
*/
function substitute(template) {
var variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return ('' + template).replace(/(?:\\)?\[([^[\]]+)]/g, function (match, name) {
if (match.charAt(0) === '\\') {
return match.substr(1, match.length - 1);
}
return variables[name] === void 0 ? '' : variables[name];
});
}
var STRIP_TAGS_REGEX = /<\/?\w+\/?>|<\w+[\s|/][^>]*>/gi;
/**
* Strip any HTML tag from the string.
*
* @param {String} string String to cut HTML from.
* @return {String}
*/
function stripTags(string) {
string += '';
return string.replace(STRIP_TAGS_REGEX, '');
}
/***/ }),
/* 32 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.isIE8 = isIE8;
exports.isIE9 = isIE9;
exports.isSafari = isSafari;
exports.isChrome = isChrome;
exports.isMobileBrowser = isMobileBrowser;
var _isIE8 = !document.createTextNode('test').textContent;
function isIE8() {
return _isIE8;
}
var _isIE9 = !!document.documentMode;
function isIE9() {
return _isIE9;
}
var _isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
function isSafari() {
return _isSafari;
}
var _isChrome = /Chrome/.test(navigator.userAgent) && /Google/.test(navigator.vendor);
function isChrome() {
return _isChrome;
}
function isMobileBrowser(userAgent) {
if (!userAgent) {
userAgent = navigator.userAgent;
}
return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
);
}
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.toSingleLine = toSingleLine;
var _array = __webpack_require__(0);
/**
* Tags a multiline string and return new one without line break characters and following spaces.
*
* @param {Array} strings Parts of the entire string without expressions.
* @param {...String} expressions Expressions converted to strings, which are added to the entire string.
* @returns {String}
*/
function toSingleLine(strings) {
for (var _len = arguments.length, expressions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
expressions[_key - 1] = arguments[_key];
}
var result = (0, _array.arrayReduce)(strings, function (previousValue, currentValue, index) {
var valueWithoutWhiteSpaces = currentValue.replace(/(?:\r?\n\s+)/g, '');
var expressionForIndex = expressions[index] ? expressions[index] : '';
return previousValue + valueWithoutWhiteSpaces + expressionForIndex;
}, '');
return result.trim();
} /* eslint-disable import/prefer-default-export */
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.isFunction = isFunction;
exports.throttle = throttle;
exports.throttleAfterHits = throttleAfterHits;
exports.debounce = debounce;
exports.pipe = pipe;
exports.partial = partial;
exports.curry = curry;
exports.curryRight = curryRight;
var _array = __webpack_require__(0);
/**
* Checks if given variable is function.
*
* @param {*} func Variable to check.
* @returns {Boolean}
*/
function isFunction(func) {
return typeof func === 'function';
}
/**
* Creates throttle function that enforces a maximum number of times a function (`func`) can be called over time (`wait`).
*
* @param {Function} func Function to invoke.
* @param {Number} wait Delay in miliseconds.
* @returns {Function}
*/
function throttle(func) {
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
var lastCalled = 0;
var result = {
lastCallThrottled: true
};
var lastTimer = null;
function _throttle() {
var _this = this;
var args = arguments;
var stamp = Date.now();
var needCall = false;
result.lastCallThrottled = true;
if (!lastCalled) {
lastCalled = stamp;
needCall = true;
}
var remaining = wait - (stamp - lastCalled);
if (needCall) {
result.lastCallThrottled = false;
func.apply(this, args);
} else {
if (lastTimer) {
clearTimeout(lastTimer);
}
lastTimer = setTimeout(function () {
result.lastCallThrottled = false;
func.apply(_this, args);
lastCalled = 0;
lastTimer = void 0;
}, remaining);
}
return result;
}
return _throttle;
}
/**
* Creates throttle function that enforces a maximum number of times a function (`func`) can be called over
* time (`wait`) after specified hits.
*
* @param {Function} func Function to invoke.
* @param {Number} wait Delay in miliseconds.
* @param {Number} hits Number of hits after throttling will be applied.
* @returns {Function}
*/
function throttleAfterHits(func) {
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
var hits = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
var funcThrottle = throttle(func, wait);
var remainHits = hits;
function _clearHits() {
remainHits = hits;
}
function _throttleAfterHits() {
if (remainHits) {
remainHits--;
return func.apply(this, arguments);
}
return funcThrottle.apply(this, arguments);
}
_throttleAfterHits.clearHits = _clearHits;
return _throttleAfterHits;
}
/**
* Creates debounce function that enforces a function (`func`) not be called again until a certain amount of time (`wait`)
* has passed without it being called.
*
* @param {Function} func Function to invoke.
* @param {Number} wait Delay in milliseconds.
* @returns {Function}
*/
function debounce(func) {
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
var lastTimer = null;
var result = void 0;
function _debounce() {
var _this2 = this;
var args = arguments;
if (lastTimer) {
clearTimeout(lastTimer);
}
lastTimer = setTimeout(function () {
result = func.apply(_this2, args);
}, wait);
return result;
}
return _debounce;
}
/**
* Creates the function that returns the result of calling the given functions. Result of the first function is passed to
* the second as an argument and so on. Only first function in the chain can handle multiple arguments.
*
* @param {Function} functions Functions to compose.
* @returns {Function}
*/
function pipe() {
for (var _len = arguments.length, functions = Array(_len), _key = 0; _key < _len; _key++) {
functions[_key] = arguments[_key];
}
var firstFunc = functions[0],
restFunc = functions.slice(1);
return function _pipe() {
return (0, _array.arrayReduce)(restFunc, function (acc, fn) {
return fn(acc);
}, firstFunc.apply(this, arguments));
};
}
/**
* Creates the function that returns the function with cached arguments.
*
* @param {Function} func Function to partialization.
* @param {Array} params Function arguments to cache.
* @returns {Function}
*/
function partial(func) {
for (var _len2 = arguments.length, params = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
params[_key2 - 1] = arguments[_key2];
}
return function _partial() {
for (var _len3 = arguments.length, restParams = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
restParams[_key3] = arguments[_key3];
}
return func.apply(this, params.concat(restParams));
};
}
/**
* Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched
* to the arguments defined in `func` then function will be invoked.
* Arguments are added to the stack in direction from the left to the right.
*
* @example
* ```
* var replace = curry(function(find, replace, string) {
* return string.replace(find, replace);
* });
*
* // returns function with bounded first argument
* var replace = replace('foo')
*
* // returns replaced string - all arguments was passed so function was invoked
* replace('bar', 'Some test with foo...');
*
* ```
*
* @param {Function} func Function to currying.
* @returns {Function}
*/
function curry(func) {
var argsLength = func.length;
function given(argsSoFar) {
return function _curry() {
for (var _len4 = arguments.length, params = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
params[_key4] = arguments[_key4];
}
var passedArgsSoFar = argsSoFar.concat(params);
var result = void 0;
if (passedArgsSoFar.length >= argsLength) {
result = func.apply(this, passedArgsSoFar);
} else {
result = given(passedArgsSoFar);
}
return result;
};
}
return given([]);
}
/**
* Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched
* to the arguments defined in `func` then function will be invoked.
* Arguments are added to the stack in direction from the right to the left.
*
* @example
* ```
* var replace = curry(function(find, replace, string) {
* return string.replace(find, replace);
* });
*
* // returns function with bounded first argument
* var replace = replace('Some test with foo...')
*
* // returns replaced string - all arguments was passed so function was invoked
* replace('bar', 'foo');
*
* ```
*
* @param {Function} func Function to currying.
* @returns {Function}
*/
function curryRight(func) {
var argsLength = func.length;
function given(argsSoFar) {
return function _curry() {
for (var _len5 = arguments.length, params = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
params[_key5] = arguments[_key5];
}
var passedArgsSoFar = argsSoFar.concat(params.reverse());
var result = void 0;
if (passedArgsSoFar.length >= argsLength) {
result = func.apply(this, passedArgsSoFar);
} else {
result = given(passedArgsSoFar);
}
return result;
};
}
return given([]);
}
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getRegisteredValidators = exports.getRegisteredValidatorNames = exports.hasValidator = exports.getValidator = exports.registerValidator = undefined;
var _staticRegister2 = __webpack_require__(48);
var _staticRegister3 = _interopRequireDefault(_staticRegister2);
var _autocompleteValidator = __webpack_require__(524);
var _autocompleteValidator2 = _interopRequireDefault(_autocompleteValidator);
var _dateValidator = __webpack_require__(525);
var _dateValidator2 = _interopRequireDefault(_dateValidator);
var _numericValidator = __webpack_require__(526);
var _numericValidator2 = _interopRequireDefault(_numericValidator);
var _timeValidator = __webpack_require__(527);
var _timeValidator2 = _interopRequireDefault(_timeValidator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _staticRegister = (0, _staticRegister3.default)('validators'),
register = _staticRegister.register,
getItem = _staticRegister.getItem,
hasItem = _staticRegister.hasItem,
getNames = _staticRegister.getNames,
getValues = _staticRegister.getValues;
register('autocomplete', _autocompleteValidator2.default);
register('date', _dateValidator2.default);
register('numeric', _numericValidator2.default);
register('time', _timeValidator2.default);
/**
* Retrieve validator function.
*
* @param {String} name Validator identification.
* @returns {Function} Returns validator function.
*/
function _getItem(name) {
if (typeof name === 'function') {
return name;
}
if (!hasItem(name)) {
throw Error('No registered validator found under "' + name + '" name');
}
return getItem(name);
}
exports.registerValidator = register;
exports.getValidator = _getItem;
exports.hasValidator = hasItem;
exports.getRegisteredValidatorNames = getNames;
exports.getRegisteredValidators = getValues;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.isFormulaExpression = isFormulaExpression;
exports.isFormulaExpressionEscaped = isFormulaExpressionEscaped;
exports.unescapeFormulaExpression = unescapeFormulaExpression;
exports.toUpperCaseFormula = toUpperCaseFormula;
exports.cellCoordFactory = cellCoordFactory;
/**
* Check if provided expression is valid formula expression.
*
* @param {*} expression Expression to check.
* @returns {Boolean}
*/
function isFormulaExpression(expression) {
return typeof expression === 'string' && expression.length >= 2 && expression.charAt(0) === '=';
}
/**
* Check if provided formula expression is escaped.
*
* @param {*} expression Expression to check.
* @returns {Boolean}
*/
function isFormulaExpressionEscaped(expression) {
return typeof expression === 'string' && expression.charAt(0) === '\'' && expression.charAt(1) === '=';
}
/**
* Replace escaped formula expression into valid string.
*
* @param {String} expression Expression to process.
* @returns {String}
*/
function unescapeFormulaExpression(expression) {
return isFormulaExpressionEscaped(expression) ? expression.substr(1) : expression;
}
/**
* Upper case formula expression.
*
* @param {String} expression Formula expression.
* @returns {String}
*/
function toUpperCaseFormula(expression) {
var PATTERN = /(\\"|"(?:\\"|[^"])*"|(\+))|(\\'|'(?:\\'|[^'])*'|(\+))/g;
var strings = expression.match(PATTERN) || [];
var index = -1;
return expression.toUpperCase().replace(PATTERN, function () {
++index;
return strings[index];
});
}
/**
* Cell coordinates function factory.
*
* @param {String} axis An axis name (`row` or `column`) which default index will be applied to.
* @param {Number} defaultIndex Default index.
* @returns {Function}
*/
function cellCoordFactory(axis, defaultIndex) {
return function (cell) {
return {
row: axis === 'row' ? defaultIndex : cell.row,
column: axis === 'column' ? defaultIndex : cell.column
};
};
}
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(17);
var hide = __webpack_require__(39);
var has = __webpack_require__(32);
var SRC = __webpack_require__(55)('src');
var TO_STRING = 'toString';
var $toString = Function[TO_STRING];
var TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(50).inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(22);
var createDesc = __webpack_require__(56);
module.exports = __webpack_require__(25) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(71);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(47);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__(55)('meta');
var isObject = __webpack_require__(12);
var has = __webpack_require__(32);
var setDesc = __webpack_require__(22).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !__webpack_require__(26)(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
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, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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; };
exports.requestAnimationFrame = requestAnimationFrame;
exports.cancelAnimationFrame = cancelAnimationFrame;
exports.isTouchSupported = isTouchSupported;
exports.isWebComponentSupportedNatively = isWebComponentSupportedNatively;
exports.hasCaptionProblem = hasCaptionProblem;
exports.getComparisonFunction = getComparisonFunction;
// https://gist.github.com/paulirish/1579671
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
var _requestAnimationFrame = window.requestAnimationFrame;
var _cancelAnimationFrame = window.cancelAnimationFrame;
for (var x = 0; x < vendors.length && !_requestAnimationFrame; ++x) {
_requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
_cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!_requestAnimationFrame) {
_requestAnimationFrame = function _requestAnimationFrame(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!_cancelAnimationFrame) {
_cancelAnimationFrame = function _cancelAnimationFrame(id) {
clearTimeout(id);
};
}
/**
* Polyfill for requestAnimationFrame
*
* @param {Function} callback
* @returns {Number}
*/
function requestAnimationFrame(callback) {
return _requestAnimationFrame.call(window, callback);
}
/**
* Polyfill for cancelAnimationFrame
*
* @param {Number} id
*/
function cancelAnimationFrame(id) {
_cancelAnimationFrame.call(window, id);
}
function isTouchSupported() {
return 'ontouchstart' in window;
}
/**
* Checks if browser is support web components natively
*
* @returns {Boolean}
*/
function isWebComponentSupportedNatively() {
var test = document.createElement('div');
return !!(test.createShadowRoot && test.createShadowRoot.toString().match(/\[native code\]/));
}
var _hasCaptionProblem;
function detectCaptionProblem() {
var TABLE = document.createElement('TABLE');
TABLE.style.borderSpacing = 0;
TABLE.style.borderWidth = 0;
TABLE.style.padding = 0;
var TBODY = document.createElement('TBODY');
TABLE.appendChild(TBODY);
TBODY.appendChild(document.createElement('TR'));
TBODY.firstChild.appendChild(document.createElement('TD'));
TBODY.firstChild.firstChild.innerHTML = '
t t
';
var CAPTION = document.createElement('CAPTION');
CAPTION.innerHTML = 'c c c c';
CAPTION.style.padding = 0;
CAPTION.style.margin = 0;
TABLE.insertBefore(CAPTION, TBODY);
document.body.appendChild(TABLE);
_hasCaptionProblem = TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight; // boolean
document.body.removeChild(TABLE);
}
function hasCaptionProblem() {
if (_hasCaptionProblem === void 0) {
detectCaptionProblem();
}
return _hasCaptionProblem;
}
var comparisonFunction = void 0;
/**
* Get string comparison function for sorting purposes. It supports multilingual string comparison base on Internationalization API.
*
* @param {String} [language]
* @param {Object} [options]
* @returns {*}
*/
function getComparisonFunction(language) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (comparisonFunction) {
return comparisonFunction;
}
if ((typeof Intl === 'undefined' ? 'undefined' : _typeof(Intl)) === 'object') {
comparisonFunction = new Intl.Collator(language, options).compare;
} else if (typeof String.prototype.localeCompare === 'function') {
comparisonFunction = function comparisonFunction(a, b) {
return ('' + a).localeCompare(b);
};
} else {
comparisonFunction = function comparisonFunction(a, b) {
if (a === b) {
return 0;
}
return a > b ? -1 : 1;
};
}
return comparisonFunction;
}
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.ITEMS = exports.UNDO = exports.SEPARATOR = exports.ROW_BELOW = exports.ROW_ABOVE = exports.REMOVE_ROW = exports.REMOVE_COLUMN = exports.REDO = exports.READ_ONLY = exports.COLUMN_RIGHT = exports.COLUMN_LEFT = exports.CLEAR_COLUMN = exports.ALIGNMENT = undefined;
var _predefinedItems2;
var _alignment = __webpack_require__(571);
Object.defineProperty(exports, 'ALIGNMENT', {
enumerable: true,
get: function get() {
return _alignment.KEY;
}
});
var _clearColumn = __webpack_require__(572);
Object.defineProperty(exports, 'CLEAR_COLUMN', {
enumerable: true,
get: function get() {
return _clearColumn.KEY;
}
});
var _columnLeft = __webpack_require__(573);
Object.defineProperty(exports, 'COLUMN_LEFT', {
enumerable: true,
get: function get() {
return _columnLeft.KEY;
}
});
var _columnRight = __webpack_require__(574);
Object.defineProperty(exports, 'COLUMN_RIGHT', {
enumerable: true,
get: function get() {
return _columnRight.KEY;
}
});
var _readOnly = __webpack_require__(575);
Object.defineProperty(exports, 'READ_ONLY', {
enumerable: true,
get: function get() {
return _readOnly.KEY;
}
});
var _redo = __webpack_require__(576);
Object.defineProperty(exports, 'REDO', {
enumerable: true,
get: function get() {
return _redo.KEY;
}
});
var _removeColumn = __webpack_require__(577);
Object.defineProperty(exports, 'REMOVE_COLUMN', {
enumerable: true,
get: function get() {
return _removeColumn.KEY;
}
});
var _removeRow = __webpack_require__(578);
Object.defineProperty(exports, 'REMOVE_ROW', {
enumerable: true,
get: function get() {
return _removeRow.KEY;
}
});
var _rowAbove = __webpack_require__(579);
Object.defineProperty(exports, 'ROW_ABOVE', {
enumerable: true,
get: function get() {
return _rowAbove.KEY;
}
});
var _rowBelow = __webpack_require__(580);
Object.defineProperty(exports, 'ROW_BELOW', {
enumerable: true,
get: function get() {
return _rowBelow.KEY;
}
});
var _separator = __webpack_require__(156);
Object.defineProperty(exports, 'SEPARATOR', {
enumerable: true,
get: function get() {
return _separator.KEY;
}
});
var _undo = __webpack_require__(581);
Object.defineProperty(exports, 'UNDO', {
enumerable: true,
get: function get() {
return _undo.KEY;
}
});
exports.predefinedItems = predefinedItems;
exports.addItem = addItem;
var _object = __webpack_require__(1);
var _alignment2 = _interopRequireDefault(_alignment);
var _clearColumn2 = _interopRequireDefault(_clearColumn);
var _columnLeft2 = _interopRequireDefault(_columnLeft);
var _columnRight2 = _interopRequireDefault(_columnRight);
var _readOnly2 = _interopRequireDefault(_readOnly);
var _redo2 = _interopRequireDefault(_redo);
var _removeColumn2 = _interopRequireDefault(_removeColumn);
var _removeRow2 = _interopRequireDefault(_removeRow);
var _rowAbove2 = _interopRequireDefault(_rowAbove);
var _rowBelow2 = _interopRequireDefault(_rowBelow);
var _separator2 = _interopRequireDefault(_separator);
var _undo2 = _interopRequireDefault(_undo);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var ITEMS = exports.ITEMS = [_rowAbove.KEY, _rowBelow.KEY, _columnLeft.KEY, _columnRight.KEY, _clearColumn.KEY, _removeRow.KEY, _removeColumn.KEY, _undo.KEY, _redo.KEY, _readOnly.KEY, _alignment.KEY, _separator.KEY];
var _predefinedItems = (_predefinedItems2 = {}, _defineProperty(_predefinedItems2, _separator.KEY, _separator2.default), _defineProperty(_predefinedItems2, _rowAbove.KEY, _rowAbove2.default), _defineProperty(_predefinedItems2, _rowBelow.KEY, _rowBelow2.default), _defineProperty(_predefinedItems2, _columnLeft.KEY, _columnLeft2.default), _defineProperty(_predefinedItems2, _columnRight.KEY, _columnRight2.default), _defineProperty(_predefinedItems2, _clearColumn.KEY, _clearColumn2.default), _defineProperty(_predefinedItems2, _removeRow.KEY, _removeRow2.default), _defineProperty(_predefinedItems2, _removeColumn.KEY, _removeColumn2.default), _defineProperty(_predefinedItems2, _undo.KEY, _undo2.default), _defineProperty(_predefinedItems2, _redo.KEY, _redo2.default), _defineProperty(_predefinedItems2, _readOnly.KEY, _readOnly2.default), _defineProperty(_predefinedItems2, _alignment.KEY, _alignment2.default), _predefinedItems2);
/**
* Gets new object with all predefined menu items.
*
* @returns {Object}
*/
function predefinedItems() {
var items = {};
(0, _object.objectEach)(_predefinedItems, function (itemFactory, key) {
items[key] = itemFactory();
});
return items;
}
/**
* Add new predefined menu item to the collection.
*
* @param {String} key Menu command id.
* @param {Object} item Object command descriptor.
*/
function addItem(key, item) {
if (ITEMS.indexOf(key) === -1) {
_predefinedItems[key] = item;
}
}
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _hotFormulaParser = __webpack_require__(66);
var _array = __webpack_require__(0);
var _base = __webpack_require__(472);
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var STATE_OUT_OFF_DATE = 1;
var STATE_COMPUTING = 2;
var STATE_UP_TO_DATE = 3;
var states = [STATE_OUT_OFF_DATE, STATE_COMPUTING, STATE_UP_TO_DATE];
/**
* Class responsible for wrapping formula expression. It contains calculated value of
* the formula, an error if it has happened and cell references which indicates a relationship with regular
* cells. This object uses physical cell coordinates.
*
* @class CellValue
* @util
*/
var CellValue = function (_BaseCell) {
_inherits(CellValue, _BaseCell);
_createClass(CellValue, null, [{
key: 'STATE_OUT_OFF_DATE',
/**
* Out of date state indicates cells ready for recomputing.
*
* @returns {Number}
*/
get: function get() {
return 1; // PhantomJS crashes when we want to use constant above
}
/**
* Computing state indicates cells under processing.
*
* @returns {Number}
*/
}, {
key: 'STATE_COMPUTING',
get: function get() {
return 2; // PhantomJS crashes when we want to use constant above
}
/**
* Up to date state indicates cells with fresh computed value.
*
* @returns {Number}
*/
}, {
key: 'STATE_UP_TO_DATE',
get: function get() {
return 3; // PhantomJS crashes when we want to use constant above
}
}]);
function CellValue(row, column) {
_classCallCheck(this, CellValue);
/**
* List of precedents cells.
*
* @type {Array}
*/
var _this = _possibleConstructorReturn(this, (CellValue.__proto__ || Object.getPrototypeOf(CellValue)).call(this, row, column));
_this.precedents = [];
/**
* Computed value.
*
* @type {*}
*/
_this.value = null;
/**
* Error name.
*
* @type {String|null}
*/
_this.error = null;
/**
* Indicates cell state.
*
* @type {String}
*/
_this.state = CellValue.STATE_UP_TO_DATE;
return _this;
}
/**
* Set computed value.
*
* @param {*} value
*/
_createClass(CellValue, [{
key: 'setValue',
value: function setValue(value) {
this.value = value;
}
/**
* Get computed value.
*
* @returns {*}
*/
}, {
key: 'getValue',
value: function getValue() {
return this.value;
}
/**
* Set error message for this cell.
*
* @param {String} error Error name.
*/
}, {
key: 'setError',
value: function setError(error) {
this.error = error;
}
/**
* Get error name for this cell.
*
* @returns {String|null}
*/
}, {
key: 'getError',
value: function getError() {
return this.error;
}
/**
* Check if cell value is marked as error.
*
* @returns {Boolean}
*/
}, {
key: 'hasError',
value: function hasError() {
return this.error !== null;
}
/**
* Set cell state.
*
* @param {Number} state Cell state.
*/
}, {
key: 'setState',
value: function setState(state) {
if (states.indexOf(state) === -1) {
throw Error('Unrecognized state: ' + state);
}
this.state = state;
}
/**
* Check cell state.
*
* @returns {Boolean}
*/
}, {
key: 'isState',
value: function isState(state) {
return this.state === state;
}
/**
* Add precedent cell to the collection.
*
* @param {CellReference} cellReference Cell reference object.
*/
}, {
key: 'addPrecedent',
value: function addPrecedent(cellReference) {
if (this.isEqual(cellReference)) {
throw Error(_hotFormulaParser.ERROR_REF);
}
if (!this.hasPrecedent(cellReference)) {
this.precedents.push(cellReference);
}
}
/**
* Remove precedent cell from the collection.
*
* @param {CellReference} cellReference Cell reference object.
*/
}, {
key: 'removePrecedent',
value: function removePrecedent(cellReference) {
if (this.isEqual(cellReference)) {
throw Error(_hotFormulaParser.ERROR_REF);
}
this.precedents = (0, _array.arrayFilter)(this.precedents, function (cell) {
return !cell.isEqual(cellReference);
});
}
/**
* Clear all precedent cells.
*/
}, {
key: 'clearPrecedents',
value: function clearPrecedents() {
this.precedents.length = 0;
}
/**
* Get precedent cells.
*
* @returns {Array}
*/
}, {
key: 'getPrecedents',
value: function getPrecedents() {
return this.precedents;
}
/**
* Check if cell value has precedents cells.
*
* @returns {Boolean}
*/
}, {
key: 'hasPrecedents',
value: function hasPrecedents() {
return this.precedents.length > 0;
}
/**
* Check if cell reference is precedents this cell.
*
* @param {CellReference} cellReference Cell reference object.
* @returns {Boolean}
*/
}, {
key: 'hasPrecedent',
value: function hasPrecedent(cellReference) {
return (0, _array.arrayFilter)(this.precedents, function (cell) {
return cell.isEqual(cellReference);
}).length > 0;
}
}]);
return CellValue;
}(_base2.default);
exports.default = CellValue;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(165);
var enumBugKeys = __webpack_require__(91);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 47 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = staticRegister;
function _toConsumableArray(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 collection = exports.collection = new Map();
function staticRegister() {
var namespace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'common';
if (!collection.has(namespace)) {
collection.set(namespace, new Map());
}
var subCollection = collection.get(namespace);
/**
* Register an item to the collection. If the item under the same was exist earlier then this item will be replaced with new one.
*
* @param {String} name Identification of the item.
* @param {*} item Item to save in the collection.
*/
function register(name, item) {
subCollection.set(name, item);
}
/**
* Retrieve the item from the collection.
*
* @param {String} name Identification of the item.
* @returns {*} Returns item which was saved in the collection.
*/
function getItem(name) {
return subCollection.get(name);
}
/**
* Check if item under specyfied name is exists.
*
* @param {String} name Identification of the item.
* @returns {Boolean} Returns `true` or `false` depends on if element exists in the collection.
*/
function hasItem(name) {
return subCollection.has(name);
}
/**
* Retrieve list of names registered from the collection.
*
* @returns {Array} Returns an array of strings with all names under which objects are stored.
*/
function getNames() {
return [].concat(_toConsumableArray(subCollection.keys()));
}
/**
* Retrieve all registered values from the collection.
*
* @returns {Array} Returns an array with all values stored in the collection.
*/
function getValues() {
return [].concat(_toConsumableArray(subCollection.values()));
}
return {
register: register,
getItem: getItem,
hasItem: hasItem,
getNames: getNames,
getValues: getValues
};
}
/***/ }),
/* 49 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 50 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.5.3' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(12);
module.exports = function (it, TYPE) {
if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
return it;
};
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(16)('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(39)(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.RecordTranslator = undefined;
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; }; }();
exports.registerIdentity = registerIdentity;
exports.getTranslator = getTranslator;
var _core = __webpack_require__(152);
var _core2 = _interopRequireDefault(_core);
var _object = __webpack_require__(1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class RecordTranslator
* @util
*/
var RecordTranslator = function () {
function RecordTranslator(hot) {
_classCallCheck(this, RecordTranslator);
this.hot = hot;
}
/**
* Translate physical row index into visual.
*
* @param {Number} row Physical row index.
* @returns {Number} Returns visual row index.
*/
_createClass(RecordTranslator, [{
key: 'toVisualRow',
value: function toVisualRow(row) {
return this.hot.runHooks('unmodifyRow', row);
}
/**
* Translate physical column index into visual.
*
* @param {Number} column Physical column index.
* @returns {Number} Returns visual column index.
*/
}, {
key: 'toVisualColumn',
value: function toVisualColumn(column) {
return this.hot.runHooks('unmodifyCol', column);
}
/**
* Translate physical coordinates into visual. Can be passed as separate 2 arguments (row, column) or as an object in first
* argument with `row` and `column` keys.
*
* @param {Number|Object} row Physical coordinates or row index.
* @param {Number} [column] Physical column index.
* @returns {Object|Array} Returns an object with visual records or an array if coordinates passed as separate arguments.
*/
}, {
key: 'toVisual',
value: function toVisual(row, column) {
var result = void 0;
if ((0, _object.isObject)(row)) {
result = {
row: this.toVisualRow(row.row),
column: this.toVisualColumn(row.column)
};
} else {
result = [this.toVisualRow(row), this.toVisualColumn(column)];
}
return result;
}
/**
* Translate visual row index into physical.
*
* @param {Number} row Visual row index.
* @returns {Number} Returns physical row index.
*/
}, {
key: 'toPhysicalRow',
value: function toPhysicalRow(row) {
return this.hot.runHooks('modifyRow', row);
}
/**
* Translate visual column index into physical.
*
* @param {Number} column Visual column index.
* @returns {Number} Returns physical column index.
*/
}, {
key: 'toPhysicalColumn',
value: function toPhysicalColumn(column) {
return this.hot.runHooks('modifyCol', column);
}
/**
* Translate visual coordinates into physical. Can be passed as separate 2 arguments (row, column) or as an object in first
* argument with `row` and `column` keys.
*
* @param {Number|Object} row Visual coordinates or row index.
* @param {Number} [column] Visual column index.
* @returns {Object|Array} Returns an object with physical records or an array if coordinates passed as separate arguments.
*/
}, {
key: 'toPhysical',
value: function toPhysical(row, column) {
var result = void 0;
if ((0, _object.isObject)(row)) {
result = {
row: this.toPhysicalRow(row.row),
column: this.toPhysicalColumn(row.column)
};
} else {
result = [this.toPhysicalRow(row), this.toPhysicalColumn(column)];
}
return result;
}
}]);
return RecordTranslator;
}();
exports.RecordTranslator = RecordTranslator;
var identities = new WeakMap();
var translatorSingletons = new WeakMap();
function registerIdentity(identity, hot) {
identities.set(identity, hot);
}
function getTranslator(identity) {
var singleton = void 0;
if (!(identity instanceof _core2.default)) {
if (!identities.has(identity)) {
throw Error('Record translator was not registered for this object identity');
}
identity = identities.get(identity);
}
if (translatorSingletons.has(identity)) {
singleton = translatorSingletons.get(identity);
} else {
singleton = new RecordTranslator(identity);
translatorSingletons.set(identity, singleton);
}
return singleton;
}
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _array = __webpack_require__(0);
var _object = __webpack_require__(1);
var _number = __webpack_require__(4);
function _toConsumableArray(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 MIXIN_NAME = 'arrayMapper';
/**
* @type {Object}
*/
var arrayMapper = {
_arrayMap: [],
/**
* Get translated index by its physical index.
*
* @param {Number} physicalIndex Physical index.
* @return {Number|null} Returns translated index mapped by passed physical index.
*/
getValueByIndex: function getValueByIndex(physicalIndex) {
var length = this._arrayMap.length;
var translatedIndex = null;
if (physicalIndex < length) {
translatedIndex = this._arrayMap[physicalIndex];
}
return translatedIndex;
},
/**
* Get physical index by its translated index.
*
* @param {*} translatedIndex Value to search.
* @returns {Number|null} Returns a physical index of the array mapper.
*/
getIndexByValue: function getIndexByValue(translatedIndex) {
var physicalIndex = void 0;
// eslint-disable-next-line no-cond-assign, no-return-assign
return (physicalIndex = this._arrayMap.indexOf(translatedIndex)) === -1 ? null : physicalIndex;
},
/**
* Insert new items to array mapper starting at passed index. New entries will be a continuation of last value in the array.
*
* @param {Number} physicalIndex Array index.
* @param {Number} [amount=1] Defines how many items will be created to an array.
* @returns {Array} Returns added items.
*/
insertItems: function insertItems(physicalIndex) {
var _this = this;
var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var newIndex = (0, _array.arrayMax)(this._arrayMap) + 1;
var addedItems = [];
(0, _number.rangeEach)(amount - 1, function (count) {
addedItems.push(_this._arrayMap.splice(physicalIndex + count, 0, newIndex + count));
});
return addedItems;
},
/**
* Remove items from array mapper.
*
* @param {Number} physicalIndex Array index.
* @param {Number} [amount=1] Defines how many items will be created to an array.
* @returns {Array} Returns removed items.
*/
removeItems: function removeItems(physicalIndex) {
var _this2 = this;
var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var removedItems = [];
if (Array.isArray(physicalIndex)) {
var mapCopy = [].concat(this._arrayMap);
// Sort descending
physicalIndex.sort(function (a, b) {
return b - a;
});
removedItems = (0, _array.arrayReduce)(physicalIndex, function (acc, item) {
_this2._arrayMap.splice(item, 1);
return acc.concat(mapCopy.slice(item, item + 1));
}, []);
} else {
removedItems = this._arrayMap.splice(physicalIndex, amount);
}
return removedItems;
},
/**
* Unshift items (remove and shift chunk of array to the left).
*
* @param {Number|Array} physicalIndex Array index or Array of indexes to unshift.
* @param {Number} [amount=1] Defines how many items will be removed from an array (when index is passed as number).
*/
unshiftItems: function unshiftItems(physicalIndex) {
var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var removedItems = this.removeItems(physicalIndex, amount);
function countRowShift(logicalRow) {
// Todo: compare perf between reduce vs sort->each->brake
return (0, _array.arrayReduce)(removedItems, function (count, removedLogicalRow) {
if (logicalRow > removedLogicalRow) {
count++;
}
return count;
}, 0);
}
this._arrayMap = (0, _array.arrayMap)(this._arrayMap, function (logicalRow, physicalRow) {
var rowShift = countRowShift(logicalRow);
if (rowShift) {
logicalRow -= rowShift;
}
return logicalRow;
});
},
/**
* Shift (right shifting) items starting at passed index.
*
* @param {Number} physicalIndex Array index.
* @param {Number} [amount=1] Defines how many items will be created to an array.
*/
shiftItems: function shiftItems(physicalIndex) {
var _this3 = this;
var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
this._arrayMap = (0, _array.arrayMap)(this._arrayMap, function (row) {
if (row >= physicalIndex) {
row += amount;
}
return row;
});
(0, _number.rangeEach)(amount - 1, function (count) {
_this3._arrayMap.splice(physicalIndex + count, 0, physicalIndex + count);
});
},
/**
* Swap indexes in arrayMapper.
*
* @param {Number} physicalIndexFrom index to move.
* @param {Number} physicalIndexTo index to.
*/
swapIndexes: function swapIndexes(physicalIndexFrom, physicalIndexTo) {
var _arrayMap;
(_arrayMap = this._arrayMap).splice.apply(_arrayMap, [physicalIndexTo, 0].concat(_toConsumableArray(this._arrayMap.splice(physicalIndexFrom, 1))));
},
/**
* Clear all stored index<->value information from an array.
*/
clearMap: function clearMap() {
this._arrayMap.length = 0;
}
};
(0, _object.defineGetter)(arrayMapper, 'MIXIN_NAME', MIXIN_NAME, {
writable: false,
enumerable: false
});
exports.default = arrayMapper;
/***/ }),
/* 55 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 56 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 57 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(22).f;
var has = __webpack_require__(32);
var TAG = __webpack_require__(16)('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/* 59 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.EditorState = undefined;
var _src = __webpack_require__(8);
var _mixed = __webpack_require__(13);
var EditorState = exports.EditorState = {
VIRGIN: 'STATE_VIRGIN', // before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', // waiting for async validation
FINISHED: 'STATE_FINISHED'
};
function BaseEditor(instance) {
this.instance = instance;
this.state = EditorState.VIRGIN;
this._opened = false;
this._fullEditMode = false;
this._closeCallback = null;
this.init();
}
BaseEditor.prototype._fireCallbacks = function (result) {
if (this._closeCallback) {
this._closeCallback(result);
this._closeCallback = null;
}
};
BaseEditor.prototype.init = function () {};
BaseEditor.prototype.getValue = function () {
throw Error('Editor getValue() method unimplemented');
};
BaseEditor.prototype.setValue = function (newValue) {
throw Error('Editor setValue() method unimplemented');
};
BaseEditor.prototype.open = function () {
throw Error('Editor open() method unimplemented');
};
BaseEditor.prototype.close = function () {
throw Error('Editor close() method unimplemented');
};
BaseEditor.prototype.prepare = function (row, col, prop, td, originalValue, cellProperties) {
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = originalValue;
this.cellProperties = cellProperties;
this.state = EditorState.VIRGIN;
};
BaseEditor.prototype.extend = function () {
var baseClass = this.constructor;
function Editor() {
baseClass.apply(this, arguments);
}
function inherit(Child, Parent) {
function Bridge() {}
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Child.prototype.constructor = Child;
return Child;
}
return inherit(Editor, baseClass);
};
BaseEditor.prototype.saveValue = function (value, ctrlDown) {
var selection = void 0;
var tmp = void 0;
// if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
if (ctrlDown) {
selection = this.instance.getSelectedLast();
if (selection[0] > selection[2]) {
tmp = selection[0];
selection[0] = selection[2];
selection[2] = tmp;
}
if (selection[1] > selection[3]) {
tmp = selection[1];
selection[1] = selection[3];
selection[3] = tmp;
}
} else {
selection = [this.row, this.col, null, null];
}
this.instance.populateFromArray(selection[0], selection[1], value, selection[2], selection[3], 'edit');
};
BaseEditor.prototype.beginEditing = function (newInitialValue, event) {
if (this.state !== EditorState.VIRGIN) {
return;
}
this.instance.view.scrollViewport(new _src.CellCoords(this.row, this.col));
this.instance.view.render();
this.state = EditorState.EDITING;
newInitialValue = typeof newInitialValue === 'string' ? newInitialValue : this.originalValue;
this.setValue((0, _mixed.stringify)(newInitialValue));
this.open(event);
this._opened = true;
this.focus();
// only rerender the selections (FillHandle should disappear when beginediting is triggered)
this.instance.view.render();
this.instance.runHooks('afterBeginEditing', this.row, this.col);
};
BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
var _this = this,
val;
if (callback) {
var previousCloseCallback = this._closeCallback;
this._closeCallback = function (result) {
if (previousCloseCallback) {
previousCloseCallback(result);
}
callback(result);
_this.instance.view.render();
};
}
if (this.isWaiting()) {
return;
}
if (this.state == EditorState.VIRGIN) {
this.instance._registerTimeout(setTimeout(function () {
_this._fireCallbacks(true);
}, 0));
return;
}
if (this.state == EditorState.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
this.instance.view.render();
return;
}
var value = this.getValue();
if (this.instance.getSettings().trimWhitespace) {
// We trim only string values
val = [[typeof value === 'string' ? String.prototype.trim.call(value || '') : value]];
} else {
val = [[value]];
}
this.state = EditorState.WAITING;
this.saveValue(val, ctrlDown);
if (this.instance.getCellValidator(this.cellProperties)) {
this.instance.addHookOnce('postAfterValidate', function (result) {
_this.state = EditorState.FINISHED;
_this.discardEditor(result);
});
} else {
this.state = EditorState.FINISHED;
this.discardEditor(true);
}
}
};
BaseEditor.prototype.cancelChanges = function () {
this.state = EditorState.FINISHED;
this.discardEditor();
};
BaseEditor.prototype.discardEditor = function (result) {
if (this.state !== EditorState.FINISHED) {
return;
}
// validator was defined and failed
if (result === false && this.cellProperties.allowInvalid !== true) {
this.instance.selectCell(this.row, this.col);
this.focus();
this.state = EditorState.EDITING;
this._fireCallbacks(false);
} else {
this.close();
this._opened = false;
this._fullEditMode = false;
this.state = EditorState.VIRGIN;
this._fireCallbacks(true);
}
};
/**
* Switch editor into full edit mode. In this state navigation keys don't close editor. This mode is activated
* automatically after hit ENTER or F2 key on the cell or while editing cell press F2 key.
*/
BaseEditor.prototype.enableFullEditMode = function () {
this._fullEditMode = true;
};
/**
* Checks if editor is in full edit mode.
*
* @returns {Boolean}
*/
BaseEditor.prototype.isInFullEditMode = function () {
return this._fullEditMode;
};
BaseEditor.prototype.isOpened = function () {
return this._opened;
};
BaseEditor.prototype.isWaiting = function () {
return this.state === EditorState.WAITING;
};
BaseEditor.prototype.checkEditorSection = function () {
var totalRows = this.instance.countRows();
var section = '';
if (this.row < this.instance.getSettings().fixedRowsTop) {
if (this.col < this.instance.getSettings().fixedColumnsLeft) {
section = 'top-left-corner';
} else {
section = 'top';
}
} else if (this.instance.getSettings().fixedRowsBottom && this.row >= totalRows - this.instance.getSettings().fixedRowsBottom) {
if (this.col < this.instance.getSettings().fixedColumnsLeft) {
section = 'bottom-left-corner';
} else {
section = 'bottom';
}
} else if (this.col < this.instance.getSettings().fixedColumnsLeft) {
section = 'left';
}
return section;
};
exports.default = BaseEditor;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* CellCoords holds cell coordinates (row, column) and few method to validate them and
* retrieve as an array or an object
*
* @class CellCoords
*/
var CellCoords = function () {
/**
* @param {Number} row Row index
* @param {Number} col Column index
*/
function CellCoords(row, col) {
_classCallCheck(this, CellCoords);
if (typeof row !== 'undefined' && typeof col !== 'undefined') {
this.row = row;
this.col = col;
} else {
this.row = null;
this.col = null;
}
}
/**
* Checks if given set of coordinates is valid in context of a given Walkontable instance
*
* @param {Walkontable} wotInstance
* @returns {Boolean}
*/
_createClass(CellCoords, [{
key: 'isValid',
value: function isValid(wotInstance) {
// is it a valid cell index (0 or higher)
if (this.row < 0 || this.col < 0) {
return false;
}
// is selection within total rows and columns
if (this.row >= wotInstance.getSetting('totalRows') || this.col >= wotInstance.getSetting('totalColumns')) {
return false;
}
return true;
}
/**
* Checks if this cell coords are the same as cell coords given as a parameter
*
* @param {CellCoords} cellCoords
* @returns {Boolean}
*/
}, {
key: 'isEqual',
value: function isEqual(cellCoords) {
if (cellCoords === this) {
return true;
}
return this.row === cellCoords.row && this.col === cellCoords.col;
}
/**
* Checks if tested coordinates are positioned in south-east from this cell coords
*
* @param {Object} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isSouthEastOf',
value: function isSouthEastOf(testedCoords) {
return this.row >= testedCoords.row && this.col >= testedCoords.col;
}
/**
* Checks if tested coordinates are positioned in north-east from this cell coords
*
* @param {Object} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isNorthWestOf',
value: function isNorthWestOf(testedCoords) {
return this.row <= testedCoords.row && this.col <= testedCoords.col;
}
/**
* Checks if tested coordinates are positioned in south-west from this cell coords
*
* @param {Object} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isSouthWestOf',
value: function isSouthWestOf(testedCoords) {
return this.row >= testedCoords.row && this.col <= testedCoords.col;
}
/**
* Checks if tested coordinates are positioned in north-east from this cell coords
*
* @param {Object} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isNorthEastOf',
value: function isNorthEastOf(testedCoords) {
return this.row <= testedCoords.row && this.col >= testedCoords.col;
}
/**
* Convert CellCoords to literal object.
*
* @return {Object} Returns a literal object with `row` and `col` properties.
*/
}, {
key: 'toObject',
value: function toObject() {
return {
row: this.row,
col: this.col
};
}
}]);
return CellCoords;
}();
exports.default = CellCoords;
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _element = __webpack_require__(2);
var _autoResize = __webpack_require__(505);
var _autoResize2 = _interopRequireDefault(_autoResize);
var _baseEditor = __webpack_require__(60);
var _baseEditor2 = _interopRequireDefault(_baseEditor);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _unicode = __webpack_require__(18);
var _event = __webpack_require__(11);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TextEditor = _baseEditor2.default.prototype.extend();
/**
* @private
* @editor TextEditor
* @class TextEditor
* @dependencies autoResize
*/
TextEditor.prototype.init = function () {
var that = this;
this.createElements();
this.eventManager = new _eventManager2.default(this);
this.bindEvents();
this.autoResize = (0, _autoResize2.default)();
this.instance.addHook('afterDestroy', function () {
that.destroy();
});
};
TextEditor.prototype.getValue = function () {
return this.TEXTAREA.value;
};
TextEditor.prototype.setValue = function (newValue) {
this.TEXTAREA.value = newValue;
};
var onBeforeKeyDown = function onBeforeKeyDown(event) {
var instance = this,
that = instance.getActiveEditor(),
ctrlDown;
// catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
// Process only events that have been fired in the editor
if (event.target !== that.TEXTAREA || (0, _event.isImmediatePropagationStopped)(event)) {
return;
}
if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
// when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
(0, _event.stopImmediatePropagation)(event);
return;
}
switch (event.keyCode) {
case _unicode.KEY_CODES.ARROW_RIGHT:
if (that.isInFullEditMode()) {
if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
(0, _event.stopImmediatePropagation)(event);
}
}
break;
case _unicode.KEY_CODES.ARROW_LEFT:
if (that.isInFullEditMode()) {
if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
(0, _event.stopImmediatePropagation)(event);
}
}
break;
case _unicode.KEY_CODES.ARROW_UP:
case _unicode.KEY_CODES.ARROW_DOWN:
if (that.isInFullEditMode()) {
if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
(0, _event.stopImmediatePropagation)(event);
}
}
break;
case _unicode.KEY_CODES.ENTER:
{
var isMultipleSelection = this.selection.isMultiple();
if (ctrlDown && !isMultipleSelection || event.altKey) {
// if ctrl+enter or alt+enter, add new line
if (that.isOpened()) {
var caretPosition = (0, _element.getCaretPosition)(that.TEXTAREA);
var value = that.getValue();
var newValue = value.slice(0, caretPosition) + '\n' + value.slice(caretPosition);
that.setValue(newValue);
(0, _element.setCaretPosition)(that.TEXTAREA, caretPosition + 1);
} else {
that.beginEditing(that.originalValue + '\n');
}
(0, _event.stopImmediatePropagation)(event);
}
event.preventDefault(); // don't add newline to field
break;
}
case _unicode.KEY_CODES.A:
case _unicode.KEY_CODES.X:
case _unicode.KEY_CODES.C:
case _unicode.KEY_CODES.V:
if (ctrlDown) {
(0, _event.stopImmediatePropagation)(event); // CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
}
break;
case _unicode.KEY_CODES.BACKSPACE:
case _unicode.KEY_CODES.DELETE:
case _unicode.KEY_CODES.HOME:
case _unicode.KEY_CODES.END:
(0, _event.stopImmediatePropagation)(event); // backspace, delete, home, end should only work locally when cell is edited (not in table context)
break;
default:
break;
}
if ([_unicode.KEY_CODES.ARROW_UP, _unicode.KEY_CODES.ARROW_RIGHT, _unicode.KEY_CODES.ARROW_DOWN, _unicode.KEY_CODES.ARROW_LEFT].indexOf(event.keyCode) === -1) {
that.autoResize.resize(String.fromCharCode(event.keyCode));
}
};
TextEditor.prototype.open = function () {
this.refreshDimensions(); // need it instantly, to prevent https://github.com/handsontable/handsontable/issues/348
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.close = function (tdOutside) {
this.textareaParentStyle.display = 'none';
this.autoResize.unObserve();
if (document.activeElement === this.TEXTAREA) {
this.instance.listen(); // don't refocus the table if user focused some cell outside of HT on purpose
}
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.focus = function () {
this.TEXTAREA.focus();
(0, _element.setCaretPosition)(this.TEXTAREA, this.TEXTAREA.value.length);
};
TextEditor.prototype.createElements = function () {
// this.$body = $(document.body);
this.TEXTAREA = document.createElement('TEXTAREA');
(0, _element.addClass)(this.TEXTAREA, 'handsontableInput');
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.TEXTAREA_PARENT = document.createElement('DIV');
(0, _element.addClass)(this.TEXTAREA_PARENT, 'handsontableInputHolder');
this.textareaParentStyle = this.TEXTAREA_PARENT.style;
this.textareaParentStyle.top = 0;
this.textareaParentStyle.left = 0;
this.textareaParentStyle.display = 'none';
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
this.instance.rootElement.appendChild(this.TEXTAREA_PARENT);
var that = this;
this.instance._registerTimeout(setTimeout(function () {
that.refreshDimensions();
}, 0));
};
TextEditor.prototype.getEditedCell = function () {
var editorSection = this.checkEditorSection(),
editedCell;
switch (editorSection) {
case 'top':
editedCell = this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.textareaParentStyle.zIndex = 101;
break;
case 'top-left-corner':
editedCell = this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.textareaParentStyle.zIndex = 103;
break;
case 'bottom-left-corner':
editedCell = this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.textareaParentStyle.zIndex = 103;
break;
case 'left':
editedCell = this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.textareaParentStyle.zIndex = 102;
break;
case 'bottom':
editedCell = this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.textareaParentStyle.zIndex = 102;
break;
default:
editedCell = this.instance.getCell(this.row, this.col);
this.textareaParentStyle.zIndex = '';
break;
}
return editedCell != -1 && editedCell != -2 ? editedCell : void 0;
};
TextEditor.prototype.refreshValue = function () {
var sourceData = this.instance.getSourceDataAtCell(this.row, this.prop);
this.originalValue = sourceData;
this.setValue(sourceData);
this.refreshDimensions();
};
TextEditor.prototype.refreshDimensions = function () {
if (this.state !== _baseEditor.EditorState.EDITING) {
return;
}
this.TD = this.getEditedCell();
// TD is outside of the viewport.
if (!this.TD) {
this.close(true);
return;
}
var currentOffset = (0, _element.offset)(this.TD),
containerOffset = (0, _element.offset)(this.instance.rootElement),
scrollableContainer = (0, _element.getScrollableElement)(this.TD),
totalRowsCount = this.instance.countRows(),
// If colHeaders is disabled, cells in the first row have border-top
editTopModifier = currentOffset.top === containerOffset.top ? 0 : 1,
editTop = currentOffset.top - containerOffset.top - editTopModifier - (scrollableContainer.scrollTop || 0),
editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0),
settings = this.instance.getSettings(),
rowHeadersCount = this.instance.hasRowHeaders(),
colHeadersCount = this.instance.hasColHeaders(),
editorSection = this.checkEditorSection(),
backgroundColor = this.TD.style.backgroundColor,
cssTransformOffset;
// TODO: Refactor this to the new instance.getCell method (from #ply-59), after 0.12.1 is released
switch (editorSection) {
case 'top':
cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
break;
case 'left':
cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
break;
case 'top-left-corner':
cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom-left-corner':
cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom':
cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
break;
default:
break;
}
if (colHeadersCount && this.instance.getSelectedLast()[0] === 0 || settings.fixedRowsBottom && this.instance.getSelectedLast()[0] === totalRowsCount - settings.fixedRowsBottom) {
editTop += 1;
}
if (this.instance.getSelectedLast()[1] === 0) {
editLeft += 1;
}
if (cssTransformOffset && cssTransformOffset != -1) {
this.textareaParentStyle[cssTransformOffset[0]] = cssTransformOffset[1];
} else {
(0, _element.resetCssTransform)(this.TEXTAREA_PARENT);
}
this.textareaParentStyle.top = editTop + 'px';
this.textareaParentStyle.left = editLeft + 'px';
var firstRowOffset = this.instance.view.wt.wtViewport.rowsRenderCalculator.startPosition;
var firstColumnOffset = this.instance.view.wt.wtViewport.columnsRenderCalculator.startPosition;
var horizontalScrollPosition = this.instance.view.wt.wtOverlays.leftOverlay.getScrollPosition();
var verticalScrollPosition = this.instance.view.wt.wtOverlays.topOverlay.getScrollPosition();
var scrollbarWidth = (0, _element.getScrollbarWidth)();
var cellTopOffset = this.TD.offsetTop + firstRowOffset - verticalScrollPosition;
var cellLeftOffset = this.TD.offsetLeft + firstColumnOffset - horizontalScrollPosition;
var width = (0, _element.innerWidth)(this.TD) - 8;
var actualVerticalScrollbarWidth = (0, _element.hasVerticalScrollbar)(scrollableContainer) ? scrollbarWidth : 0;
var actualHorizontalScrollbarWidth = (0, _element.hasHorizontalScrollbar)(scrollableContainer) ? scrollbarWidth : 0;
var maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 9 - actualVerticalScrollbarWidth;
var height = this.TD.scrollHeight + 1;
var maxHeight = Math.max(this.instance.view.maximumVisibleElementHeight(cellTopOffset) - actualHorizontalScrollbarWidth, 23);
var cellComputedStyle = (0, _element.getComputedStyle)(this.TD);
this.TEXTAREA.style.fontSize = cellComputedStyle.fontSize;
this.TEXTAREA.style.fontFamily = cellComputedStyle.fontFamily;
this.TEXTAREA.style.backgroundColor = ''; // RESET STYLE
this.TEXTAREA.style.backgroundColor = backgroundColor ? backgroundColor : (0, _element.getComputedStyle)(this.TEXTAREA).backgroundColor;
this.autoResize.init(this.TEXTAREA, {
minHeight: Math.min(height, maxHeight),
maxHeight: maxHeight, // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
minWidth: Math.min(width, maxWidth),
maxWidth: maxWidth // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
}, true);
this.textareaParentStyle.display = 'block';
};
TextEditor.prototype.bindEvents = function () {
var editor = this;
this.eventManager.addEventListener(this.TEXTAREA, 'cut', function (event) {
(0, _event.stopPropagation)(event);
});
this.eventManager.addEventListener(this.TEXTAREA, 'paste', function (event) {
(0, _event.stopPropagation)(event);
});
this.instance.addHook('afterScrollHorizontally', function () {
editor.refreshDimensions();
});
this.instance.addHook('afterScrollVertically', function () {
editor.refreshDimensions();
});
this.instance.addHook('afterColumnResize', function () {
editor.refreshDimensions();
editor.focus();
});
this.instance.addHook('afterRowResize', function () {
editor.refreshDimensions();
editor.focus();
});
this.instance.addHook('afterDestroy', function () {
editor.eventManager.destroy();
});
};
TextEditor.prototype.destroy = function () {
this.eventManager.destroy();
};
exports.default = TextEditor;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.sortComparison = sortComparison;
exports.toVisualValue = toVisualValue;
exports.createArrayAssertion = createArrayAssertion;
exports.toEmptyString = toEmptyString;
exports.unifyColumnValues = unifyColumnValues;
exports.intersectValues = intersectValues;
var _feature = __webpack_require__(43);
var _array = __webpack_require__(0);
var sortCompare = (0, _feature.getComparisonFunction)();
/**
* Comparison function for sorting purposes.
*
* @param {*} a
* @param {*} b
* @returns {Number} Returns number from -1 to 1.
*/
function sortComparison(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}
return sortCompare(a, b);
}
/**
* Convert raw value into visual value.
*
* @param {*} value
* @param {String} defaultEmptyValue Default value for empty cells.
* @returns {*}
*/
function toVisualValue(value, defaultEmptyValue) {
if (value === '') {
value = '(' + defaultEmptyValue + ')';
}
return value;
}
var SUPPORT_SET_CONSTRUCTOR = new Set([1]).has(1);
var SUPPORT_FAST_DEDUPE = SUPPORT_SET_CONSTRUCTOR && typeof Array.from === 'function';
/**
* Create an array assertion to compare if an element exists in that array (in a more efficient way than .indexOf).
*
* @param {Array} initialData Values to compare.
* @returns {Function}
*/
function createArrayAssertion(initialData) {
if (SUPPORT_SET_CONSTRUCTOR) {
initialData = new Set(initialData);
}
return function (value) {
var result = void 0;
if (SUPPORT_SET_CONSTRUCTOR) {
result = initialData.has(value);
} else {
/* eslint-disable no-bitwise */
result = !!~initialData.indexOf(value);
}
return result;
};
}
/**
* Convert empty-ish values like null and undefined to an empty string.
*
* @param value Value to check.
* @returns {String}
*/
function toEmptyString(value) {
return value == null ? '' : value;
}
/**
* Unify column values (replace `null` and `undefined` values into empty string, unique values and sort them).
*
* @param {Array} values An array of values.
* @returns {Array}
*/
function unifyColumnValues(values) {
if (SUPPORT_FAST_DEDUPE) {
values = Array.from(new Set(values));
} else {
values = (0, _array.arrayUnique)(values);
}
values = values.sort(function (a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}
if (a === b) {
return 0;
}
return a > b ? 1 : -1;
});
return values;
}
/**
* Intersect 'base' values with 'selected' values and return an array of object.
*
* @param {Array} base An array of base values.
* @param {Array} selected An array of selected values.
* @param {String} defaultEmptyValue Default value for empty cells.
* @param {Function} [callback] A callback function which is invoked for every item in an array.
* @returns {Array}
*/
function intersectValues(base, selected, defaultEmptyValue, callback) {
var result = [];
var same = base === selected;
var selectedItemsAssertion = void 0;
if (!same) {
selectedItemsAssertion = createArrayAssertion(selected);
}
(0, _array.arrayEach)(base, function (value) {
var checked = false;
if (same || selectedItemsAssertion(value)) {
checked = true;
}
var item = { checked: checked, value: value, visualValue: toVisualValue(value, defaultEmptyValue) };
if (callback) {
callback(item);
}
result.push(item);
});
return result;
}
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getOperationFunc = getOperationFunc;
exports.getOperationName = getOperationName;
exports.registerOperation = registerOperation;
var operations = exports.operations = {};
/**
* Get operation closure with pre-bound arguments.
*
* @param {String} id Operator `id`.
* @returns {Function}
*/
function getOperationFunc(id) {
if (!operations[id]) {
throw Error("Operation with id \"" + id + "\" does not exist.");
}
var func = operations[id].func;
return function (conditions, value) {
return func(conditions, value);
};
}
/**
* Return name of operation which is displayed inside UI component, basing on it's `id`.
*
* @param {String} id `Id` of operation.
*/
function getOperationName(id) {
return operations[id].name;
}
/**
* Operator registerer.
*
* @param {String} id Operation `id`.
* @param {String} name Operation name which is displayed inside UI component.
* @param {Function} func Operation function.
*/
function registerOperation(id, name, func) {
operations[id] = { name: name, func: func };
}
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _object = __webpack_require__(1);
var _localHooks = __webpack_require__(21);
var _localHooks2 = _interopRequireDefault(_localHooks);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _element = __webpack_require__(2);
var _array = __webpack_require__(0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var STATE_BUILT = 'built';
var STATE_BUILDING = 'building';
var EVENTS_TO_REGISTER = ['click', 'input', 'keydown', 'keypress', 'keyup', 'focus', 'blur', 'change'];
/**
* @class
* @private
*/
var BaseUI = function () {
_createClass(BaseUI, null, [{
key: 'DEFAULTS',
get: function get() {
return (0, _object.clone)({
className: '',
value: '',
tagName: 'div',
children: [],
wrapIt: true
});
}
}]);
function BaseUI(hotInstance, options) {
_classCallCheck(this, BaseUI);
/**
* Instance of Handsontable.
*
* @type {Core}
*/
this.hot = hotInstance;
/**
* Instance of EventManager.
*
* @type {EventManager}
*/
this.eventManager = new _eventManager2.default(this);
/**
* List of element options.
*
* @type {Object}
*/
this.options = (0, _object.extend)(BaseUI.DEFAULTS, options);
/**
* Build root DOM element.
*
* @type {Element}
* @private
*/
this._element = document.createElement(this.options.wrapIt ? 'div' : this.options.tagName);
/**
* Flag which determines build state of element.
*
* @type {Boolean}
*/
this.buildState = false;
}
/**
* Set the element value.
*
* @returns {*}
*/
_createClass(BaseUI, [{
key: 'setValue',
value: function setValue(value) {
this.options.value = value;
this.update();
}
/**
* Get the element value.
*
* @returns {*}
*/
}, {
key: 'getValue',
value: function getValue() {
return this.options.value;
}
/**
* Get element as a DOM object.
*
* @returns {Element}
*/
}, {
key: 'isBuilt',
/**
* Check if element was built (built whole DOM structure).
*
* @returns {Boolean}
*/
value: function isBuilt() {
return this.buildState === STATE_BUILT;
}
/**
* Build DOM structure.
*/
}, {
key: 'build',
value: function build() {
var _this = this;
var registerEvent = function registerEvent(element, eventName) {
_this.eventManager.addEventListener(element, eventName, function (event) {
return _this.runLocalHooks(eventName, event, _this);
});
};
if (!this.buildState) {
this.buildState = STATE_BUILDING;
}
if (this.options.className) {
(0, _element.addClass)(this._element, this.options.className);
}
if (this.options.children.length) {
(0, _array.arrayEach)(this.options.children, function (element) {
return _this._element.appendChild(element.element);
});
} else if (this.options.wrapIt) {
var element = document.createElement(this.options.tagName);
(0, _object.objectEach)(this.options, function (value, key) {
if (element[key] !== void 0 && key !== 'className' && key !== 'tagName' && key !== 'children') {
element[key] = value;
}
});
this._element.appendChild(element);
(0, _array.arrayEach)(EVENTS_TO_REGISTER, function (eventName) {
return registerEvent(element, eventName);
});
} else {
(0, _array.arrayEach)(EVENTS_TO_REGISTER, function (eventName) {
return registerEvent(_this._element, eventName);
});
}
}
/**
* Update DOM structure.
*/
}, {
key: 'update',
value: function update() {}
/**
* Reset to initial state.
*/
}, {
key: 'reset',
value: function reset() {
this.options.value = '';
this.update();
}
/**
* Show element.
*/
}, {
key: 'show',
value: function show() {
this.element.style.display = '';
}
/**
* Hide element.
*/
}, {
key: 'hide',
value: function hide() {
this.element.style.display = 'none';
}
/**
* Focus element.
*/
}, {
key: 'focus',
value: function focus() {}
}, {
key: 'destroy',
value: function destroy() {
this.eventManager.destroy();
this.eventManager = null;
this.hot = null;
if (this._element.parentNode) {
this._element.parentNode.removeChild(this._element);
}
this._element = null;
}
}, {
key: 'element',
get: function get() {
if (this.buildState === STATE_BUILDING) {
return this._element;
}
if (this.buildState === STATE_BUILT) {
this.update();
return this._element;
}
this.buildState = STATE_BUILDING;
this.build();
this.buildState = STATE_BUILT;
return this._element;
}
}]);
return BaseUI;
}();
(0, _object.mixin)(BaseUI, _localHooks2.default);
exports.default = BaseUI;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["formulaParser"] = factory();
else
root["formulaParser"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 16);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
exports.nil = new Error('#NULL!');
exports.div0 = new Error('#DIV/0!');
exports.value = new Error('#VALUE!');
exports.ref = new Error('#REF!');
exports.name = new Error('#NAME?');
exports.num = new Error('#NUM!');
exports.na = new Error('#N/A');
exports.error = new Error('#ERROR!');
exports.data = new Error('#GETTING_DATA');
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
exports.flattenShallow = function(array) {
if (!array || !array.reduce) {
return array;
}
return array.reduce(function(a, b) {
var aIsArray = Array.isArray(a);
var bIsArray = Array.isArray(b);
if (aIsArray && bIsArray ) {
return a.concat(b);
}
if (aIsArray) {
a.push(b);
return a;
}
if (bIsArray) {
return [a].concat(b);
}
return [a, b];
});
};
exports.isFlat = function(array) {
if (!array) {
return false;
}
for (var i = 0; i < array.length; ++i) {
if (Array.isArray(array[i])) {
return false;
}
}
return true;
};
exports.flatten = function() {
var result = exports.argsToArray.apply(null, arguments);
while (!exports.isFlat(result)) {
result = exports.flattenShallow(result);
}
return result;
};
exports.argsToArray = function(args) {
var result = [];
exports.arrayEach(args, function(value) {
result.push(value);
});
return result;
};
exports.numbers = function() {
var possibleNumbers = this.flatten.apply(null, arguments);
return possibleNumbers.filter(function(el) {
return typeof el === 'number';
});
};
exports.cleanFloat = function(number) {
var power = 1e14;
return Math.round(number * power) / power;
};
exports.parseBool = function(bool) {
if (typeof bool === 'boolean') {
return bool;
}
if (bool instanceof Error) {
return bool;
}
if (typeof bool === 'number') {
return bool !== 0;
}
if (typeof bool === 'string') {
var up = bool.toUpperCase();
if (up === 'TRUE') {
return true;
}
if (up === 'FALSE') {
return false;
}
}
if (bool instanceof Date && !isNaN(bool)) {
return true;
}
return error.value;
};
exports.parseNumber = function(string) {
if (string === undefined || string === '') {
return error.value;
}
if (!isNaN(string)) {
return parseFloat(string);
}
return error.value;
};
exports.parseNumberArray = function(arr) {
var len;
if (!arr || (len = arr.length) === 0) {
return error.value;
}
var parsed;
while (len--) {
parsed = exports.parseNumber(arr[len]);
if (parsed === error.value) {
return parsed;
}
arr[len] = parsed;
}
return arr;
};
exports.parseMatrix = function(matrix) {
var n;
if (!matrix || (n = matrix.length) === 0) {
return error.value;
}
var pnarr;
for (var i = 0; i < matrix.length; i++) {
pnarr = exports.parseNumberArray(matrix[i]);
matrix[i] = pnarr;
if (pnarr instanceof Error) {
return pnarr;
}
}
return matrix;
};
var d1900 = new Date(1900, 0, 1);
exports.parseDate = function(date) {
if (!isNaN(date)) {
if (date instanceof Date) {
return new Date(date);
}
var d = parseInt(date, 10);
if (d < 0) {
return error.num;
}
if (d <= 60) {
return new Date(d1900.getTime() + (d - 1) * 86400000);
}
return new Date(d1900.getTime() + (d - 2) * 86400000);
}
if (typeof date === 'string') {
date = new Date(date);
if (!isNaN(date)) {
return date;
}
}
return error.value;
};
exports.parseDateArray = function(arr) {
var len = arr.length;
var parsed;
while (len--) {
parsed = this.parseDate(arr[len]);
if (parsed === error.value) {
return parsed;
}
arr[len] = parsed;
}
return arr;
};
exports.anyIsError = function() {
var n = arguments.length;
while (n--) {
if (arguments[n] instanceof Error) {
return true;
}
}
return false;
};
exports.arrayValuesToNumbers = function(arr) {
var n = arr.length;
var el;
while (n--) {
el = arr[n];
if (typeof el === 'number') {
continue;
}
if (el === true) {
arr[n] = 1;
continue;
}
if (el === false) {
arr[n] = 0;
continue;
}
if (typeof el === 'string') {
var number = this.parseNumber(el);
if (number instanceof Error) {
arr[n] = 0;
} else {
arr[n] = number;
}
}
}
return arr;
};
exports.rest = function(array, idx) {
idx = idx || 1;
if (!array || typeof array.slice !== 'function') {
return array;
}
return array.slice(idx);
};
exports.initial = function(array, idx) {
idx = idx || 1;
if (!array || typeof array.slice !== 'function') {
return array;
}
return array.slice(0, array.length - idx);
};
exports.arrayEach = function(array, iteratee) {
var index = -1, length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
};
exports.transpose = function(matrix) {
if(!matrix) {
return error.value;
}
return matrix[0].map(function(col, i) {
return matrix.map(function(row) {
return row[i];
});
});
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _errors;
exports['default'] = error;
exports.isValidStrict = isValidStrict;
var ERROR = exports.ERROR = 'ERROR';
var ERROR_DIV_ZERO = exports.ERROR_DIV_ZERO = 'DIV/0';
var ERROR_NAME = exports.ERROR_NAME = 'NAME';
var ERROR_NOT_AVAILABLE = exports.ERROR_NOT_AVAILABLE = 'N/A';
var ERROR_NULL = exports.ERROR_NULL = 'NULL';
var ERROR_NUM = exports.ERROR_NUM = 'NUM';
var ERROR_REF = exports.ERROR_REF = 'REF';
var ERROR_VALUE = exports.ERROR_VALUE = 'VALUE';
var errors = (_errors = {}, _errors[ERROR] = '#ERROR!', _errors[ERROR_DIV_ZERO] = '#DIV/0!', _errors[ERROR_NAME] = '#NAME?', _errors[ERROR_NOT_AVAILABLE] = '#N/A', _errors[ERROR_NULL] = '#NULL!', _errors[ERROR_NUM] = '#NUM!', _errors[ERROR_REF] = '#REF!', _errors[ERROR_VALUE] = '#VALUE!', _errors);
/**
* Return error type based on provided error id.
*
* @param {String} type Error type.
* @returns {String|null} Returns error id.
*/
function error(type) {
var result = void 0;
type = (type + '').replace(/#|!|\?/g, '');
if (errors[type]) {
result = errors[type];
}
return result ? result : null;
}
/**
* Check if error type is strict valid with knows errors.
*
* @param {String} Error type.
* @return {Boolean}
*/
function isValidStrict(type) {
var valid = false;
for (var i in errors) {
if (Object.prototype.hasOwnProperty.call(errors, i) && errors[i] === type) {
valid = true;
break;
}
}
return valid;
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.toNumber = toNumber;
exports.invertNumber = invertNumber;
/**
* Convert value into number.
*
* @param {String|Number} number
* @returns {*}
*/
function toNumber(number) {
var result = void 0;
if (typeof number === 'number') {
result = number;
} else if (typeof number === 'string') {
result = number.indexOf('.') > -1 ? parseFloat(number) : parseInt(number, 10);
}
return result;
}
/**
* Invert provided number.
*
* @param {Number} number
* @returns {Number} Returns inverted number.
*/
function invertNumber(number) {
return -1 * toNumber(number);
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var utils = __webpack_require__(1);
var error = __webpack_require__(0);
var statistical = __webpack_require__(5);
var information = __webpack_require__(7);
exports.ABS = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.abs(number);
return result;
};
exports.ACOS = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.acos(number);
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.ACOSH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.log(number + Math.sqrt(number * number - 1));
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.ACOT = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.atan(1 / number);
return result;
};
exports.ACOTH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = 0.5 * Math.log((number + 1) / (number - 1));
if (isNaN(result)) {
result = error.num;
}
return result;
};
//TODO: use options
exports.AGGREGATE = function(function_num, options, ref1, ref2) {
function_num = utils.parseNumber(function_num);
options = utils.parseNumber(function_num);
if (utils.anyIsError(function_num, options)) {
return error.value;
}
switch (function_num) {
case 1:
return statistical.AVERAGE(ref1);
case 2:
return statistical.COUNT(ref1);
case 3:
return statistical.COUNTA(ref1);
case 4:
return statistical.MAX(ref1);
case 5:
return statistical.MIN(ref1);
case 6:
return exports.PRODUCT(ref1);
case 7:
return statistical.STDEV.S(ref1);
case 8:
return statistical.STDEV.P(ref1);
case 9:
return exports.SUM(ref1);
case 10:
return statistical.VAR.S(ref1);
case 11:
return statistical.VAR.P(ref1);
case 12:
return statistical.MEDIAN(ref1);
case 13:
return statistical.MODE.SNGL(ref1);
case 14:
return statistical.LARGE(ref1, ref2);
case 15:
return statistical.SMALL(ref1, ref2);
case 16:
return statistical.PERCENTILE.INC(ref1, ref2);
case 17:
return statistical.QUARTILE.INC(ref1, ref2);
case 18:
return statistical.PERCENTILE.EXC(ref1, ref2);
case 19:
return statistical.QUARTILE.EXC(ref1, ref2);
}
};
exports.ARABIC = function(text) {
// Credits: Rafa? Kukawski
if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) {
return error.value;
}
var r = 0;
text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function(i) {
r += {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
}[i];
});
return r;
};
exports.ASIN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.asin(number);
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.ASINH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.log(number + Math.sqrt(number * number + 1));
};
exports.ATAN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.atan(number);
};
exports.ATAN2 = function(number_x, number_y) {
number_x = utils.parseNumber(number_x);
number_y = utils.parseNumber(number_y);
if (utils.anyIsError(number_x, number_y)) {
return error.value;
}
return Math.atan2(number_x, number_y);
};
exports.ATANH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var result = Math.log((1 + number) / (1 - number)) / 2;
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.BASE = function(number, radix, min_length) {
min_length = min_length || 0;
number = utils.parseNumber(number);
radix = utils.parseNumber(radix);
min_length = utils.parseNumber(min_length);
if (utils.anyIsError(number, radix, min_length)) {
return error.value;
}
min_length = (min_length === undefined) ? 0 : min_length;
var result = number.toString(radix);
return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result;
};
exports.CEILING = function(number, significance, mode) {
significance = (significance === undefined) ? 1 : Math.abs(significance);
mode = mode || 0;
number = utils.parseNumber(number);
significance = utils.parseNumber(significance);
mode = utils.parseNumber(mode);
if (utils.anyIsError(number, significance, mode)) {
return error.value;
}
if (significance === 0) {
return 0;
}
var precision = -Math.floor(Math.log(significance) / Math.log(10));
if (number >= 0) {
return exports.ROUND(Math.ceil(number / significance) * significance, precision);
} else {
if (mode === 0) {
return -exports.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision);
} else {
return -exports.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision);
}
}
};
exports.CEILING.MATH = exports.CEILING;
exports.CEILING.PRECISE = exports.CEILING;
exports.COMBIN = function(number, number_chosen) {
number = utils.parseNumber(number);
number_chosen = utils.parseNumber(number_chosen);
if (utils.anyIsError(number, number_chosen)) {
return error.value;
}
return exports.FACT(number) / (exports.FACT(number_chosen) * exports.FACT(number - number_chosen));
};
exports.COMBINA = function(number, number_chosen) {
number = utils.parseNumber(number);
number_chosen = utils.parseNumber(number_chosen);
if (utils.anyIsError(number, number_chosen)) {
return error.value;
}
return (number === 0 && number_chosen === 0) ? 1 : exports.COMBIN(number + number_chosen - 1, number - 1);
};
exports.COS = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.cos(number);
};
exports.COSH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return (Math.exp(number) + Math.exp(-number)) / 2;
};
exports.COT = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return 1 / Math.tan(number);
};
exports.COTH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var e2 = Math.exp(2 * number);
return (e2 + 1) / (e2 - 1);
};
exports.CSC = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return 1 / Math.sin(number);
};
exports.CSCH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return 2 / (Math.exp(number) - Math.exp(-number));
};
exports.DECIMAL = function(number, radix) {
if (arguments.length < 1) {
return error.value;
}
return parseInt(number, radix);
};
exports.DEGREES = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return number * 180 / Math.PI;
};
exports.EVEN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return exports.CEILING(number, -2, -1);
};
exports.EXP = function(number) {
if (arguments.length < 1) {
return error.na;
}
if (typeof number !== 'number' || arguments.length > 1) {
return error.error;
}
number = Math.exp(number);
return number;
};
var MEMOIZED_FACT = [];
exports.FACT = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var n = Math.floor(number);
if (n === 0 || n === 1) {
return 1;
} else if (MEMOIZED_FACT[n] > 0) {
return MEMOIZED_FACT[n];
} else {
MEMOIZED_FACT[n] = exports.FACT(n - 1) * n;
return MEMOIZED_FACT[n];
}
};
exports.FACTDOUBLE = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var n = Math.floor(number);
if (n <= 0) {
return 1;
} else {
return n * exports.FACTDOUBLE(n - 2);
}
};
exports.FLOOR = function(number, significance) {
number = utils.parseNumber(number);
significance = utils.parseNumber(significance);
if (utils.anyIsError(number, significance)) {
return error.value;
}
if (significance === 0) {
return 0;
}
if (!(number > 0 && significance > 0) && !(number < 0 && significance < 0)) {
return error.num;
}
significance = Math.abs(significance);
var precision = -Math.floor(Math.log(significance) / Math.log(10));
if (number >= 0) {
return exports.ROUND(Math.floor(number / significance) * significance, precision);
} else {
return -exports.ROUND(Math.ceil(Math.abs(number) / significance), precision);
}
};
//TODO: Verify
exports.FLOOR.MATH = function(number, significance, mode) {
significance = (significance === undefined) ? 1 : significance;
mode = (mode === undefined) ? 0 : mode;
number = utils.parseNumber(number);
significance = utils.parseNumber(significance);
mode = utils.parseNumber(mode);
if (utils.anyIsError(number, significance, mode)) {
return error.value;
}
if (significance === 0) {
return 0;
}
significance = significance ? Math.abs(significance) : 1;
var precision = -Math.floor(Math.log(significance) / Math.log(10));
if (number >= 0) {
return exports.ROUND(Math.floor(number / significance) * significance, precision);
} else if (mode === 0 || mode === undefined) {
return -exports.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision);
}
return -exports.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision);
};
// Deprecated
exports.FLOOR.PRECISE = exports.FLOOR.MATH;
// adapted http://rosettacode.org/wiki/Greatest_common_divisor#JavaScript
exports.GCD = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var n = range.length;
var r0 = range[0];
var x = r0 < 0 ? -r0 : r0;
for (var i = 1; i < n; i++) {
var ri = range[i];
var y = ri < 0 ? -ri : ri;
while (x && y) {
if (x > y) {
x %= y;
} else {
y %= x;
}
}
x += y;
}
return x;
};
exports.INT = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.floor(number);
};
//TODO: verify
exports.ISO = {
CEILING: exports.CEILING
};
exports.LCM = function() {
// Credits: Jonas Raoni Soares Silva
var o = utils.parseNumberArray(utils.flatten(arguments));
if (o instanceof Error) {
return o;
}
for (var i, j, n, d, r = 1;
(n = o.pop()) !== undefined;) {
while (n > 1) {
if (n % 2) {
for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) {
//empty
}
d = (i <= j) ? i : n;
} else {
d = 2;
}
for (n /= d, r *= d, i = o.length; i;
(o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) {
//empty
}
}
}
return r;
};
exports.LN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.log(number);
};
exports.LN10 = function() {
return Math.log(10);
};
exports.LN2 = function() {
return Math.log(2);
};
exports.LOG10E = function() {
return Math.LOG10E;
};
exports.LOG2E = function() {
return Math.LOG2E;
};
exports.LOG = function(number, base) {
number = utils.parseNumber(number);
base = utils.parseNumber(base);
if (utils.anyIsError(number, base)) {
return error.value;
}
base = (base === undefined) ? 10 : base;
return Math.log(number) / Math.log(base);
};
exports.LOG10 = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.log(number) / Math.log(10);
};
exports.MOD = function(dividend, divisor) {
dividend = utils.parseNumber(dividend);
divisor = utils.parseNumber(divisor);
if (utils.anyIsError(dividend, divisor)) {
return error.value;
}
if (divisor === 0) {
return error.div0;
}
var modulus = Math.abs(dividend % divisor);
return (divisor > 0) ? modulus : -modulus;
};
exports.MROUND = function(number, multiple) {
number = utils.parseNumber(number);
multiple = utils.parseNumber(multiple);
if (utils.anyIsError(number, multiple)) {
return error.value;
}
if (number * multiple < 0) {
return error.num;
}
return Math.round(number / multiple) * multiple;
};
exports.MULTINOMIAL = function() {
var args = utils.parseNumberArray(utils.flatten(arguments));
if (args instanceof Error) {
return args;
}
var sum = 0;
var divisor = 1;
for (var i = 0; i < args.length; i++) {
sum += args[i];
divisor *= exports.FACT(args[i]);
}
return exports.FACT(sum) / divisor;
};
exports.ODD = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var temp = Math.ceil(Math.abs(number));
temp = (temp & 1) ? temp : temp + 1;
return (number > 0) ? temp : -temp;
};
exports.PI = function() {
return Math.PI;
};
exports.E = function() {
return Math.E;
};
exports.POWER = function(number, power) {
number = utils.parseNumber(number);
power = utils.parseNumber(power);
if (utils.anyIsError(number, power)) {
return error.value;
}
var result = Math.pow(number, power);
if (isNaN(result)) {
return error.num;
}
return result;
};
exports.PRODUCT = function() {
var args = utils.parseNumberArray(utils.flatten(arguments));
if (args instanceof Error) {
return args;
}
var result = 1;
for (var i = 0; i < args.length; i++) {
result *= args[i];
}
return result;
};
exports.QUOTIENT = function(numerator, denominator) {
numerator = utils.parseNumber(numerator);
denominator = utils.parseNumber(denominator);
if (utils.anyIsError(numerator, denominator)) {
return error.value;
}
return parseInt(numerator / denominator, 10);
};
exports.RADIANS = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return number * Math.PI / 180;
};
exports.RAND = function() {
return Math.random();
};
exports.RANDBETWEEN = function(bottom, top) {
bottom = utils.parseNumber(bottom);
top = utils.parseNumber(top);
if (utils.anyIsError(bottom, top)) {
return error.value;
}
// Creative Commons Attribution 3.0 License
// Copyright (c) 2012 eqcode
return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1;
};
// TODO
exports.ROMAN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
// The MIT License
// Copyright (c) 2008 Steven Levithan
var digits = String(number).split('');
var key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
var roman = '';
var i = 3;
while (i--) {
roman = (key[+digits.pop() + (i * 10)] || '') + roman;
}
return new Array(+digits.join('') + 1).join('M') + roman;
};
exports.ROUND = function(number, digits) {
number = utils.parseNumber(number);
digits = utils.parseNumber(digits);
if (utils.anyIsError(number, digits)) {
return error.value;
}
return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits);
};
exports.ROUNDDOWN = function(number, digits) {
number = utils.parseNumber(number);
digits = utils.parseNumber(digits);
if (utils.anyIsError(number, digits)) {
return error.value;
}
var sign = (number > 0) ? 1 : -1;
return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits);
};
exports.ROUNDUP = function(number, digits) {
number = utils.parseNumber(number);
digits = utils.parseNumber(digits);
if (utils.anyIsError(number, digits)) {
return error.value;
}
var sign = (number > 0) ? 1 : -1;
return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits);
};
exports.SEC = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return 1 / Math.cos(number);
};
exports.SECH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return 2 / (Math.exp(number) + Math.exp(-number));
};
exports.SERIESSUM = function(x, n, m, coefficients) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
m = utils.parseNumber(m);
coefficients = utils.parseNumberArray(coefficients);
if (utils.anyIsError(x, n, m, coefficients)) {
return error.value;
}
var result = coefficients[0] * Math.pow(x, n);
for (var i = 1; i < coefficients.length; i++) {
result += coefficients[i] * Math.pow(x, n + i * m);
}
return result;
};
exports.SIGN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
if (number < 0) {
return -1;
} else if (number === 0) {
return 0;
} else {
return 1;
}
};
exports.SIN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.sin(number);
};
exports.SINH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return (Math.exp(number) - Math.exp(-number)) / 2;
};
exports.SQRT = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
if (number < 0) {
return error.num;
}
return Math.sqrt(number);
};
exports.SQRTPI = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.sqrt(number * Math.PI);
};
exports.SQRT1_2 = function() {
return 1 / Math.sqrt(2);
};
exports.SQRT2 = function() {
return Math.sqrt(2);
};
exports.SUBTOTAL = function(function_code, ref1) {
function_code = utils.parseNumber(function_code);
if (function_code instanceof Error) {
return function_code;
}
switch (function_code) {
case 1:
return statistical.AVERAGE(ref1);
case 2:
return statistical.COUNT(ref1);
case 3:
return statistical.COUNTA(ref1);
case 4:
return statistical.MAX(ref1);
case 5:
return statistical.MIN(ref1);
case 6:
return exports.PRODUCT(ref1);
case 7:
return statistical.STDEV.S(ref1);
case 8:
return statistical.STDEV.P(ref1);
case 9:
return exports.SUM(ref1);
case 10:
return statistical.VAR.S(ref1);
case 11:
return statistical.VAR.P(ref1);
// no hidden values for us
case 101:
return statistical.AVERAGE(ref1);
case 102:
return statistical.COUNT(ref1);
case 103:
return statistical.COUNTA(ref1);
case 104:
return statistical.MAX(ref1);
case 105:
return statistical.MIN(ref1);
case 106:
return exports.PRODUCT(ref1);
case 107:
return statistical.STDEV.S(ref1);
case 108:
return statistical.STDEV.P(ref1);
case 109:
return exports.SUM(ref1);
case 110:
return statistical.VAR.S(ref1);
case 111:
return statistical.VAR.P(ref1);
}
};
exports.ADD = function (num1, num2) {
if (arguments.length !== 2) {
return error.na;
}
num1 = utils.parseNumber(num1);
num2 = utils.parseNumber(num2);
if (utils.anyIsError(num1, num2)) {
return error.value;
}
return num1 + num2;
};
exports.MINUS = function (num1, num2) {
if (arguments.length !== 2) {
return error.na;
}
num1 = utils.parseNumber(num1);
num2 = utils.parseNumber(num2);
if (utils.anyIsError(num1, num2)) {
return error.value;
}
return num1 - num2;
};
exports.DIVIDE = function (dividend, divisor) {
if (arguments.length !== 2) {
return error.na;
}
dividend = utils.parseNumber(dividend);
divisor = utils.parseNumber(divisor);
if (utils.anyIsError(dividend, divisor)) {
return error.value;
}
if (divisor === 0) {
return error.div0;
}
return dividend / divisor;
};
exports.MULTIPLY = function (factor1, factor2) {
if (arguments.length !== 2) {
return error.na;
}
factor1 = utils.parseNumber(factor1);
factor2 = utils.parseNumber(factor2);
if (utils.anyIsError(factor1, factor2)) {
return error.value;
}
return factor1 * factor2;
};
exports.GTE = function (num1, num2) {
if (arguments.length !== 2) {
return error.na;
}
num1 = utils.parseNumber(num1);
num2 = utils.parseNumber(num2);
if (utils.anyIsError(num1, num2)) {
return error.error;
}
return num1 >= num2;
};
exports.LT = function (num1, num2) {
if (arguments.length !== 2) {
return error.na;
}
num1 = utils.parseNumber(num1);
num2 = utils.parseNumber(num2);
if (utils.anyIsError(num1, num2)) {
return error.error;
}
return num1 < num2;
};
exports.LTE = function (num1, num2) {
if (arguments.length !== 2) {
return error.na;
}
num1 = utils.parseNumber(num1);
num2 = utils.parseNumber(num2);
if (utils.anyIsError(num1, num2)) {
return error.error;
}
return num1 <= num2;
};
exports.EQ = function (value1, value2) {
if (arguments.length !== 2) {
return error.na;
}
return value1 === value2;
};
exports.NE = function (value1, value2) {
if (arguments.length !== 2) {
return error.na;
}
return value1 !== value2;
};
exports.POW = function (base, exponent) {
if (arguments.length !== 2) {
return error.na;
}
base = utils.parseNumber(base);
exponent = utils.parseNumber(exponent);
if (utils.anyIsError(base, exponent)) {
return error.error;
}
return exports.POWER(base, exponent);
};
exports.SUM = function() {
var result = 0;
utils.arrayEach(utils.argsToArray(arguments), function(value) {
if (typeof value === 'number') {
result += value;
} else if (typeof value === 'string') {
var parsed = parseFloat(value);
!isNaN(parsed) && (result += parsed);
} else if (Array.isArray(value)) {
result += exports.SUM.apply(null, value);
}
});
return result;
};
exports.SUMIF = function(range, criteria) {
range = utils.parseNumberArray(utils.flatten(range));
if (range instanceof Error) {
return range;
}
var result = 0;
for (var i = 0; i < range.length; i++) {
result += (eval(range[i] + criteria)) ? range[i] : 0; // jshint ignore:line
}
return result;
};
exports.SUMIFS = function() {
var args = utils.argsToArray(arguments);
var range = utils.parseNumberArray(utils.flatten(args.shift()));
if (range instanceof Error) {
return range;
}
var criteria = args;
var n_range_elements = range.length;
var n_criterias = criteria.length;
var result = 0;
for (var i = 0; i < n_range_elements; i++) {
var el = range[i];
var condition = '';
for (var c = 0; c < n_criterias; c++) {
condition += el + criteria[c];
if (c !== n_criterias - 1) {
condition += '&&';
}
}
if (eval(condition)) { // jshint ignore:line
result += el;
}
}
return result;
};
exports.SUMPRODUCT = function() {
if (!arguments || arguments.length === 0) {
return error.value;
}
var arrays = arguments.length + 1;
var result = 0;
var product;
var k;
var _i;
var _ij;
for (var i = 0; i < arguments[0].length; i++) {
if (!(arguments[0][i] instanceof Array)) {
product = 1;
for (k = 1; k < arrays; k++) {
_i = utils.parseNumber(arguments[k - 1][i]);
if (_i instanceof Error) {
return _i;
}
product *= _i;
}
result += product;
} else {
for (var j = 0; j < arguments[0][i].length; j++) {
product = 1;
for (k = 1; k < arrays; k++) {
_ij = utils.parseNumber(arguments[k - 1][i][j]);
if (_ij instanceof Error) {
return _ij;
}
product *= _ij;
}
result += product;
}
}
}
return result;
};
exports.SUMSQ = function() {
var numbers = utils.parseNumberArray(utils.flatten(arguments));
if (numbers instanceof Error) {
return numbers;
}
var result = 0;
var length = numbers.length;
for (var i = 0; i < length; i++) {
result += (information.ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0;
}
return result;
};
exports.SUMX2MY2 = function(array_x, array_y) {
array_x = utils.parseNumberArray(utils.flatten(array_x));
array_y = utils.parseNumberArray(utils.flatten(array_y));
if (utils.anyIsError(array_x, array_y)) {
return error.value;
}
var result = 0;
for (var i = 0; i < array_x.length; i++) {
result += array_x[i] * array_x[i] - array_y[i] * array_y[i];
}
return result;
};
exports.SUMX2PY2 = function(array_x, array_y) {
array_x = utils.parseNumberArray(utils.flatten(array_x));
array_y = utils.parseNumberArray(utils.flatten(array_y));
if (utils.anyIsError(array_x, array_y)) {
return error.value;
}
var result = 0;
array_x = utils.parseNumberArray(utils.flatten(array_x));
array_y = utils.parseNumberArray(utils.flatten(array_y));
for (var i = 0; i < array_x.length; i++) {
result += array_x[i] * array_x[i] + array_y[i] * array_y[i];
}
return result;
};
exports.SUMXMY2 = function(array_x, array_y) {
array_x = utils.parseNumberArray(utils.flatten(array_x));
array_y = utils.parseNumberArray(utils.flatten(array_y));
if (utils.anyIsError(array_x, array_y)) {
return error.value;
}
var result = 0;
array_x = utils.flatten(array_x);
array_y = utils.flatten(array_y);
for (var i = 0; i < array_x.length; i++) {
result += Math.pow(array_x[i] - array_y[i], 2);
}
return result;
};
exports.TAN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return Math.tan(number);
};
exports.TANH = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
var e2 = Math.exp(2 * number);
return (e2 - 1) / (e2 + 1);
};
exports.TRUNC = function(number, digits) {
digits = (digits === undefined) ? 0 : digits;
number = utils.parseNumber(number);
digits = utils.parseNumber(digits);
if (utils.anyIsError(number, digits)) {
return error.value;
}
var sign = (number > 0) ? 1 : -1;
return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits);
};
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var mathTrig = __webpack_require__(4);
var text = __webpack_require__(6);
var jStat = __webpack_require__(11).jStat;
var utils = __webpack_require__(1);
var error = __webpack_require__(0);
var misc = __webpack_require__(12);
var SQRT2PI = 2.5066282746310002;
exports.AVEDEV = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
return jStat.sum(jStat(range).subtract(jStat.mean(range)).abs()[0]) / range.length;
};
exports.AVERAGE = function() {
var range = utils.numbers(utils.flatten(arguments));
var n = range.length;
var sum = 0;
var count = 0;
var result;
for (var i = 0; i < n; i++) {
sum += range[i];
count += 1;
}
result = sum / count;
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.AVERAGEA = function() {
var range = utils.flatten(arguments);
var n = range.length;
var sum = 0;
var count = 0;
var result;
for (var i = 0; i < n; i++) {
var el = range[i];
if (typeof el === 'number') {
sum += el;
}
if (el === true) {
sum++;
}
if (el !== null) {
count++;
}
}
result = sum / count;
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.AVERAGEIF = function(range, criteria, average_range) {
if (arguments.length <= 1) {
return error.na;
}
average_range = average_range || range;
range = utils.flatten(range);
average_range = utils.parseNumberArray(utils.flatten(average_range));
if (average_range instanceof Error) {
return average_range;
}
var average_count = 0;
var result = 0;
for (var i = 0; i < range.length; i++) {
if (eval(range[i] + criteria)) { // jshint ignore:line
result += average_range[i];
average_count++;
}
}
return result / average_count;
};
exports.AVERAGEIFS = function() {
// Does not work with multi dimensional ranges yet!
//http://office.microsoft.com/en-001/excel-help/averageifs-function-HA010047493.aspx
var args = utils.argsToArray(arguments);
var criteria = (args.length - 1) / 2;
var range = utils.flatten(args[0]);
var count = 0;
var result = 0;
for (var i = 0; i < range.length; i++) {
var condition = '';
for (var j = 0; j < criteria; j++) {
condition += args[2 * j + 1][i] + args[2 * j + 2];
if (j !== criteria - 1) {
condition += '&&';
}
}
if (eval(condition)) { // jshint ignore:line
result += range[i];
count++;
}
}
var average = result / count;
if (isNaN(average)) {
return 0;
} else {
return average;
}
};
exports.BETA = {};
exports.BETA.DIST = function(x, alpha, beta, cumulative, A, B) {
if (arguments.length < 4) {
return error.value;
}
A = (A === undefined) ? 0 : A;
B = (B === undefined) ? 1 : B;
x = utils.parseNumber(x);
alpha = utils.parseNumber(alpha);
beta = utils.parseNumber(beta);
A = utils.parseNumber(A);
B = utils.parseNumber(B);
if (utils.anyIsError(x, alpha, beta, A, B)) {
return error.value;
}
x = (x - A) / (B - A);
return (cumulative) ? jStat.beta.cdf(x, alpha, beta) : jStat.beta.pdf(x, alpha, beta);
};
exports.BETA.INV = function(probability, alpha, beta, A, B) {
A = (A === undefined) ? 0 : A;
B = (B === undefined) ? 1 : B;
probability = utils.parseNumber(probability);
alpha = utils.parseNumber(alpha);
beta = utils.parseNumber(beta);
A = utils.parseNumber(A);
B = utils.parseNumber(B);
if (utils.anyIsError(probability, alpha, beta, A, B)) {
return error.value;
}
return jStat.beta.inv(probability, alpha, beta) * (B - A) + A;
};
exports.BINOM = {};
exports.BINOM.DIST = function(successes, trials, probability, cumulative) {
successes = utils.parseNumber(successes);
trials = utils.parseNumber(trials);
probability = utils.parseNumber(probability);
cumulative = utils.parseNumber(cumulative);
if (utils.anyIsError(successes, trials, probability, cumulative)) {
return error.value;
}
return (cumulative) ? jStat.binomial.cdf(successes, trials, probability) : jStat.binomial.pdf(successes, trials, probability);
};
exports.BINOM.DIST.RANGE = function(trials, probability, successes, successes2) {
successes2 = (successes2 === undefined) ? successes : successes2;
trials = utils.parseNumber(trials);
probability = utils.parseNumber(probability);
successes = utils.parseNumber(successes);
successes2 = utils.parseNumber(successes2);
if (utils.anyIsError(trials, probability, successes, successes2)) {
return error.value;
}
var result = 0;
for (var i = successes; i <= successes2; i++) {
result += mathTrig.COMBIN(trials, i) * Math.pow(probability, i) * Math.pow(1 - probability, trials - i);
}
return result;
};
exports.BINOM.INV = function(trials, probability, alpha) {
trials = utils.parseNumber(trials);
probability = utils.parseNumber(probability);
alpha = utils.parseNumber(alpha);
if (utils.anyIsError(trials, probability, alpha)) {
return error.value;
}
var x = 0;
while (x <= trials) {
if (jStat.binomial.cdf(x, trials, probability) >= alpha) {
return x;
}
x++;
}
};
exports.CHISQ = {};
exports.CHISQ.DIST = function(x, k, cumulative) {
x = utils.parseNumber(x);
k = utils.parseNumber(k);
if (utils.anyIsError(x, k)) {
return error.value;
}
return (cumulative) ? jStat.chisquare.cdf(x, k) : jStat.chisquare.pdf(x, k);
};
exports.CHISQ.DIST.RT = function(x, k) {
if (!x | !k) {
return error.na;
}
if (x < 1 || k > Math.pow(10, 10)) {
return error.num;
}
if ((typeof x !== 'number') || (typeof k !== 'number')) {
return error.value;
}
return 1 - jStat.chisquare.cdf(x, k);
};
exports.CHISQ.INV = function(probability, k) {
probability = utils.parseNumber(probability);
k = utils.parseNumber(k);
if (utils.anyIsError(probability, k)) {
return error.value;
}
return jStat.chisquare.inv(probability, k);
};
exports.CHISQ.INV.RT = function(p, k) {
if (!p | !k) {
return error.na;
}
if (p < 0 || p > 1 || k < 1 || k > Math.pow(10, 10)) {
return error.num;
}
if ((typeof p !== 'number') || (typeof k !== 'number')) {
return error.value;
}
return jStat.chisquare.inv(1.0 - p, k);
};
exports.CHISQ.TEST = function(observed, expected) {
if (arguments.length !== 2) {
return error.na;
}
if ((!(observed instanceof Array)) || (!(expected instanceof Array))) {
return error.value;
}
if (observed.length !== expected.length) {
return error.value;
}
if (observed[0] && expected[0] &&
observed[0].length !== expected[0].length) {
return error.value;
}
var row = observed.length;
var tmp, i, j;
// Convert single-dimension array into two-dimension array
for (i = 0; i < row; i ++) {
if (!(observed[i] instanceof Array)) {
tmp = observed[i];
observed[i] = [];
observed[i].push(tmp);
}
if (!(expected[i] instanceof Array)) {
tmp = expected[i];
expected[i] = [];
expected[i].push(tmp);
}
}
var col = observed[0].length;
var dof = (col === 1) ? row-1 : (row-1)*(col-1);
var xsqr = 0;
var Pi =Math.PI;
for (i = 0; i < row; i ++) {
for (j = 0; j < col; j ++) {
xsqr += Math.pow((observed[i][j] - expected[i][j]), 2) / expected[i][j];
}
}
// Get independency by X square and its degree of freedom
function ChiSq(xsqr, dof) {
var p = Math.exp(-0.5 * xsqr);
if((dof%2) === 1) {
p = p * Math.sqrt(2 * xsqr/Pi);
}
var k = dof;
while(k >= 2) {
p = p * xsqr/k;
k = k - 2;
}
var t = p;
var a = dof;
while (t > 0.0000000001*p) {
a = a + 2;
t = t * xsqr/a;
p = p + t;
}
return 1-p;
}
return Math.round(ChiSq(xsqr, dof) * 1000000) / 1000000;
};
exports.COLUMN = function(matrix, index) {
if (arguments.length !== 2) {
return error.na;
}
if (index < 0) {
return error.num;
}
if (!(matrix instanceof Array) || (typeof index !== 'number')) {
return error.value;
}
if (matrix.length === 0) {
return undefined;
}
return jStat.col(matrix, index);
};
exports.COLUMNS = function(matrix) {
if (arguments.length !== 1) {
return error.na;
}
if (!(matrix instanceof Array)) {
return error.value;
}
if (matrix.length === 0) {
return 0;
}
return jStat.cols(matrix);
};
exports.CONFIDENCE = {};
exports.CONFIDENCE.NORM = function(alpha, sd, n) {
alpha = utils.parseNumber(alpha);
sd = utils.parseNumber(sd);
n = utils.parseNumber(n);
if (utils.anyIsError(alpha, sd, n)) {
return error.value;
}
return jStat.normalci(1, alpha, sd, n)[1] - 1;
};
exports.CONFIDENCE.T = function(alpha, sd, n) {
alpha = utils.parseNumber(alpha);
sd = utils.parseNumber(sd);
n = utils.parseNumber(n);
if (utils.anyIsError(alpha, sd, n)) {
return error.value;
}
return jStat.tci(1, alpha, sd, n)[1] - 1;
};
exports.CORREL = function(array1, array2) {
array1 = utils.parseNumberArray(utils.flatten(array1));
array2 = utils.parseNumberArray(utils.flatten(array2));
if (utils.anyIsError(array1, array2)) {
return error.value;
}
return jStat.corrcoeff(array1, array2);
};
exports.COUNT = function() {
return utils.numbers(utils.flatten(arguments)).length;
};
exports.COUNTA = function() {
var range = utils.flatten(arguments);
return range.length - exports.COUNTBLANK(range);
};
exports.COUNTIN = function (range, value) {
var result = 0;
range = utils.flatten(range);
for (var i = 0; i < range.length; i++) {
if (range[i] === value) {
result++;
}
}
return result;
};
exports.COUNTBLANK = function() {
var range = utils.flatten(arguments);
var blanks = 0;
var element;
for (var i = 0; i < range.length; i++) {
element = range[i];
if (element === null || element === '') {
blanks++;
}
}
return blanks;
};
exports.COUNTIF = function(range, criteria) {
range = utils.flatten(range);
if (!/[<>=!]/.test(criteria)) {
criteria = '=="' + criteria + '"';
}
var matches = 0;
for (var i = 0; i < range.length; i++) {
if (typeof range[i] !== 'string') {
if (eval(range[i] + criteria)) { // jshint ignore:line
matches++;
}
} else {
if (eval('"' + range[i] + '"' + criteria)) { // jshint ignore:line
matches++;
}
}
}
return matches;
};
exports.COUNTIFS = function() {
var args = utils.argsToArray(arguments);
var results = new Array(utils.flatten(args[0]).length);
for (var i = 0; i < results.length; i++) {
results[i] = true;
}
for (i = 0; i < args.length; i += 2) {
var range = utils.flatten(args[i]);
var criteria = args[i + 1];
if (!/[<>=!]/.test(criteria)) {
criteria = '=="' + criteria + '"';
}
for (var j = 0; j < range.length; j++) {
if (typeof range[j] !== 'string') {
results[j] = results[j] && eval(range[j] + criteria); // jshint ignore:line
} else {
results[j] = results[j] && eval('"' + range[j] + '"' + criteria); // jshint ignore:line
}
}
}
var result = 0;
for (i = 0; i < results.length; i++) {
if (results[i]) {
result++;
}
}
return result;
};
exports.COUNTUNIQUE = function () {
return misc.UNIQUE.apply(null, utils.flatten(arguments)).length;
};
exports.COVARIANCE = {};
exports.COVARIANCE.P = function(array1, array2) {
array1 = utils.parseNumberArray(utils.flatten(array1));
array2 = utils.parseNumberArray(utils.flatten(array2));
if (utils.anyIsError(array1, array2)) {
return error.value;
}
var mean1 = jStat.mean(array1);
var mean2 = jStat.mean(array2);
var result = 0;
var n = array1.length;
for (var i = 0; i < n; i++) {
result += (array1[i] - mean1) * (array2[i] - mean2);
}
return result / n;
};
exports.COVARIANCE.S = function(array1, array2) {
array1 = utils.parseNumberArray(utils.flatten(array1));
array2 = utils.parseNumberArray(utils.flatten(array2));
if (utils.anyIsError(array1, array2)) {
return error.value;
}
return jStat.covariance(array1, array2);
};
exports.DEVSQ = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var mean = jStat.mean(range);
var result = 0;
for (var i = 0; i < range.length; i++) {
result += Math.pow((range[i] - mean), 2);
}
return result;
};
exports.EXPON = {};
exports.EXPON.DIST = function(x, lambda, cumulative) {
x = utils.parseNumber(x);
lambda = utils.parseNumber(lambda);
if (utils.anyIsError(x, lambda)) {
return error.value;
}
return (cumulative) ? jStat.exponential.cdf(x, lambda) : jStat.exponential.pdf(x, lambda);
};
exports.F = {};
exports.F.DIST = function(x, d1, d2, cumulative) {
x = utils.parseNumber(x);
d1 = utils.parseNumber(d1);
d2 = utils.parseNumber(d2);
if (utils.anyIsError(x, d1, d2)) {
return error.value;
}
return (cumulative) ? jStat.centralF.cdf(x, d1, d2) : jStat.centralF.pdf(x, d1, d2);
};
exports.F.DIST.RT = function(x, d1, d2) {
if (arguments.length !== 3) {
return error.na;
}
if (x < 0 || d1 < 1 || d2 < 1) {
return error.num;
}
if ((typeof x !== 'number') || (typeof d1 !== 'number') || (typeof d2 !== 'number')) {
return error.value;
}
return 1 - jStat.centralF.cdf(x, d1, d2);
};
exports.F.INV = function(probability, d1, d2) {
probability = utils.parseNumber(probability);
d1 = utils.parseNumber(d1);
d2 = utils.parseNumber(d2);
if (utils.anyIsError(probability, d1, d2)) {
return error.value;
}
if (probability <= 0.0 || probability > 1.0) {
return error.num;
}
return jStat.centralF.inv(probability, d1, d2);
};
exports.F.INV.RT = function(p, d1, d2) {
if (arguments.length !== 3) {
return error.na;
}
if (p < 0 || p > 1 || d1 < 1 || d1 > Math.pow(10, 10) || d2 < 1 || d2 > Math.pow(10, 10)) {
return error.num;
}
if ((typeof p !== 'number') || (typeof d1 !== 'number') || (typeof d2 !== 'number')) {
return error.value;
}
return jStat.centralF.inv(1.0 - p, d1, d2);
};
exports.F.TEST = function(array1, array2) {
if (!array1 || !array2) {
return error.na;
}
if (!(array1 instanceof Array) || !(array2 instanceof Array)) {
return error.na;
}
if (array1.length < 2 || array2.length < 2) {
return error.div0;
}
var sumOfSquares = function(values, x1) {
var sum = 0;
for (var i = 0; i < values.length; i++) {
sum +=Math.pow((values[i] - x1), 2);
}
return sum;
};
var x1 = mathTrig.SUM(array1) / array1.length;
var x2 = mathTrig.SUM(array2) / array2.length;
var sum1 = sumOfSquares(array1, x1) / (array1.length - 1);
var sum2 = sumOfSquares(array2, x2) / (array2.length - 1);
return sum1 / sum2;
};
exports.FISHER = function(x) {
x = utils.parseNumber(x);
if (x instanceof Error) {
return x;
}
return Math.log((1 + x) / (1 - x)) / 2;
};
exports.FISHERINV = function(y) {
y = utils.parseNumber(y);
if (y instanceof Error) {
return y;
}
var e2y = Math.exp(2 * y);
return (e2y - 1) / (e2y + 1);
};
exports.FORECAST = function(x, data_y, data_x) {
x = utils.parseNumber(x);
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(x, data_y, data_x)) {
return error.value;
}
var xmean = jStat.mean(data_x);
var ymean = jStat.mean(data_y);
var n = data_x.length;
var num = 0;
var den = 0;
for (var i = 0; i < n; i++) {
num += (data_x[i] - xmean) * (data_y[i] - ymean);
den += Math.pow(data_x[i] - xmean, 2);
}
var b = num / den;
var a = ymean - b * xmean;
return a + b * x;
};
exports.FREQUENCY = function(data, bins) {
data = utils.parseNumberArray(utils.flatten(data));
bins = utils.parseNumberArray(utils.flatten(bins));
if (utils.anyIsError(data, bins)) {
return error.value;
}
var n = data.length;
var b = bins.length;
var r = [];
for (var i = 0; i <= b; i++) {
r[i] = 0;
for (var j = 0; j < n; j++) {
if (i === 0) {
if (data[j] <= bins[0]) {
r[0] += 1;
}
} else if (i < b) {
if (data[j] > bins[i - 1] && data[j] <= bins[i]) {
r[i] += 1;
}
} else if (i === b) {
if (data[j] > bins[b - 1]) {
r[b] += 1;
}
}
}
}
return r;
};
exports.GAMMA = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
if (number === 0) {
return error.num;
}
if (parseInt(number, 10) === number && number < 0) {
return error.num;
}
return jStat.gammafn(number);
};
exports.GAMMA.DIST = function(value, alpha, beta, cumulative) {
if (arguments.length !== 4) {
return error.na;
}
if (value < 0 || alpha <= 0 || beta <= 0) {
return error.value;
}
if ((typeof value !== 'number') || (typeof alpha !== 'number') || (typeof beta !== 'number')) {
return error.value;
}
return cumulative ? jStat.gamma.cdf(value, alpha, beta, true) : jStat.gamma.pdf(value, alpha, beta, false);
};
exports.GAMMA.INV = function(probability, alpha, beta) {
if (arguments.length !== 3) {
return error.na;
}
if (probability < 0 || probability > 1 || alpha <= 0 || beta <= 0) {
return error.num;
}
if ((typeof probability !== 'number') || (typeof alpha !== 'number') || (typeof beta !== 'number')) {
return error.value;
}
return jStat.gamma.inv(probability, alpha, beta);
};
exports.GAMMALN = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return jStat.gammaln(number);
};
exports.GAMMALN.PRECISE = function(x) {
if (arguments.length !== 1) {
return error.na;
}
if (x <= 0) {
return error.num;
}
if (typeof x !== 'number') {
return error.value;
}
return jStat.gammaln(x);
};
exports.GAUSS = function(z) {
z = utils.parseNumber(z);
if (z instanceof Error) {
return z;
}
return jStat.normal.cdf(z, 0, 1) - 0.5;
};
exports.GEOMEAN = function() {
var args = utils.parseNumberArray(utils.flatten(arguments));
if (args instanceof Error) {
return args;
}
return jStat.geomean(args);
};
exports.GROWTH = function(known_y, known_x, new_x, use_const) {
// Credits: Ilmari Karonen (http://stackoverflow.com/questions/14161990/how-to-implement-growth-function-in-javascript)
known_y = utils.parseNumberArray(known_y);
if (known_y instanceof Error) {
return known_y;
}
// Default values for optional parameters:
var i;
if (known_x === undefined) {
known_x = [];
for (i = 1; i <= known_y.length; i++) {
known_x.push(i);
}
}
if (new_x === undefined) {
new_x = [];
for (i = 1; i <= known_y.length; i++) {
new_x.push(i);
}
}
known_x = utils.parseNumberArray(known_x);
new_x = utils.parseNumberArray(new_x);
if (utils.anyIsError(known_x, new_x)) {
return error.value;
}
if (use_const === undefined) {
use_const = true;
}
// Calculate sums over the data:
var n = known_y.length;
var avg_x = 0;
var avg_y = 0;
var avg_xy = 0;
var avg_xx = 0;
for (i = 0; i < n; i++) {
var x = known_x[i];
var y = Math.log(known_y[i]);
avg_x += x;
avg_y += y;
avg_xy += x * y;
avg_xx += x * x;
}
avg_x /= n;
avg_y /= n;
avg_xy /= n;
avg_xx /= n;
// Compute linear regression coefficients:
var beta;
var alpha;
if (use_const) {
beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x);
alpha = avg_y - beta * avg_x;
} else {
beta = avg_xy / avg_xx;
alpha = 0;
}
// Compute and return result array:
var new_y = [];
for (i = 0; i < new_x.length; i++) {
new_y.push(Math.exp(alpha + beta * new_x[i]));
}
return new_y;
};
exports.HARMEAN = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var n = range.length;
var den = 0;
for (var i = 0; i < n; i++) {
den += 1 / range[i];
}
return n / den;
};
exports.HYPGEOM = {};
exports.HYPGEOM.DIST = function(x, n, M, N, cumulative) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
M = utils.parseNumber(M);
N = utils.parseNumber(N);
if (utils.anyIsError(x, n, M, N)) {
return error.value;
}
function pdf(x, n, M, N) {
return mathTrig.COMBIN(M, x) * mathTrig.COMBIN(N - M, n - x) / mathTrig.COMBIN(N, n);
}
function cdf(x, n, M, N) {
var result = 0;
for (var i = 0; i <= x; i++) {
result += pdf(i, n, M, N);
}
return result;
}
return (cumulative) ? cdf(x, n, M, N) : pdf(x, n, M, N);
};
exports.INTERCEPT = function(known_y, known_x) {
known_y = utils.parseNumberArray(known_y);
known_x = utils.parseNumberArray(known_x);
if (utils.anyIsError(known_y, known_x)) {
return error.value;
}
if (known_y.length !== known_x.length) {
return error.na;
}
return exports.FORECAST(0, known_y, known_x);
};
exports.KURT = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var mean = jStat.mean(range);
var n = range.length;
var sigma = 0;
for (var i = 0; i < n; i++) {
sigma += Math.pow(range[i] - mean, 4);
}
sigma = sigma / Math.pow(jStat.stdev(range, true), 4);
return ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3));
};
exports.LARGE = function(range, k) {
range = utils.parseNumberArray(utils.flatten(range));
k = utils.parseNumber(k);
if (utils.anyIsError(range, k)) {
return range;
}
return range.sort(function(a, b) {
return b - a;
})[k - 1];
};
exports.LINEST = function(data_y, data_x) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(data_y, data_x)) {
return error.value;
}
var ymean = jStat.mean(data_y);
var xmean = jStat.mean(data_x);
var n = data_x.length;
var num = 0;
var den = 0;
for (var i = 0; i < n; i++) {
num += (data_x[i] - xmean) * (data_y[i] - ymean);
den += Math.pow(data_x[i] - xmean, 2);
}
var m = num / den;
var b = ymean - m * xmean;
return [m, b];
};
// According to Microsoft:
// http://office.microsoft.com/en-us/starter-help/logest-function-HP010342665.aspx
// LOGEST returns are based on the following linear model:
// ln y = x1 ln m1 + ... + xn ln mn + ln b
exports.LOGEST = function(data_y, data_x) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(data_y, data_x)) {
return error.value;
}
for (var i = 0; i < data_y.length; i ++) {
data_y[i] = Math.log(data_y[i]);
}
var result = exports.LINEST(data_y, data_x);
result[0] = Math.round(Math.exp(result[0])*1000000)/1000000;
result[1] = Math.round(Math.exp(result[1])*1000000)/1000000;
return result;
};
exports.LOGNORM = {};
exports.LOGNORM.DIST = function(x, mean, sd, cumulative) {
x = utils.parseNumber(x);
mean = utils.parseNumber(mean);
sd = utils.parseNumber(sd);
if (utils.anyIsError(x, mean, sd)) {
return error.value;
}
return (cumulative) ? jStat.lognormal.cdf(x, mean, sd) : jStat.lognormal.pdf(x, mean, sd);
};
exports.LOGNORM.INV = function(probability, mean, sd) {
probability = utils.parseNumber(probability);
mean = utils.parseNumber(mean);
sd = utils.parseNumber(sd);
if (utils.anyIsError(probability, mean, sd)) {
return error.value;
}
return jStat.lognormal.inv(probability, mean, sd);
};
exports.MAX = function() {
var range = utils.numbers(utils.flatten(arguments));
return (range.length === 0) ? 0 : Math.max.apply(Math, range);
};
exports.MAXA = function() {
var range = utils.arrayValuesToNumbers(utils.flatten(arguments));
return (range.length === 0) ? 0 : Math.max.apply(Math, range);
};
exports.MEDIAN = function() {
var range = utils.arrayValuesToNumbers(utils.flatten(arguments));
var result = jStat.median(range);
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.MIN = function() {
var range = utils.numbers(utils.flatten(arguments));
return (range.length === 0) ? 0 : Math.min.apply(Math, range);
};
exports.MINA = function() {
var range = utils.arrayValuesToNumbers(utils.flatten(arguments));
return (range.length === 0) ? 0 : Math.min.apply(Math, range);
};
exports.MODE = {};
exports.MODE.MULT = function() {
// Credits: Roönaän
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var n = range.length;
var count = {};
var maxItems = [];
var max = 0;
var currentItem;
for (var i = 0; i < n; i++) {
currentItem = range[i];
count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1;
if (count[currentItem] > max) {
max = count[currentItem];
maxItems = [];
}
if (count[currentItem] === max) {
maxItems[maxItems.length] = currentItem;
}
}
return maxItems;
};
exports.MODE.SNGL = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
return exports.MODE.MULT(range).sort(function(a, b) {
return a - b;
})[0];
};
exports.NEGBINOM = {};
exports.NEGBINOM.DIST = function(k, r, p, cumulative) {
k = utils.parseNumber(k);
r = utils.parseNumber(r);
p = utils.parseNumber(p);
if (utils.anyIsError(k, r, p)) {
return error.value;
}
return (cumulative) ? jStat.negbin.cdf(k, r, p) : jStat.negbin.pdf(k, r, p);
};
exports.NORM = {};
exports.NORM.DIST = function(x, mean, sd, cumulative) {
x = utils.parseNumber(x);
mean = utils.parseNumber(mean);
sd = utils.parseNumber(sd);
if (utils.anyIsError(x, mean, sd)) {
return error.value;
}
if (sd <= 0) {
return error.num;
}
// Return normal distribution computed by jStat [http://jstat.org]
return (cumulative) ? jStat.normal.cdf(x, mean, sd) : jStat.normal.pdf(x, mean, sd);
};
exports.NORM.INV = function(probability, mean, sd) {
probability = utils.parseNumber(probability);
mean = utils.parseNumber(mean);
sd = utils.parseNumber(sd);
if (utils.anyIsError(probability, mean, sd)) {
return error.value;
}
return jStat.normal.inv(probability, mean, sd);
};
exports.NORM.S = {};
exports.NORM.S.DIST = function(z, cumulative) {
z = utils.parseNumber(z);
if (z instanceof Error) {
return error.value;
}
return (cumulative) ? jStat.normal.cdf(z, 0, 1) : jStat.normal.pdf(z, 0, 1);
};
exports.NORM.S.INV = function(probability) {
probability = utils.parseNumber(probability);
if (probability instanceof Error) {
return error.value;
}
return jStat.normal.inv(probability, 0, 1);
};
exports.PEARSON = function(data_x, data_y) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(data_y, data_x)) {
return error.value;
}
var xmean = jStat.mean(data_x);
var ymean = jStat.mean(data_y);
var n = data_x.length;
var num = 0;
var den1 = 0;
var den2 = 0;
for (var i = 0; i < n; i++) {
num += (data_x[i] - xmean) * (data_y[i] - ymean);
den1 += Math.pow(data_x[i] - xmean, 2);
den2 += Math.pow(data_y[i] - ymean, 2);
}
return num / Math.sqrt(den1 * den2);
};
exports.PERCENTILE = {};
exports.PERCENTILE.EXC = function(array, k) {
array = utils.parseNumberArray(utils.flatten(array));
k = utils.parseNumber(k);
if (utils.anyIsError(array, k)) {
return error.value;
}
array = array.sort(function(a, b) {
{
return a - b;
}
});
var n = array.length;
if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) {
return error.num;
}
var l = k * (n + 1) - 1;
var fl = Math.floor(l);
return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl]));
};
exports.PERCENTILE.INC = function(array, k) {
array = utils.parseNumberArray(utils.flatten(array));
k = utils.parseNumber(k);
if (utils.anyIsError(array, k)) {
return error.value;
}
array = array.sort(function(a, b) {
return a - b;
});
var n = array.length;
var l = k * (n - 1);
var fl = Math.floor(l);
return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl]));
};
exports.PERCENTRANK = {};
exports.PERCENTRANK.EXC = function(array, x, significance) {
significance = (significance === undefined) ? 3 : significance;
array = utils.parseNumberArray(utils.flatten(array));
x = utils.parseNumber(x);
significance = utils.parseNumber(significance);
if (utils.anyIsError(array, x, significance)) {
return error.value;
}
array = array.sort(function(a, b) {
return a - b;
});
var uniques = misc.UNIQUE.apply(null, array);
var n = array.length;
var m = uniques.length;
var power = Math.pow(10, significance);
var result = 0;
var match = false;
var i = 0;
while (!match && i < m) {
if (x === uniques[i]) {
result = (array.indexOf(uniques[i]) + 1) / (n + 1);
match = true;
} else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) {
result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1);
match = true;
}
i++;
}
return Math.floor(result * power) / power;
};
exports.PERCENTRANK.INC = function(array, x, significance) {
significance = (significance === undefined) ? 3 : significance;
array = utils.parseNumberArray(utils.flatten(array));
x = utils.parseNumber(x);
significance = utils.parseNumber(significance);
if (utils.anyIsError(array, x, significance)) {
return error.value;
}
array = array.sort(function(a, b) {
return a - b;
});
var uniques = misc.UNIQUE.apply(null, array);
var n = array.length;
var m = uniques.length;
var power = Math.pow(10, significance);
var result = 0;
var match = false;
var i = 0;
while (!match && i < m) {
if (x === uniques[i]) {
result = array.indexOf(uniques[i]) / (n - 1);
match = true;
} else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) {
result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1);
match = true;
}
i++;
}
return Math.floor(result * power) / power;
};
exports.PERMUT = function(number, number_chosen) {
number = utils.parseNumber(number);
number_chosen = utils.parseNumber(number_chosen);
if (utils.anyIsError(number, number_chosen)) {
return error.value;
}
return mathTrig.FACT(number) / mathTrig.FACT(number - number_chosen);
};
exports.PERMUTATIONA = function(number, number_chosen) {
number = utils.parseNumber(number);
number_chosen = utils.parseNumber(number_chosen);
if (utils.anyIsError(number, number_chosen)) {
return error.value;
}
return Math.pow(number, number_chosen);
};
exports.PHI = function(x) {
x = utils.parseNumber(x);
if (x instanceof Error) {
return error.value;
}
return Math.exp(-0.5 * x * x) / SQRT2PI;
};
exports.POISSON = {};
exports.POISSON.DIST = function(x, mean, cumulative) {
x = utils.parseNumber(x);
mean = utils.parseNumber(mean);
if (utils.anyIsError(x, mean)) {
return error.value;
}
return (cumulative) ? jStat.poisson.cdf(x, mean) : jStat.poisson.pdf(x, mean);
};
exports.PROB = function(range, probability, lower, upper) {
if (lower === undefined) {
return 0;
}
upper = (upper === undefined) ? lower : upper;
range = utils.parseNumberArray(utils.flatten(range));
probability = utils.parseNumberArray(utils.flatten(probability));
lower = utils.parseNumber(lower);
upper = utils.parseNumber(upper);
if (utils.anyIsError(range, probability, lower, upper)) {
return error.value;
}
if (lower === upper) {
return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0;
}
var sorted = range.sort(function(a, b) {
return a - b;
});
var n = sorted.length;
var result = 0;
for (var i = 0; i < n; i++) {
if (sorted[i] >= lower && sorted[i] <= upper) {
result += probability[range.indexOf(sorted[i])];
}
}
return result;
};
exports.QUARTILE = {};
exports.QUARTILE.EXC = function(range, quart) {
range = utils.parseNumberArray(utils.flatten(range));
quart = utils.parseNumber(quart);
if (utils.anyIsError(range, quart)) {
return error.value;
}
switch (quart) {
case 1:
return exports.PERCENTILE.EXC(range, 0.25);
case 2:
return exports.PERCENTILE.EXC(range, 0.5);
case 3:
return exports.PERCENTILE.EXC(range, 0.75);
default:
return error.num;
}
};
exports.QUARTILE.INC = function(range, quart) {
range = utils.parseNumberArray(utils.flatten(range));
quart = utils.parseNumber(quart);
if (utils.anyIsError(range, quart)) {
return error.value;
}
switch (quart) {
case 1:
return exports.PERCENTILE.INC(range, 0.25);
case 2:
return exports.PERCENTILE.INC(range, 0.5);
case 3:
return exports.PERCENTILE.INC(range, 0.75);
default:
return error.num;
}
};
exports.RANK = {};
exports.RANK.AVG = function(number, range, order) {
number = utils.parseNumber(number);
range = utils.parseNumberArray(utils.flatten(range));
if (utils.anyIsError(number, range)) {
return error.value;
}
range = utils.flatten(range);
order = order || false;
var sort = (order) ? function(a, b) {
return a - b;
} : function(a, b) {
return b - a;
};
range = range.sort(sort);
var length = range.length;
var count = 0;
for (var i = 0; i < length; i++) {
if (range[i] === number) {
count++;
}
}
return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1;
};
exports.RANK.EQ = function(number, range, order) {
number = utils.parseNumber(number);
range = utils.parseNumberArray(utils.flatten(range));
if (utils.anyIsError(number, range)) {
return error.value;
}
order = order || false;
var sort = (order) ? function(a, b) {
return a - b;
} : function(a, b) {
return b - a;
};
range = range.sort(sort);
return range.indexOf(number) + 1;
};
exports.ROW = function(matrix, index) {
if (arguments.length !== 2) {
return error.na;
}
if (index < 0) {
return error.num;
}
if (!(matrix instanceof Array) || (typeof index !== 'number')) {
return error.value;
}
if (matrix.length === 0) {
return undefined;
}
return jStat.row(matrix, index);
};
exports.ROWS = function(matrix) {
if (arguments.length !== 1) {
return error.na;
}
if (!(matrix instanceof Array)) {
return error.value;
}
if (matrix.length === 0) {
return 0;
}
return jStat.rows(matrix);
};
exports.RSQ = function(data_x, data_y) { // no need to flatten here, PEARSON will take care of that
data_x = utils.parseNumberArray(utils.flatten(data_x));
data_y = utils.parseNumberArray(utils.flatten(data_y));
if (utils.anyIsError(data_x, data_y)) {
return error.value;
}
return Math.pow(exports.PEARSON(data_x, data_y), 2);
};
exports.SKEW = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var mean = jStat.mean(range);
var n = range.length;
var sigma = 0;
for (var i = 0; i < n; i++) {
sigma += Math.pow(range[i] - mean, 3);
}
return n * sigma / ((n - 1) * (n - 2) * Math.pow(jStat.stdev(range, true), 3));
};
exports.SKEW.P = function() {
var range = utils.parseNumberArray(utils.flatten(arguments));
if (range instanceof Error) {
return range;
}
var mean = jStat.mean(range);
var n = range.length;
var m2 = 0;
var m3 = 0;
for (var i = 0; i < n; i++) {
m3 += Math.pow(range[i] - mean, 3);
m2 += Math.pow(range[i] - mean, 2);
}
m3 = m3 / n;
m2 = m2 / n;
return m3 / Math.pow(m2, 3 / 2);
};
exports.SLOPE = function(data_y, data_x) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(data_y, data_x)) {
return error.value;
}
var xmean = jStat.mean(data_x);
var ymean = jStat.mean(data_y);
var n = data_x.length;
var num = 0;
var den = 0;
for (var i = 0; i < n; i++) {
num += (data_x[i] - xmean) * (data_y[i] - ymean);
den += Math.pow(data_x[i] - xmean, 2);
}
return num / den;
};
exports.SMALL = function(range, k) {
range = utils.parseNumberArray(utils.flatten(range));
k = utils.parseNumber(k);
if (utils.anyIsError(range, k)) {
return range;
}
return range.sort(function(a, b) {
return a - b;
})[k - 1];
};
exports.STANDARDIZE = function(x, mean, sd) {
x = utils.parseNumber(x);
mean = utils.parseNumber(mean);
sd = utils.parseNumber(sd);
if (utils.anyIsError(x, mean, sd)) {
return error.value;
}
return (x - mean) / sd;
};
exports.STDEV = {};
exports.STDEV.P = function() {
var v = exports.VAR.P.apply(this, arguments);
var result = Math.sqrt(v);
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.STDEV.S = function() {
var v = exports.VAR.S.apply(this, arguments);
var result = Math.sqrt(v);
return result;
};
exports.STDEVA = function() {
var v = exports.VARA.apply(this, arguments);
var result = Math.sqrt(v);
return result;
};
exports.STDEVPA = function() {
var v = exports.VARPA.apply(this, arguments);
var result = Math.sqrt(v);
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.STEYX = function(data_y, data_x) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
if (utils.anyIsError(data_y, data_x)) {
return error.value;
}
var xmean = jStat.mean(data_x);
var ymean = jStat.mean(data_y);
var n = data_x.length;
var lft = 0;
var num = 0;
var den = 0;
for (var i = 0; i < n; i++) {
lft += Math.pow(data_y[i] - ymean, 2);
num += (data_x[i] - xmean) * (data_y[i] - ymean);
den += Math.pow(data_x[i] - xmean, 2);
}
return Math.sqrt((lft - num * num / den) / (n - 2));
};
exports.TRANSPOSE = function(matrix) {
if (!matrix) {
return error.na;
}
return jStat.transpose(matrix);
};
exports.T = text.T;
exports.T.DIST = function(x, df, cumulative) {
x = utils.parseNumber(x);
df = utils.parseNumber(df);
if (utils.anyIsError(x, df)) {
return error.value;
}
return (cumulative) ? jStat.studentt.cdf(x, df) : jStat.studentt.pdf(x, df);
};
exports.T.DIST['2T'] = function(x, df) {
if (arguments.length !== 2) {
return error.na;
}
if (x < 0 || df < 1) {
return error.num;
}
if ((typeof x !== 'number') || (typeof df !== 'number')) {
return error.value;
}
return (1 - jStat.studentt.cdf(x , df)) * 2;
};
exports.T.DIST.RT = function(x, df) {
if (arguments.length !== 2) {
return error.na;
}
if (x < 0 || df < 1) {
return error.num;
}
if ((typeof x !== 'number') || (typeof df !== 'number')) {
return error.value;
}
return 1 - jStat.studentt.cdf(x , df);
};
exports.T.INV = function(probability, df) {
probability = utils.parseNumber(probability);
df = utils.parseNumber(df);
if (utils.anyIsError(probability, df)) {
return error.value;
}
return jStat.studentt.inv(probability, df);
};
exports.T.INV['2T'] = function(probability, df) {
probability = utils.parseNumber(probability);
df = utils.parseNumber(df);
if (probability <= 0 || probability > 1 || df < 1) {
return error.num;
}
if (utils.anyIsError(probability, df)) {
return error.value;
}
return Math.abs(jStat.studentt.inv(probability/2, df));
};
// The algorithm can be found here:
// http://www.chem.uoa.gr/applets/AppletTtest/Appl_Ttest2.html
exports.T.TEST = function(data_x, data_y) {
data_x = utils.parseNumberArray(utils.flatten(data_x));
data_y = utils.parseNumberArray(utils.flatten(data_y));
if (utils.anyIsError(data_x, data_y)) {
return error.value;
}
var mean_x = jStat.mean(data_x);
var mean_y = jStat.mean(data_y);
var s_x = 0;
var s_y = 0;
var i;
for (i = 0; i < data_x.length; i++) {
s_x += Math.pow(data_x[i] - mean_x, 2);
}
for (i = 0; i < data_y.length; i++) {
s_y += Math.pow(data_y[i] - mean_y, 2);
}
s_x = s_x / (data_x.length-1);
s_y = s_y / (data_y.length-1);
var t = Math.abs(mean_x - mean_y) / Math.sqrt(s_x/data_x.length + s_y/data_y.length);
return exports.T.DIST['2T'](t, data_x.length+data_y.length-2);
};
exports.TREND = function(data_y, data_x, new_data_x) {
data_y = utils.parseNumberArray(utils.flatten(data_y));
data_x = utils.parseNumberArray(utils.flatten(data_x));
new_data_x = utils.parseNumberArray(utils.flatten(new_data_x));
if (utils.anyIsError(data_y, data_x, new_data_x)) {
return error.value;
}
var linest = exports.LINEST(data_y, data_x);
var m = linest[0];
var b = linest[1];
var result = [];
new_data_x.forEach(function(x) {
result.push(m * x + b);
});
return result;
};
exports.TRIMMEAN = function(range, percent) {
range = utils.parseNumberArray(utils.flatten(range));
percent = utils.parseNumber(percent);
if (utils.anyIsError(range, percent)) {
return error.value;
}
var trim = mathTrig.FLOOR(range.length * percent, 2) / 2;
return jStat.mean(utils.initial(utils.rest(range.sort(function(a, b) {
return a - b;
}), trim), trim));
};
exports.VAR = {};
exports.VAR.P = function() {
var range = utils.numbers(utils.flatten(arguments));
var n = range.length;
var sigma = 0;
var mean = exports.AVERAGE(range);
var result;
for (var i = 0; i < n; i++) {
sigma += Math.pow(range[i] - mean, 2);
}
result = sigma / n;
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.VAR.S = function() {
var range = utils.numbers(utils.flatten(arguments));
var n = range.length;
var sigma = 0;
var mean = exports.AVERAGE(range);
for (var i = 0; i < n; i++) {
sigma += Math.pow(range[i] - mean, 2);
}
return sigma / (n - 1);
};
exports.VARA = function() {
var range = utils.flatten(arguments);
var n = range.length;
var sigma = 0;
var count = 0;
var mean = exports.AVERAGEA(range);
for (var i = 0; i < n; i++) {
var el = range[i];
if (typeof el === 'number') {
sigma += Math.pow(el - mean, 2);
} else if (el === true) {
sigma += Math.pow(1 - mean, 2);
} else {
sigma += Math.pow(0 - mean, 2);
}
if (el !== null) {
count++;
}
}
return sigma / (count - 1);
};
exports.VARPA = function() {
var range = utils.flatten(arguments);
var n = range.length;
var sigma = 0;
var count = 0;
var mean = exports.AVERAGEA(range);
var result;
for (var i = 0; i < n; i++) {
var el = range[i];
if (typeof el === 'number') {
sigma += Math.pow(el - mean, 2);
} else if (el === true) {
sigma += Math.pow(1 - mean, 2);
} else {
sigma += Math.pow(0 - mean, 2);
}
if (el !== null) {
count++;
}
}
result = sigma / count;
if (isNaN(result)) {
result = error.num;
}
return result;
};
exports.WEIBULL = {};
exports.WEIBULL.DIST = function(x, alpha, beta, cumulative) {
x = utils.parseNumber(x);
alpha = utils.parseNumber(alpha);
beta = utils.parseNumber(beta);
if (utils.anyIsError(x, alpha, beta)) {
return error.value;
}
return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha);
};
exports.Z = {};
exports.Z.TEST = function(range, x, sd) {
range = utils.parseNumberArray(utils.flatten(range));
x = utils.parseNumber(x);
if (utils.anyIsError(range, x)) {
return error.value;
}
sd = sd || exports.STDEV.S(range);
var n = range.length;
return 1 - exports.NORM.S.DIST((exports.AVERAGE(range) - x) / (sd / Math.sqrt(n)), true);
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
var utils = __webpack_require__(1);
var error = __webpack_require__(0);
var numbro = __webpack_require__(9);
//TODO
exports.ASC = function() {
throw new Error('ASC is not implemented');
};
//TODO
exports.BAHTTEXT = function() {
throw new Error('BAHTTEXT is not implemented');
};
exports.CHAR = function(number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return String.fromCharCode(number);
};
exports.CLEAN = function(text) {
text = text || '';
var re = /[\0-\x1F]/g;
return text.replace(re, "");
};
exports.CODE = function(text) {
text = text || '';
var result = text.charCodeAt(0);
if (isNaN(result)) {
result = error.na;
}
return result;
};
exports.CONCATENATE = function() {
var args = utils.flatten(arguments);
var trueFound = 0;
while ((trueFound = args.indexOf(true)) > -1) {
args[trueFound] = 'TRUE';
}
var falseFound = 0;
while ((falseFound = args.indexOf(false)) > -1) {
args[falseFound] = 'FALSE';
}
return args.join('');
};
//TODO
exports.DBCS = function() {
throw new Error('DBCS is not implemented');
};
exports.DOLLAR = function(number, decimals) {
decimals = (decimals === undefined) ? 2 : decimals;
number = utils.parseNumber(number);
decimals = utils.parseNumber(decimals);
if (utils.anyIsError(number, decimals)) {
return error.value;
}
var format = '';
if (decimals <= 0) {
number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
format = '($0,0)';
} else if (decimals > 0) {
format = '($0,0.' + new Array(decimals + 1).join('0') + ')';
}
return numbro(number).format(format);
};
exports.EXACT = function(text1, text2) {
if (arguments.length !== 2) {
return error.na;
}
return text1 === text2;
};
exports.FIND = function(find_text, within_text, position) {
if (arguments.length < 2) {
return error.na;
}
position = (position === undefined) ? 0 : position;
return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null;
};
exports.FIXED = function(number, decimals, no_commas) {
decimals = (decimals === undefined) ? 2 : decimals;
no_commas = (no_commas === undefined) ? false : no_commas;
number = utils.parseNumber(number);
decimals = utils.parseNumber(decimals);
if (utils.anyIsError(number, decimals)) {
return error.value;
}
var format = no_commas ? '0' : '0,0';
if (decimals <= 0) {
number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
} else if (decimals > 0) {
format += '.' + new Array(decimals + 1).join('0');
}
return numbro(number).format(format);
};
exports.HTML2TEXT = function (value) {
var result = '';
if (value) {
if (value instanceof Array) {
value.forEach(function (line) {
if (result !== '') {
result += '\n';
}
result += (line.replace(/<(?:.|\n)*?>/gm, ''));
});
} else {
result = value.replace(/<(?:.|\n)*?>/gm, '');
}
}
return result;
};
exports.LEFT = function(text, number) {
number = (number === undefined) ? 1 : number;
number = utils.parseNumber(number);
if (number instanceof Error || typeof text !== 'string') {
return error.value;
}
return text ? text.substring(0, number) : null;
};
exports.LEN = function(text) {
if (arguments.length === 0) {
return error.error;
}
if (typeof text === 'string') {
return text ? text.length : 0;
}
if (text.length) {
return text.length;
}
return error.value;
};
exports.LOWER = function(text) {
if (typeof text !== 'string') {
return error.value;
}
return text ? text.toLowerCase() : text;
};
exports.MID = function(text, start, number) {
start = utils.parseNumber(start);
number = utils.parseNumber(number);
if (utils.anyIsError(start, number) || typeof text !== 'string') {
return number;
}
var begin = start - 1;
var end = begin + number;
return text.substring(begin, end);
};
// TODO
exports.NUMBERVALUE = function (text, decimal_separator, group_separator) {
decimal_separator = (typeof decimal_separator === 'undefined') ? '.' : decimal_separator;
group_separator = (typeof group_separator === 'undefined') ? ',' : group_separator;
return Number(text.replace(decimal_separator, '.').replace(group_separator, ''));
};
// TODO
exports.PRONETIC = function() {
throw new Error('PRONETIC is not implemented');
};
exports.PROPER = function(text) {
if (text === undefined || text.length === 0) {
return error.value;
}
if (text === true) {
text = 'TRUE';
}
if (text === false) {
text = 'FALSE';
}
if (isNaN(text) && typeof text === 'number') {
return error.value;
}
if (typeof text === 'number') {
text = '' + text;
}
return text.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
exports.REGEXEXTRACT = function (text, regular_expression) {
if (arguments.length < 2) {
return error.na;
}
var match = text.match(new RegExp(regular_expression));
return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null;
};
exports.REGEXMATCH = function (text, regular_expression, full) {
if (arguments.length < 2) {
return error.na;
}
var match = text.match(new RegExp(regular_expression));
return full ? match : !!match;
};
exports.REGEXREPLACE = function (text, regular_expression, replacement) {
if (arguments.length < 3) {
return error.na;
}
return text.replace(new RegExp(regular_expression), replacement);
};
exports.REPLACE = function(text, position, length, new_text) {
position = utils.parseNumber(position);
length = utils.parseNumber(length);
if (utils.anyIsError(position, length) ||
typeof text !== 'string' ||
typeof new_text !== 'string') {
return error.value;
}
return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length);
};
exports.REPT = function(text, number) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return new Array(number + 1).join(text);
};
exports.RIGHT = function(text, number) {
number = (number === undefined) ? 1 : number;
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
return text ? text.substring(text.length - number) : error.na;
};
exports.SEARCH = function(find_text, within_text, position) {
var foundAt;
if (typeof find_text !== 'string' || typeof within_text !== 'string') {
return error.value;
}
position = (position === undefined) ? 0 : position;
foundAt = within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1)+1;
return (foundAt === 0)?error.value:foundAt;
};
exports.SPLIT = function (text, separator) {
return text.split(separator);
};
exports.SUBSTITUTE = function(text, old_text, new_text, occurrence) {
if (arguments.length < 2) {
return error.na;
}
if (!text || !old_text || !new_text) {
return text;
} else if (occurrence === undefined) {
return text.replace(new RegExp(old_text, 'g'), new_text);
} else {
var index = 0;
var i = 0;
while (text.indexOf(old_text, index) > 0) {
index = text.indexOf(old_text, index + 1);
i++;
if (i === occurrence) {
return text.substring(0, index) + new_text + text.substring(index + old_text.length);
}
}
}
};
exports.T = function(value) {
return (typeof value === "string") ? value : '';
};
// TODO incomplete implementation
exports.TEXT = function(value, format) {
value = utils.parseNumber(value);
if (utils.anyIsError(value)) {
return error.na;
}
return numbro(value).format(format);
};
exports.TRIM = function(text) {
if (typeof text !== 'string') {
return error.value;
}
return text.replace(/ +/g, ' ').trim();
};
exports.UNICHAR = exports.CHAR;
exports.UNICODE = exports.CODE;
exports.UPPER = function(text) {
if (typeof text !== 'string') {
return error.value;
}
return text.toUpperCase();
};
exports.VALUE = function(text) {
if (typeof text !== 'string') {
return error.value;
}
var result = numbro().unformat(text);
return result === void 0 ? 0 : result;
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
// TODO
exports.CELL = function() {
throw new Error('CELL is not implemented');
};
exports.ERROR = {};
exports.ERROR.TYPE = function(error_val) {
switch (error_val) {
case error.nil: return 1;
case error.div0: return 2;
case error.value: return 3;
case error.ref: return 4;
case error.name: return 5;
case error.num: return 6;
case error.na: return 7;
case error.data: return 8;
}
return error.na;
};
// TODO
exports.INFO = function() {
throw new Error('INFO is not implemented');
};
exports.ISBLANK = function(value) {
return value === null;
};
exports.ISBINARY = function (number) {
return (/^[01]{1,10}$/).test(number);
};
exports.ISERR = function(value) {
return ([error.value, error.ref, error.div0, error.num, error.name, error.nil]).indexOf(value) >= 0 ||
(typeof value === 'number' && (isNaN(value) || !isFinite(value)));
};
exports.ISERROR = function(value) {
return exports.ISERR(value) || value === error.na;
};
exports.ISEVEN = function(number) {
return (Math.floor(Math.abs(number)) & 1) ? false : true;
};
// TODO
exports.ISFORMULA = function() {
throw new Error('ISFORMULA is not implemented');
};
exports.ISLOGICAL = function(value) {
return value === true || value === false;
};
exports.ISNA = function(value) {
return value === error.na;
};
exports.ISNONTEXT = function(value) {
return typeof(value) !== 'string';
};
exports.ISNUMBER = function(value) {
return typeof(value) === 'number' && !isNaN(value) && isFinite(value);
};
exports.ISODD = function(number) {
return (Math.floor(Math.abs(number)) & 1) ? true : false;
};
// TODO
exports.ISREF = function() {
throw new Error('ISREF is not implemented');
};
exports.ISTEXT = function(value) {
return typeof(value) === 'string';
};
exports.N = function(value) {
if (this.ISNUMBER(value)) {
return value;
}
if (value instanceof Date) {
return value.getTime();
}
if (value === true) {
return 1;
}
if (value === false) {
return 0;
}
if (this.ISERROR(value)) {
return value;
}
return 0;
};
exports.NA = function() {
return error.na;
};
// TODO
exports.SHEET = function() {
throw new Error('SHEET is not implemented');
};
// TODO
exports.SHEETS = function() {
throw new Error('SHEETS is not implemented');
};
exports.TYPE = function(value) {
if (this.ISNUMBER(value)) {
return 1;
}
if (this.ISTEXT(value)) {
return 2;
}
if (this.ISLOGICAL(value)) {
return 4;
}
if (this.ISERROR(value)) {
return 16;
}
if (Array.isArray(value)) {
return 64;
}
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var utils = __webpack_require__(1);
var d1900 = new Date(1900, 0, 1);
var WEEK_STARTS = [
undefined,
0,
1,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
1,
2,
3,
4,
5,
6,
0
];
var WEEK_TYPES = [
[],
[1, 2, 3, 4, 5, 6, 7],
[7, 1, 2, 3, 4, 5, 6],
[6, 0, 1, 2, 3, 4, 5],
[],
[],
[],
[],
[],
[],
[],
[7, 1, 2, 3, 4, 5, 6],
[6, 7, 1, 2, 3, 4, 5],
[5, 6, 7, 1, 2, 3, 4],
[4, 5, 6, 7, 1, 2, 3],
[3, 4, 5, 6, 7, 1, 2],
[2, 3, 4, 5, 6, 7, 1],
[1, 2, 3, 4, 5, 6, 7]
];
var WEEKEND_TYPES = [
[],
[6, 0],
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6],
undefined,
undefined,
undefined, [0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6]
];
exports.DATE = function(year, month, day) {
var result;
year = utils.parseNumber(year);
month = utils.parseNumber(month);
day = utils.parseNumber(day);
if (utils.anyIsError(year, month, day)) {
result = error.value;
} else if (year < 0 || month < 0 || day < 0) {
result = error.num;
} else {
result = new Date(year, month - 1, day);
}
return result;
};
exports.DATEVALUE = function(date_text) {
if (typeof date_text !== 'string') {
return error.value;
}
var date = Date.parse(date_text);
if (isNaN(date)) {
return error.value;
}
if (date <= -2203891200000) {
return (date - d1900) / 86400000 + 1;
}
return (date - d1900) / 86400000 + 2;
};
exports.DAY = function(serial_number) {
var date = utils.parseDate(serial_number);
if (date instanceof Error) {
return date;
}
return date.getDate();
};
exports.DAYS = function(end_date, start_date) {
end_date = utils.parseDate(end_date);
start_date = utils.parseDate(start_date);
if (end_date instanceof Error) {
return end_date;
}
if (start_date instanceof Error) {
return start_date;
}
return serial(end_date) - serial(start_date);
};
exports.DAYS360 = function(start_date, end_date, method) {
method = utils.parseBool(method);
start_date = utils.parseDate(start_date);
end_date = utils.parseDate(end_date);
if (start_date instanceof Error) {
return start_date;
}
if (end_date instanceof Error) {
return end_date;
}
if (method instanceof Error) {
return method;
}
var sm = start_date.getMonth();
var em = end_date.getMonth();
var sd, ed;
if (method) {
sd = start_date.getDate() === 31 ? 30 : start_date.getDate();
ed = end_date.getDate() === 31 ? 30 : end_date.getDate();
} else {
var smd = new Date(start_date.getFullYear(), sm + 1, 0).getDate();
var emd = new Date(end_date.getFullYear(), em + 1, 0).getDate();
sd = start_date.getDate() === smd ? 30 : start_date.getDate();
if (end_date.getDate() === emd) {
if (sd < 30) {
em++;
ed = 1;
} else {
ed = 30;
}
} else {
ed = end_date.getDate();
}
}
return 360 * (end_date.getFullYear() - start_date.getFullYear()) +
30 * (em - sm) + (ed - sd);
};
exports.EDATE = function(start_date, months) {
start_date = utils.parseDate(start_date);
if (start_date instanceof Error) {
return start_date;
}
if (isNaN(months)) {
return error.value;
}
months = parseInt(months, 10);
start_date.setMonth(start_date.getMonth() + months);
return serial(start_date);
};
exports.EOMONTH = function(start_date, months) {
start_date = utils.parseDate(start_date);
if (start_date instanceof Error) {
return start_date;
}
if (isNaN(months)) {
return error.value;
}
months = parseInt(months, 10);
return serial(new Date(start_date.getFullYear(), start_date.getMonth() + months + 1, 0));
};
exports.HOUR = function(serial_number) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
return serial_number.getHours();
};
exports.INTERVAL = function (second) {
if (typeof second !== 'number' && typeof second !== 'string') {
return error.value;
} else {
second = parseInt(second, 10);
}
var year = Math.floor(second/946080000);
second = second%946080000;
var month = Math.floor(second/2592000);
second = second%2592000;
var day = Math.floor(second/86400);
second = second%86400;
var hour = Math.floor(second/3600);
second = second%3600;
var min = Math.floor(second/60);
second = second%60;
var sec = second;
year = (year > 0) ? year + 'Y' : '';
month = (month > 0) ? month + 'M' : '';
day = (day > 0) ? day + 'D' : '';
hour = (hour > 0) ? hour + 'H' : '';
min = (min > 0) ? min + 'M' : '';
sec = (sec > 0) ? sec + 'S' : '';
return 'P' + year + month + day + 'T' + hour + min + sec;
};
exports.ISOWEEKNUM = function(date) {
date = utils.parseDate(date);
if (date instanceof Error) {
return date;
}
date.setHours(0, 0, 0);
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
var yearStart = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - yearStart) / 86400000) + 1) / 7);
};
exports.MINUTE = function(serial_number) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
return serial_number.getMinutes();
};
exports.MONTH = function(serial_number) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
return serial_number.getMonth() + 1;
};
exports.NETWORKDAYS = function(start_date, end_date, holidays) {
return this.NETWORKDAYS.INTL(start_date, end_date, 1, holidays);
};
exports.NETWORKDAYS.INTL = function(start_date, end_date, weekend, holidays) {
start_date = utils.parseDate(start_date);
if (start_date instanceof Error) {
return start_date;
}
end_date = utils.parseDate(end_date);
if (end_date instanceof Error) {
return end_date;
}
if (weekend === undefined) {
weekend = WEEKEND_TYPES[1];
} else {
weekend = WEEKEND_TYPES[weekend];
}
if (!(weekend instanceof Array)) {
return error.value;
}
if (holidays === undefined) {
holidays = [];
} else if (!(holidays instanceof Array)) {
holidays = [holidays];
}
for (var i = 0; i < holidays.length; i++) {
var h = utils.parseDate(holidays[i]);
if (h instanceof Error) {
return h;
}
holidays[i] = h;
}
var days = (end_date - start_date) / (1000 * 60 * 60 * 24) + 1;
var total = days;
var day = start_date;
for (i = 0; i < days; i++) {
var d = (new Date().getTimezoneOffset() > 0) ? day.getUTCDay() : day.getDay();
var dec = false;
if (d === weekend[0] || d === weekend[1]) {
dec = true;
}
for (var j = 0; j < holidays.length; j++) {
var holiday = holidays[j];
if (holiday.getDate() === day.getDate() &&
holiday.getMonth() === day.getMonth() &&
holiday.getFullYear() === day.getFullYear()) {
dec = true;
break;
}
}
if (dec) {
total--;
}
day.setDate(day.getDate() + 1);
}
return total;
};
exports.NOW = function() {
return new Date();
};
exports.SECOND = function(serial_number) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
return serial_number.getSeconds();
};
exports.TIME = function(hour, minute, second) {
hour = utils.parseNumber(hour);
minute = utils.parseNumber(minute);
second = utils.parseNumber(second);
if (utils.anyIsError(hour, minute, second)) {
return error.value;
}
if (hour < 0 || minute < 0 || second < 0) {
return error.num;
}
return (3600 * hour + 60 * minute + second) / 86400;
};
exports.TIMEVALUE = function(time_text) {
time_text = utils.parseDate(time_text);
if (time_text instanceof Error) {
return time_text;
}
return (3600 * time_text.getHours() + 60 * time_text.getMinutes() + time_text.getSeconds()) / 86400;
};
exports.TODAY = function() {
return new Date();
};
exports.WEEKDAY = function(serial_number, return_type) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
if (return_type === undefined) {
return_type = 1;
}
var day = serial_number.getDay();
return WEEK_TYPES[return_type][day];
};
exports.WEEKNUM = function(serial_number, return_type) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
if (return_type === undefined) {
return_type = 1;
}
if (return_type === 21) {
return this.ISOWEEKNUM(serial_number);
}
var week_start = WEEK_STARTS[return_type];
var jan = new Date(serial_number.getFullYear(), 0, 1);
var inc = jan.getDay() < week_start ? 1 : 0;
jan -= Math.abs(jan.getDay() - week_start) * 24 * 60 * 60 * 1000;
return Math.floor(((serial_number - jan) / (1000 * 60 * 60 * 24)) / 7 + 1) + inc;
};
exports.WORKDAY = function(start_date, days, holidays) {
return this.WORKDAY.INTL(start_date, days, 1, holidays);
};
exports.WORKDAY.INTL = function(start_date, days, weekend, holidays) {
start_date = utils.parseDate(start_date);
if (start_date instanceof Error) {
return start_date;
}
days = utils.parseNumber(days);
if (days instanceof Error) {
return days;
}
if (days < 0) {
return error.num;
}
if (weekend === undefined) {
weekend = WEEKEND_TYPES[1];
} else {
weekend = WEEKEND_TYPES[weekend];
}
if (!(weekend instanceof Array)) {
return error.value;
}
if (holidays === undefined) {
holidays = [];
} else if (!(holidays instanceof Array)) {
holidays = [holidays];
}
for (var i = 0; i < holidays.length; i++) {
var h = utils.parseDate(holidays[i]);
if (h instanceof Error) {
return h;
}
holidays[i] = h;
}
var d = 0;
while (d < days) {
start_date.setDate(start_date.getDate() + 1);
var day = start_date.getDay();
if (day === weekend[0] || day === weekend[1]) {
continue;
}
for (var j = 0; j < holidays.length; j++) {
var holiday = holidays[j];
if (holiday.getDate() === start_date.getDate() &&
holiday.getMonth() === start_date.getMonth() &&
holiday.getFullYear() === start_date.getFullYear()) {
d--;
break;
}
}
d++;
}
return start_date;
};
exports.YEAR = function(serial_number) {
serial_number = utils.parseDate(serial_number);
if (serial_number instanceof Error) {
return serial_number;
}
return serial_number.getFullYear();
};
function isLeapYear(year) {
return new Date(year, 1, 29).getMonth() === 1;
}
// TODO : Use DAYS ?
function daysBetween(start_date, end_date) {
return Math.ceil((end_date - start_date) / 1000 / 60 / 60 / 24);
}
exports.YEARFRAC = function(start_date, end_date, basis) {
start_date = utils.parseDate(start_date);
if (start_date instanceof Error) {
return start_date;
}
end_date = utils.parseDate(end_date);
if (end_date instanceof Error) {
return end_date;
}
basis = basis || 0;
var sd = start_date.getDate();
var sm = start_date.getMonth() + 1;
var sy = start_date.getFullYear();
var ed = end_date.getDate();
var em = end_date.getMonth() + 1;
var ey = end_date.getFullYear();
switch (basis) {
case 0:
// US (NASD) 30/360
if (sd === 31 && ed === 31) {
sd = 30;
ed = 30;
} else if (sd === 31) {
sd = 30;
} else if (sd === 30 && ed === 31) {
ed = 30;
}
return ((ed + em * 30 + ey * 360) - (sd + sm * 30 + sy * 360)) / 360;
case 1:
// Actual/actual
var feb29Between = function(date1, date2) {
var year1 = date1.getFullYear();
var mar1year1 = new Date(year1, 2, 1);
if (isLeapYear(year1) && date1 < mar1year1 && date2 >= mar1year1) {
return true;
}
var year2 = date2.getFullYear();
var mar1year2 = new Date(year2, 2, 1);
return (isLeapYear(year2) && date2 >= mar1year2 && date1 < mar1year2);
};
var ylength = 365;
if (sy === ey || ((sy + 1) === ey) && ((sm > em) || ((sm === em) && (sd >= ed)))) {
if ((sy === ey && isLeapYear(sy)) ||
feb29Between(start_date, end_date) ||
(em === 1 && ed === 29)) {
ylength = 366;
}
return daysBetween(start_date, end_date) / ylength;
}
var years = (ey - sy) + 1;
var days = (new Date(ey + 1, 0, 1) - new Date(sy, 0, 1)) / 1000 / 60 / 60 / 24;
var average = days / years;
return daysBetween(start_date, end_date) / average;
case 2:
// Actual/360
return daysBetween(start_date, end_date) / 360;
case 3:
// Actual/365
return daysBetween(start_date, end_date) / 365;
case 4:
// European 30/360
return ((ed + em * 30 + ey * 360) - (sd + sm * 30 + sy * 360)) / 360;
}
};
function serial(date) {
var addOn = (date > -2203891200000) ? 2 : 1;
return (date - d1900) / 86400000 + addOn;
}
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* numbro.js
* version : 1.11.1
* author : Företagsplatsen AB
* license : MIT
* http://www.foretagsplatsen.se
*/
(function () {
'use strict';
/************************************
Constants
************************************/
var numbro,
VERSION = '1.11.1',
binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytes = {
general: { scale: 1024, suffixes: decimalSuffixes, marker: 'bd' },
binary: { scale: 1024, suffixes: binarySuffixes, marker: 'b' },
decimal: { scale: 1000, suffixes: decimalSuffixes, marker: 'd' }
},
// general must be before the others because it reuses their characters!
byteFormatOrder = [ bytes.general, bytes.binary, bytes.decimal ],
// internal storage for culture config files
cultures = {},
// Todo: Remove in 2.0.0
languages = cultures,
currentCulture = 'en-US',
zeroFormat = null,
defaultFormat = '0,0',
defaultCurrencyFormat = '0$',
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module.exports),
// default culture
enUS = {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function(number) {
var b = number % 10;
return (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$',
position: 'prefix'
},
defaults: {
currencyFormat: ',0000 a'
},
formats: {
fourDigits: '0000 a',
fullWithTwoDecimals: '$ ,0.00',
fullWithTwoDecimalsNoCurrency: ',0.00'
}
};
/************************************
Constructors
************************************/
// Numbro prototype object
function Numbro(number) {
this._value = number;
}
function numberLength(number) {
if (number === 0) { return 1; }
return Math.floor(Math.log(Math.abs(number)) / Math.LN10) + 1;
}
function zeroes(count) {
var i, ret = '';
for (i = 0; i < count; i++) {
ret += '0';
}
return ret;
}
/**
* Implementation of toFixed() for numbers with exponents
* This function may return negative representations for zero values e.g. "-0.0"
*/
function toFixedLargeSmall(value, precision) {
var mantissa,
beforeDec,
afterDec,
exponent,
prefix,
endStr,
zerosStr,
str;
str = value.toString();
mantissa = str.split('e')[0];
exponent = str.split('e')[1];
beforeDec = mantissa.split('.')[0];
afterDec = mantissa.split('.')[1] || '';
if (+exponent > 0) {
// exponent is positive - add zeros after the numbers
str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
} else {
// exponent is negative
if (+beforeDec < 0) {
prefix = '-0';
} else {
prefix = '0';
}
// tack on the decimal point if needed
if (precision > 0) {
prefix += '.';
}
zerosStr = zeroes((-1 * exponent) - 1);
// substring off the end to satisfy the precision
endStr = (zerosStr + Math.abs(beforeDec) + afterDec).substr(0, precision);
str = prefix + endStr;
}
// only add percision 0's if the exponent is positive
if (+exponent > 0 && precision > 0) {
str += '.' + zeroes(precision);
}
return str;
}
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*
* Also removes negative signs for zero-formatted numbers. e.g. -0.01 w/ precision 1 -> 0.0
*/
function toFixed(value, precision, roundingFunction, optionals) {
var power = Math.pow(10, precision),
optionalsRegExp,
output;
if (value.toString().indexOf('e') > -1) {
// toFixed returns scientific notation for numbers above 1e21 and below 1e-7
output = toFixedLargeSmall(value, precision);
// remove the leading negative sign if it exists and should not be present (e.g. -0.00)
if (output.charAt(0) === '-' && +output >= 0) {
output = output.substr(1); // chop off the '-'
}
}
else {
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value + 'e+' + precision) / power).toFixed(precision);
}
if (optionals) {
optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
/************************************
Formatting
************************************/
// determine what type of formatting we need to do
function formatNumbro(n, format, roundingFunction) {
var output,
escapedFormat = format.replace(/\{[^\{\}]*\}/g, '');
// figure out what kind of format we are dealing with
if (escapedFormat.indexOf('$') > -1) { // currency!!!!!
output = formatCurrency(n, cultures[currentCulture].currency.symbol, format, roundingFunction);
} else if (escapedFormat.indexOf('%') > -1) { // percentage
output = formatPercentage(n, format, roundingFunction);
} else if (escapedFormat.indexOf(':') > -1) { // time
output = formatTime(n, format);
} else { // plain ol' numbers or bytes
output = formatNumber(n._value, format, roundingFunction);
}
// return string
return output;
}
// revert to number
function unformatNumbro(n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (cultures[currentCulture].delimiters.decimal !== '.') {
string = string.replace(/\./g, '').replace(cultures[currentCulture].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.thousand +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.million +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.billion +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.trillion +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 1; power < binarySuffixes.length && !bytesMultiplier; ++power) {
if (string.indexOf(binarySuffixes[power]) > -1) {
bytesMultiplier = Math.pow(1024, power);
} else if (string.indexOf(decimalSuffixes[power]) > -1) {
bytesMultiplier = Math.pow(1000, power);
}
}
var str = string.replace(/[^0-9\.]+/g, '');
if (str === '') {
// An empty string is not a number.
n._value = NaN;
} else {
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) *
((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) *
((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) *
((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) *
((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) *
((string.indexOf('%') > -1) ? 0.01 : 1) *
(((string.split('-').length +
Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2) ? 1 : -1) *
Number(str);
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
}
return n._value;
}
function formatCurrency(n, currencySymbol, originalFormat, roundingFunction) {
var format = originalFormat,
symbolIndex = format.indexOf('$'),
openParenIndex = format.indexOf('('),
plusSignIndex = format.indexOf('+'),
minusSignIndex = format.indexOf('-'),
space = '',
decimalSeparator = '',
spliceIndex,
output;
if(format.indexOf('$') === -1){
// Use defaults instead of the format provided
if (cultures[currentCulture].currency.position === 'infix') {
decimalSeparator = currencySymbol;
if (cultures[currentCulture].currency.spaceSeparated) {
decimalSeparator = ' ' + decimalSeparator + ' ';
}
} else if (cultures[currentCulture].currency.spaceSeparated) {
space = ' ';
}
} else {
// check for space before or after currency
if (format.indexOf(' $') > -1) {
space = ' ';
format = format.replace(' $', '');
} else if (format.indexOf('$ ') > -1) {
space = ' ';
format = format.replace('$ ', '');
} else {
format = format.replace('$', '');
}
}
// Format The Number
output = formatNumber(n._value, format, roundingFunction, decimalSeparator);
if (originalFormat.indexOf('$') === -1) {
// Use defaults instead of the format provided
switch (cultures[currentCulture].currency.position) {
case 'postfix':
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + currencySymbol);
output = output.join('');
} else {
output = output + space + currencySymbol;
}
break;
case 'infix':
break;
case 'prefix':
if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
output.splice(spliceIndex, 0, currencySymbol + space);
output = output.join('');
} else {
output = currencySymbol + space + output;
}
break;
default:
throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
}
} else {
// position the symbol
if (symbolIndex <= 1) {
if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = 1;
if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
// the symbol appears before the "(", "+" or "-"
spliceIndex = 0;
}
output.splice(spliceIndex, 0, currencySymbol + space);
output = output.join('');
} else {
output = currencySymbol + space + output;
}
} else {
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + currencySymbol);
output = output.join('');
} else {
output = output + space + currencySymbol;
}
}
}
return output;
}
function formatForeignCurrency(n, foreignCurrencySymbol, originalFormat, roundingFunction) {
return formatCurrency(n, foreignCurrencySymbol, originalFormat, roundingFunction);
}
function formatPercentage(n, format, roundingFunction) {
var space = '',
output,
value = n._value * 100;
// check for space before %
if (format.indexOf(' %') > -1) {
space = ' ';
format = format.replace(' %', '');
} else {
format = format.replace('%', '');
}
output = formatNumber(value, format, roundingFunction);
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
}
function formatTime(n) {
var hours = Math.floor(n._value / 60 / 60),
minutes = Math.floor((n._value - (hours * 60 * 60)) / 60),
seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60));
return hours + ':' +
((minutes < 10) ? '0' + minutes : minutes) + ':' +
((seconds < 10) ? '0' + seconds : seconds);
}
function unformatTime(string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
function formatByteUnits (value, suffixes, scale) {
var suffix = suffixes[0],
power,
min,
max,
abs = Math.abs(value);
if (abs >= scale) {
for (power = 1; power < suffixes.length; ++power) {
min = Math.pow(scale, power);
max = Math.pow(scale, power + 1);
if (abs >= min && abs < max) {
suffix = suffixes[power];
value = value / min;
break;
}
}
// values greater than or equal to [scale] YB never set the suffix
if (suffix === suffixes[0]) {
value = value / Math.pow(scale, suffixes.length - 1);
suffix = suffixes[suffixes.length - 1];
}
}
return { value: value, suffix: suffix };
}
function formatNumber (value, format, roundingFunction, sep) {
var negP = false,
signed = false,
optDec = false,
abbr = '',
abbrK = false, // force abbreviation to thousands
abbrM = false, // force abbreviation to millions
abbrB = false, // force abbreviation to billions
abbrT = false, // force abbreviation to trillions
abbrForce = false, // force abbreviation
bytes = '',
byteFormat,
units,
ord = '',
abs = Math.abs(value),
totalLength,
length,
minimumPrecision,
pow,
w,
intPrecision,
precision,
prefix,
postfix,
thousands,
d = '',
forcedNeg = false,
neg = false,
indexOpenP,
indexMinus,
paren = '',
minlen,
i;
// check if number is zero and a custom zero format has been set
if (value === 0 && zeroFormat !== null) {
return zeroFormat;
}
if (!isFinite(value)) {
return '' + value;
}
if (format.indexOf('{') === 0) {
var end = format.indexOf('}');
if (end === -1) {
throw Error('Format should also contain a "}"');
}
prefix = format.slice(1, end);
format = format.slice(end + 1);
} else {
prefix = '';
}
if (format.indexOf('}') === format.length - 1 && format.length) {
var start = format.indexOf('{');
if (start === -1) {
throw Error('Format should also contain a "{"');
}
postfix = format.slice(start + 1, -1);
format = format.slice(0, start + 1);
} else {
postfix = '';
}
// check for min length
var info;
if (format.indexOf('.') === -1) {
info = format.match(/([0-9]+).*/);
} else {
info = format.match(/([0-9]+)\..*/);
}
minlen = info === null ? -1 : info[1].length;
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (format.indexOf('-') !== -1) {
forcedNeg = true;
}
if (format.indexOf('(') > -1) {
negP = true;
format = format.slice(1, -1);
} else if (format.indexOf('+') > -1) {
signed = true;
format = format.replace(/\+/g, '');
}
// see if abbreviation is wanted
if (format.indexOf('a') > -1) {
intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
intPrecision = parseInt(intPrecision[0], 10);
// check if abbreviation is specified
abbrK = format.indexOf('aK') >= 0;
abbrM = format.indexOf('aM') >= 0;
abbrB = format.indexOf('aB') >= 0;
abbrT = format.indexOf('aT') >= 0;
abbrForce = abbrK || abbrM || abbrB || abbrT;
// check for space before abbreviation
if (format.indexOf(' a') > -1) {
abbr = ' ';
format = format.replace(' a', '');
} else {
format = format.replace('a', '');
}
totalLength = numberLength(value);
minimumPrecision = totalLength % 3;
minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
if (intPrecision && abs !== 0) {
pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
abs = abs / Math.pow(10, pow);
}
if (totalLength !== intPrecision) {
if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
// trillion
abbr = abbr + cultures[currentCulture].abbreviations.trillion;
value = value / Math.pow(10, 12);
} else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
// billion
abbr = abbr + cultures[currentCulture].abbreviations.billion;
value = value / Math.pow(10, 9);
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
// million
abbr = abbr + cultures[currentCulture].abbreviations.million;
value = value / Math.pow(10, 6);
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
// thousand
abbr = abbr + cultures[currentCulture].abbreviations.thousand;
value = value / Math.pow(10, 3);
}
}
length = numberLength(value);
if (intPrecision && length < intPrecision && format.indexOf('.') === -1) {
format += '[.]';
format += zeroes(intPrecision - length);
}
}
// see if we are formatting
// binary-decimal bytes (1024 MB), binary bytes (1024 MiB), or decimal bytes (1000 MB)
for (i = 0; i < byteFormatOrder.length; ++i) {
byteFormat = byteFormatOrder[i];
if (format.indexOf(byteFormat.marker) > -1) {
// check for space before
if (format.indexOf(' ' + byteFormat.marker) >-1) {
bytes = ' ';
}
// remove the marker (with the space if it had one)
format = format.replace(bytes + byteFormat.marker, '');
units = formatByteUnits(value, byteFormat.suffixes, byteFormat.scale);
value = units.value;
bytes = bytes + units.suffix;
break;
}
}
// see if ordinal is wanted
if (format.indexOf('o') > -1) {
// check for space before
if (format.indexOf(' o') > -1) {
ord = ' ';
format = format.replace(' o', '');
} else {
format = format.replace('o', '');
}
if (cultures[currentCulture].ordinal) {
ord = ord + cultures[currentCulture].ordinal(value);
}
}
if (format.indexOf('[.]') > -1) {
optDec = true;
format = format.replace('[.]', '.');
}
precision = format.split('.')[1];
thousands = format.indexOf(',');
if (precision) {
var dSplit = [];
if (precision.indexOf('*') !== -1) {
d = value.toString();
dSplit = d.split('.');
if (dSplit.length > 1) {
d = toFixed(value, dSplit[1].length, roundingFunction);
}
} else {
if (precision.indexOf('[') > -1) {
precision = precision.replace(']', '');
precision = precision.split('[');
d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction,
precision[1].length);
} else {
d = toFixed(value, precision.length, roundingFunction);
}
}
dSplit = d.split('.');
w = dSplit[0];
if (dSplit.length > 1 && dSplit[1].length) {
var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
d = p + dSplit[1];
} else {
d = '';
}
if (optDec && Number(d.slice(1)) === 0) {
d = '';
}
} else {
w = toFixed(value, 0, roundingFunction);
}
// format number
if (w.indexOf('-') > -1) {
w = w.slice(1);
neg = true;
}
if (w.length < minlen) {
w = zeroes(minlen - w.length) + w;
}
if (thousands > -1) {
w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
cultures[currentCulture].delimiters.thousands);
}
if (format.indexOf('.') === 0) {
w = '';
}
indexOpenP = format.indexOf('(');
indexMinus = format.indexOf('-');
if (indexOpenP < indexMinus) {
paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
} else {
paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
}
return prefix +
paren + ((!neg && signed && value !== 0) ? '+' : '') +
w + d +
((ord) ? ord : '') +
((abbr && !sep) ? abbr : '') +
((bytes) ? bytes : '') +
((negP && neg) ? ')' : '') +
postfix;
}
/************************************
Top Level Functions
************************************/
numbro = function(input) {
if (numbro.isNumbro(input)) {
input = input.value();
} else if (typeof input === 'string' || typeof input === 'number') {
input = numbro.fn.unformat(input);
} else {
input = NaN;
}
return new Numbro(Number(input));
};
// version number
numbro.version = VERSION;
// compare numbro object
numbro.isNumbro = function(obj) {
return obj instanceof Numbro;
};
/**
* This function allow the user to set a new language with a fallback if
* the language does not exist. If no fallback language is provided,
* it fallbacks to english.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `setCulture` should be used instead.
*/
numbro.setLanguage = function(newLanguage, fallbackLanguage) {
console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
var key = newLanguage,
prefix = newLanguage.split('-')[0],
matchingLanguage = null;
if (!languages[key]) {
Object.keys(languages).forEach(function(language) {
if (!matchingLanguage && language.split('-')[0] === prefix) {
matchingLanguage = language;
}
});
key = matchingLanguage || fallbackLanguage || 'en-US';
}
chooseCulture(key);
};
/**
* This function allow the user to set a new culture with a fallback if
* the culture does not exist. If no fallback culture is provided,
* it falls back to "en-US".
*/
numbro.setCulture = function(newCulture, fallbackCulture) {
var key = newCulture,
suffix = newCulture.split('-')[1],
matchingCulture = null;
if (!cultures[key]) {
if (suffix) {
Object.keys(cultures).forEach(function(language) {
if (!matchingCulture && language.split('-')[1] === suffix) {
matchingCulture = language;
}
});
}
key = matchingCulture || fallbackCulture || 'en-US';
}
chooseCulture(key);
};
/**
* This function will load languages and then set the global language. If
* no arguments are passed in, it will simply return the current global
* language key.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `culture` should be used instead.
*/
numbro.language = function(key, values) {
console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
if (!key) {
return currentCulture;
}
if (key && !values) {
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
chooseCulture(key);
}
if (values || !languages[key]) {
setCulture(key, values);
}
return numbro;
};
/**
* This function will load cultures and then set the global culture. If
* no arguments are passed in, it will simply return the current global
* culture code.
*/
numbro.culture = function(code, values) {
if (!code) {
return currentCulture;
}
if (code && !values) {
if (!cultures[code]) {
throw new Error('Unknown culture : ' + code);
}
chooseCulture(code);
}
if (values || !cultures[code]) {
setCulture(code, values);
}
return numbro;
};
/**
* This function provides access to the loaded language data. If
* no arguments are passed in, it will simply return the current
* global language object.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `culture` should be used instead.
*/
numbro.languageData = function(key) {
console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
if (!key) {
return languages[currentCulture];
}
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
return languages[key];
};
/**
* This function provides access to the loaded culture data. If
* no arguments are passed in, it will simply return the current
* global culture object.
*/
numbro.cultureData = function(code) {
if (!code) {
return cultures[currentCulture];
}
if (!cultures[code]) {
throw new Error('Unknown culture : ' + code);
}
return cultures[code];
};
numbro.culture('en-US', enUS);
/**
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `cultures` should be used instead.
*/
numbro.languages = function() {
console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
return languages;
};
numbro.cultures = function() {
return cultures;
};
numbro.zeroFormat = function(format) {
zeroFormat = typeof(format) === 'string' ? format : null;
};
numbro.defaultFormat = function(format) {
defaultFormat = typeof(format) === 'string' ? format : '0.0';
};
numbro.defaultCurrencyFormat = function (format) {
defaultCurrencyFormat = typeof(format) === 'string' ? format : '0$';
};
numbro.validate = function(val, culture) {
var _decimalSep,
_thousandSep,
_currSymbol,
_valArray,
_abbrObj,
_thousandRegEx,
cultureData,
temp;
//coerce val to string
if (typeof val !== 'string') {
val += '';
if (console.warn) {
console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
}
}
//trim whitespaces from either sides
val = val.trim();
//replace the initial '+' or '-' sign if present
val = val.replace(/^[+-]?/, '');
//if val is just digits return true
if ( !! val.match(/^\d+$/)) {
return true;
}
//if val is empty return false
if (val === '') {
return false;
}
//get the decimal and thousands separator from numbro.cultureData
try {
//check if the culture is understood by numbro. if not, default it to current culture
cultureData = numbro.cultureData(culture);
} catch (e) {
cultureData = numbro.cultureData(numbro.culture());
}
//setup the delimiters and currency symbol based on culture
_currSymbol = cultureData.currency.symbol;
_abbrObj = cultureData.abbreviations;
_decimalSep = cultureData.delimiters.decimal;
if (cultureData.delimiters.thousands === '.') {
_thousandSep = '\\.';
} else {
_thousandSep = cultureData.delimiters.thousands;
}
// validating currency symbol
temp = val.match(/^[^\d\.\,]+/);
if (temp !== null) {
val = val.substr(1);
if (temp[0] !== _currSymbol) {
return false;
}
}
//validating abbreviation symbol
temp = val.match(/[^\d]+$/);
if (temp !== null) {
val = val.slice(0, -1);
if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
return false;
}
}
_thousandRegEx = new RegExp(_thousandSep + '{2}');
if (!val.match(/[^\d.,]/g)) {
_valArray = val.split(_decimalSep);
if (_valArray.length > 2) {
return false;
} else {
if (_valArray.length < 2) {
return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
} else {
if (_valArray[0] === '') {
// for values without leading zero eg. .984
return (!_valArray[0].match(_thousandRegEx) &&
!!_valArray[1].match(/^\d+$/));
} else if (_valArray[0].length === 1) {
return ( !! _valArray[0].match(/^\d+$/) &&
!_valArray[0].match(_thousandRegEx) &&
!! _valArray[1].match(/^\d+$/));
} else {
return ( !! _valArray[0].match(/^\d+.*\d$/) &&
!_valArray[0].match(_thousandRegEx) &&
!! _valArray[1].match(/^\d+$/));
}
}
}
}
return false;
};
/**
* * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `loadCulturesInNode` should be used instead.
*/
numbro.loadLanguagesInNode = function() {
console.warn('`loadLanguagesInNode` is deprecated since version 1.6.0. Use `loadCulturesInNode` instead');
numbro.loadCulturesInNode();
};
numbro.loadCulturesInNode = function() {
// TODO: Rename the folder in 2.0.0
var cultures = __webpack_require__(27);
for(var langLocaleCode in cultures) {
if(langLocaleCode) {
numbro.culture(langLocaleCode, cultures[langLocaleCode]);
}
}
};
/************************************
Helpers
************************************/
function setCulture(code, values) {
cultures[code] = values;
}
function chooseCulture(code) {
currentCulture = code;
var defaults = cultures[code].defaults;
if (defaults && defaults.format) {
numbro.defaultFormat(defaults.format);
}
if (defaults && defaults.currencyFormat) {
numbro.defaultCurrencyFormat(defaults.currencyFormat);
}
}
function inNodejsRuntime() {
return (typeof process !== 'undefined') &&
(process.browser === undefined) &&
process.title &&
(
process.title.indexOf('node') !== -1 ||
process.title.indexOf('meteor-tool') > 0 ||
process.title === 'grunt' ||
process.title === 'gulp'
) &&
("function" !== 'undefined');
}
/************************************
Floating-point helpers
************************************/
// The floating-point helper functions and implementation
// borrows heavily from sinful.js: http://guipn.github.io/sinful.js/
/**
* Array.prototype.reduce for browsers that don't support it
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Compatibility
*/
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, optInitialValue) {
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index,
value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = optInitialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
/************************************
Numbro Prototype
************************************/
numbro.fn = Numbro.prototype = {
clone: function() {
return numbro(this);
},
format: function(inputString, roundingFunction) {
return formatNumbro(this,
inputString ? inputString : defaultFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
formatCurrency: function(inputString, roundingFunction) {
return formatCurrency(this,
cultures[currentCulture].currency.symbol,
inputString ? inputString : defaultCurrencyFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
formatForeignCurrency: function(currencySymbol, inputString, roundingFunction) {
return formatForeignCurrency(this,
currencySymbol,
inputString ? inputString : defaultCurrencyFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
unformat: function(inputString) {
if (typeof inputString === 'number') {
return inputString;
} else if (typeof inputString === 'string') {
var result = unformatNumbro(this, inputString);
// Any unparseable string (represented as NaN in the result) is
// converted into undefined.
return isNaN(result) ? undefined : result;
} else {
return undefined;
}
},
binaryByteUnits: function() {
return formatByteUnits(this._value, bytes.binary.suffixes, bytes.binary.scale).suffix;
},
byteUnits: function() {
return formatByteUnits(this._value, bytes.general.suffixes, bytes.general.scale).suffix;
},
decimalByteUnits: function() {
return formatByteUnits(this._value, bytes.decimal.suffixes, bytes.decimal.scale).suffix;
},
value: function() {
return this._value;
},
valueOf: function() {
return this._value;
},
set: function(value) {
this._value = Number(value);
return this;
},
add: function(value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr) {
return accum + corrFactor * curr;
}
this._value = [this._value, value].reduce(cback, 0) / corrFactor;
return this;
},
subtract: function(value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr) {
return accum - corrFactor * curr;
}
this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor;
return this;
},
multiply: function(value) {
function cback(accum, curr) {
var corrFactor = correctionFactor(accum, curr),
result = accum * corrFactor;
result *= curr * corrFactor;
result /= corrFactor * corrFactor;
return result;
}
this._value = [this._value, value].reduce(cback, 1);
return this;
},
divide: function(value) {
function cback(accum, curr) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) / (curr * corrFactor);
}
this._value = [this._value, value].reduce(cback);
return this;
},
difference: function(value) {
return Math.abs(numbro(this._value).subtract(value).value());
}
};
/************************************
Exposing Numbro
************************************/
if (inNodejsRuntime()) {
//Todo: Rename the folder in 2.0.0
numbro.loadCulturesInNode();
}
// CommonJS module is defined
if (hasModule) {
module.exports = numbro;
} else {
/*global ender:false */
if (typeof ender === 'undefined') {
// here, `this` means `window` in the browser, or `global` on the server
// add `numbro` as a global object via a string identifier,
// for Closure Compiler 'advanced' mode
this.numbro = numbro;
}
/*global define:false */
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return numbro;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}
}.call(typeof window === 'undefined' ? this : window));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10)))
/***/ }),
/* 10 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
(function (window, factory) {
if (true) {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
window.jStat = factory();
}
})(this, function () {
var jStat = (function(Math, undefined) {
// For quick reference.
var concat = Array.prototype.concat;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
// Calculate correction for IEEE error
// TODO: This calculation can be improved.
function calcRdx(n, m) {
var val = n > m ? n : m;
return Math.pow(10,
17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E));
}
var isArray = Array.isArray || function isArray(arg) {
return toString.call(arg) === '[object Array]';
};
function isFunction(arg) {
return toString.call(arg) === '[object Function]';
}
function isNumber(arg) {
return typeof arg === 'number' && arg === arg;
}
// Converts the jStat matrix to vector.
function toVector(arr) {
return concat.apply([], arr);
}
// The one and only jStat constructor.
function jStat() {
return new jStat._init(arguments);
}
// TODO: Remove after all references in src files have been removed.
jStat.fn = jStat.prototype;
// By separating the initializer from the constructor it's easier to handle
// always returning a new instance whether "new" was used or not.
jStat._init = function _init(args) {
var i;
// If first argument is an array, must be vector or matrix.
if (isArray(args[0])) {
// Check if matrix.
if (isArray(args[0][0])) {
// See if a mapping function was also passed.
if (isFunction(args[1]))
args[0] = jStat.map(args[0], args[1]);
// Iterate over each is faster than this.push.apply(this, args[0].
for (var i = 0; i < args[0].length; i++)
this[i] = args[0][i];
this.length = args[0].length;
// Otherwise must be a vector.
} else {
this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0];
this.length = 1;
}
// If first argument is number, assume creation of sequence.
} else if (isNumber(args[0])) {
this[0] = jStat.seq.apply(null, args);
this.length = 1;
// Handle case when jStat object is passed to jStat.
} else if (args[0] instanceof jStat) {
// Duplicate the object and pass it back.
return jStat(args[0].toArray());
// Unexpected argument value, return empty jStat object.
// TODO: This is strange behavior. Shouldn't this throw or some such to let
// the user know they had bad arguments?
} else {
this[0] = [];
this.length = 1;
}
return this;
};
jStat._init.prototype = jStat.prototype;
jStat._init.constructor = jStat;
// Utility functions.
// TODO: for internal use only?
jStat.utils = {
calcRdx: calcRdx,
isArray: isArray,
isFunction: isFunction,
isNumber: isNumber,
toVector: toVector
};
// Easily extend the jStat object.
// TODO: is this seriously necessary?
jStat.extend = function extend(obj) {
var i, j;
if (arguments.length === 1) {
for (j in obj)
jStat[j] = obj[j];
return this;
}
for (var i = 1; i < arguments.length; i++) {
for (j in arguments[i])
obj[j] = arguments[i][j];
}
return obj;
};
// Returns the number of rows in the matrix.
jStat.rows = function rows(arr) {
return arr.length || 1;
};
// Returns the number of columns in the matrix.
jStat.cols = function cols(arr) {
return arr[0].length || 1;
};
// Returns the dimensions of the object { rows: i, cols: j }
jStat.dimensions = function dimensions(arr) {
return {
rows: jStat.rows(arr),
cols: jStat.cols(arr)
};
};
// Returns a specified row as a vector or return a sub matrix by pick some rows
jStat.row = function row(arr, index) {
if (isArray(index)) {
return index.map(function(i) {
return jStat.row(arr, i);
})
}
return arr[index];
};
// return row as array
// rowa([[1,2],[3,4]],0) -> [1,2]
jStat.rowa = function rowa(arr, i) {
return jStat.row(arr, i);
};
// Returns the specified column as a vector or return a sub matrix by pick some
// columns
jStat.col = function col(arr, index) {
if (isArray(index)) {
var submat = jStat.arange(arr.length).map(function(i) {
return new Array(index.length);
});
index.forEach(function(ind, i){
jStat.arange(arr.length).forEach(function(j) {
submat[j][i] = arr[j][ind];
});
});
return submat;
}
var column = new Array(arr.length);
for (var i = 0; i < arr.length; i++)
column[i] = [arr[i][index]];
return column;
};
// return column as array
// cola([[1,2],[3,4]],0) -> [1,3]
jStat.cola = function cola(arr, i) {
return jStat.col(arr, i).map(function(a){ return a[0] });
};
// Returns the diagonal of the matrix
jStat.diag = function diag(arr) {
var nrow = jStat.rows(arr);
var res = new Array(nrow);
for (var row = 0; row < nrow; row++)
res[row] = [arr[row][row]];
return res;
};
// Returns the anti-diagonal of the matrix
jStat.antidiag = function antidiag(arr) {
var nrow = jStat.rows(arr) - 1;
var res = new Array(nrow);
for (var i = 0; nrow >= 0; nrow--, i++)
res[i] = [arr[i][nrow]];
return res;
};
// Transpose a matrix or array.
jStat.transpose = function transpose(arr) {
var obj = [];
var objArr, rows, cols, j, i;
// Make sure arr is in matrix format.
if (!isArray(arr[0]))
arr = [arr];
rows = arr.length;
cols = arr[0].length;
for (var i = 0; i < cols; i++) {
objArr = new Array(rows);
for (j = 0; j < rows; j++)
objArr[j] = arr[j][i];
obj.push(objArr);
}
// If obj is vector, return only single array.
return obj.length === 1 ? obj[0] : obj;
};
// Map a function to an array or array of arrays.
// "toAlter" is an internal variable.
jStat.map = function map(arr, func, toAlter) {
var row, nrow, ncol, res, col;
if (!isArray(arr[0]))
arr = [arr];
nrow = arr.length;
ncol = arr[0].length;
res = toAlter ? arr : new Array(nrow);
for (row = 0; row < nrow; row++) {
// if the row doesn't exist, create it
if (!res[row])
res[row] = new Array(ncol);
for (col = 0; col < ncol; col++)
res[row][col] = func(arr[row][col], row, col);
}
return res.length === 1 ? res[0] : res;
};
// Cumulatively combine the elements of an array or array of arrays using a function.
jStat.cumreduce = function cumreduce(arr, func, toAlter) {
var row, nrow, ncol, res, col;
if (!isArray(arr[0]))
arr = [arr];
nrow = arr.length;
ncol = arr[0].length;
res = toAlter ? arr : new Array(nrow);
for (row = 0; row < nrow; row++) {
// if the row doesn't exist, create it
if (!res[row])
res[row] = new Array(ncol);
if (ncol > 0)
res[row][0] = arr[row][0];
for (col = 1; col < ncol; col++)
res[row][col] = func(res[row][col-1], arr[row][col]);
}
return res.length === 1 ? res[0] : res;
};
// Destructively alter an array.
jStat.alter = function alter(arr, func) {
return jStat.map(arr, func, true);
};
// Generate a rows x cols matrix according to the supplied function.
jStat.create = function create(rows, cols, func) {
var res = new Array(rows);
var i, j;
if (isFunction(cols)) {
func = cols;
cols = rows;
}
for (var i = 0; i < rows; i++) {
res[i] = new Array(cols);
for (j = 0; j < cols; j++)
res[i][j] = func(i, j);
}
return res;
};
function retZero() { return 0; }
// Generate a rows x cols matrix of zeros.
jStat.zeros = function zeros(rows, cols) {
if (!isNumber(cols))
cols = rows;
return jStat.create(rows, cols, retZero);
};
function retOne() { return 1; }
// Generate a rows x cols matrix of ones.
jStat.ones = function ones(rows, cols) {
if (!isNumber(cols))
cols = rows;
return jStat.create(rows, cols, retOne);
};
// Generate a rows x cols matrix of uniformly random numbers.
jStat.rand = function rand(rows, cols) {
if (!isNumber(cols))
cols = rows;
return jStat.create(rows, cols, Math.random);
};
function retIdent(i, j) { return i === j ? 1 : 0; }
// Generate an identity matrix of size row x cols.
jStat.identity = function identity(rows, cols) {
if (!isNumber(cols))
cols = rows;
return jStat.create(rows, cols, retIdent);
};
// Tests whether a matrix is symmetric
jStat.symmetric = function symmetric(arr) {
var issymmetric = true;
var size = arr.length;
var row, col;
if (arr.length !== arr[0].length)
return false;
for (row = 0; row < size; row++) {
for (col = 0; col < size; col++)
if (arr[col][row] !== arr[row][col])
return false;
}
return true;
};
// Set all values to zero.
jStat.clear = function clear(arr) {
return jStat.alter(arr, retZero);
};
// Generate sequence.
jStat.seq = function seq(min, max, length, func) {
if (!isFunction(func))
func = false;
var arr = [];
var hival = calcRdx(min, max);
var step = (max * hival - min * hival) / ((length - 1) * hival);
var current = min;
var cnt;
// Current is assigned using a technique to compensate for IEEE error.
// TODO: Needs better implementation.
for (cnt = 0;
current <= max && cnt < length;
cnt++, current = (min * hival + step * hival * cnt) / hival) {
arr.push((func ? func(current, cnt) : current));
}
return arr;
};
// arange(5) -> [0,1,2,3,4]
// arange(1,5) -> [1,2,3,4]
// arange(5,1,-1) -> [5,4,3,2]
jStat.arange = function arange(start, end, step) {
var rl = [];
step = step || 1;
if (end === undefined) {
end = start;
start = 0;
}
if (start === end || step === 0) {
return [];
}
if (start < end && step < 0) {
return [];
}
if (start > end && step > 0) {
return [];
}
if (step > 0) {
for (i = start; i < end; i += step) {
rl.push(i);
}
} else {
for (i = start; i > end; i += step) {
rl.push(i);
}
}
return rl;
};
// A=[[1,2,3],[4,5,6],[7,8,9]]
// slice(A,{row:{end:2},col:{start:1}}) -> [[2,3],[5,6]]
// slice(A,1,{start:1}) -> [5,6]
// as numpy code A[:2,1:]
jStat.slice = (function(){
function _slice(list, start, end, step) {
// note it's not equal to range.map mode it's a bug
var i;
var rl = [];
var length = list.length;
if (start === undefined && end === undefined && step === undefined) {
return jStat.copy(list);
}
start = start || 0;
end = end || list.length;
start = start >= 0 ? start : length + start;
end = end >= 0 ? end : length + end;
step = step || 1;
if (start === end || step === 0) {
return [];
}
if (start < end && step < 0) {
return [];
}
if (start > end && step > 0) {
return [];
}
if (step > 0) {
for (i = start; i < end; i += step) {
rl.push(list[i]);
}
} else {
for (i = start; i > end;i += step) {
rl.push(list[i]);
}
}
return rl;
}
function slice(list, rcSlice) {
rcSlice = rcSlice || {};
if (isNumber(rcSlice.row)) {
if (isNumber(rcSlice.col))
return list[rcSlice.row][rcSlice.col];
var row = jStat.rowa(list, rcSlice.row);
var colSlice = rcSlice.col || {};
return _slice(row, colSlice.start, colSlice.end, colSlice.step);
}
if (isNumber(rcSlice.col)) {
var col = jStat.cola(list, rcSlice.col);
var rowSlice = rcSlice.row || {};
return _slice(col, rowSlice.start, rowSlice.end, rowSlice.step);
}
var rowSlice = rcSlice.row || {};
var colSlice = rcSlice.col || {};
var rows = _slice(list, rowSlice.start, rowSlice.end, rowSlice.step);
return rows.map(function(row) {
return _slice(row, colSlice.start, colSlice.end, colSlice.step);
});
}
return slice;
}());
// A=[[1,2,3],[4,5,6],[7,8,9]]
// sliceAssign(A,{row:{start:1},col:{start:1}},[[0,0],[0,0]])
// A=[[1,2,3],[4,0,0],[7,0,0]]
jStat.sliceAssign = function sliceAssign(A, rcSlice, B) {
if (isNumber(rcSlice.row)) {
if (isNumber(rcSlice.col))
return A[rcSlice.row][rcSlice.col] = B;
rcSlice.col = rcSlice.col || {};
rcSlice.col.start = rcSlice.col.start || 0;
rcSlice.col.end = rcSlice.col.end || A[0].length;
rcSlice.col.step = rcSlice.col.step || 1;
var nl = jStat.arange(rcSlice.col.start,
Math.min(A.length, rcSlice.col.end),
rcSlice.col.step);
var m = rcSlice.row;
nl.forEach(function(n, i) {
A[m][n] = B[i];
});
return A;
}
if (isNumber(rcSlice.col)) {
rcSlice.row = rcSlice.row || {};
rcSlice.row.start = rcSlice.row.start || 0;
rcSlice.row.end = rcSlice.row.end || A.length;
rcSlice.row.step = rcSlice.row.step || 1;
var ml = jStat.arange(rcSlice.row.start,
Math.min(A[0].length, rcSlice.row.end),
rcSlice.row.step);
var n = rcSlice.col;
ml.forEach(function(m, j) {
A[m][n] = B[j];
});
return A;
}
if (B[0].length === undefined) {
B = [B];
}
rcSlice.row.start = rcSlice.row.start || 0;
rcSlice.row.end = rcSlice.row.end || A.length;
rcSlice.row.step = rcSlice.row.step || 1;
rcSlice.col.start = rcSlice.col.start || 0;
rcSlice.col.end = rcSlice.col.end || A[0].length;
rcSlice.col.step = rcSlice.col.step || 1;
var ml = jStat.arange(rcSlice.row.start,
Math.min(A.length, rcSlice.row.end),
rcSlice.row.step);
var nl = jStat.arange(rcSlice.col.start,
Math.min(A[0].length, rcSlice.col.end),
rcSlice.col.step);
ml.forEach(function(m, i) {
nl.forEach(function(n, j) {
A[m][n] = B[i][j];
});
});
return A;
};
// [1,2,3] ->
// [[1,0,0],[0,2,0],[0,0,3]]
jStat.diagonal = function diagonal(diagArray) {
var mat = jStat.zeros(diagArray.length, diagArray.length);
diagArray.forEach(function(t, i) {
mat[i][i] = t;
});
return mat;
};
// return copy of A
jStat.copy = function copy(A) {
return A.map(function(row) {
if (isNumber(row))
return row;
return row.map(function(t) {
return t;
});
});
};
// TODO: Go over this entire implementation. Seems a tragic waste of resources
// doing all this work. Instead, and while ugly, use new Function() to generate
// a custom function for each static method.
// Quick reference.
var jProto = jStat.prototype;
// Default length.
jProto.length = 0;
// For internal use only.
// TODO: Check if they're actually used, and if they are then rename them
// to _*
jProto.push = Array.prototype.push;
jProto.sort = Array.prototype.sort;
jProto.splice = Array.prototype.splice;
jProto.slice = Array.prototype.slice;
// Return a clean array.
jProto.toArray = function toArray() {
return this.length > 1 ? slice.call(this) : slice.call(this)[0];
};
// Map a function to a matrix or vector.
jProto.map = function map(func, toAlter) {
return jStat(jStat.map(this, func, toAlter));
};
// Cumulatively combine the elements of a matrix or vector using a function.
jProto.cumreduce = function cumreduce(func, toAlter) {
return jStat(jStat.cumreduce(this, func, toAlter));
};
// Destructively alter an array.
jProto.alter = function alter(func) {
jStat.alter(this, func);
return this;
};
// Extend prototype with methods that have no argument.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jProto[passfunc] = function(func) {
var self = this,
results;
// Check for callback.
if (func) {
setTimeout(function() {
func.call(self, jProto[passfunc].call(self));
});
return this;
}
results = jStat[passfunc](this);
return isArray(results) ? jStat(results) : results;
};
})(funcs[i]);
})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' '));
// Extend prototype with methods that have one argument.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jProto[passfunc] = function(index, func) {
var self = this;
// check for callback
if (func) {
setTimeout(function() {
func.call(self, jProto[passfunc].call(self, index));
});
return this;
}
return jStat(jStat[passfunc](this, index));
};
})(funcs[i]);
})('row col'.split(' '));
// Extend prototype with simple shortcut methods.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jProto[passfunc] = new Function(
'return jStat(jStat.' + passfunc + '.apply(null, arguments));');
})(funcs[i]);
})('create zeros ones rand identity'.split(' '));
// Exposing jStat.
return jStat;
}(Math));
(function(jStat, Math) {
var isFunction = jStat.utils.isFunction;
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
}
// sum of an array
jStat.sum = function sum(arr) {
var sum = 0;
var i = arr.length;
while (--i >= 0)
sum += arr[i];
return sum;
};
// sum squared
jStat.sumsqrd = function sumsqrd(arr) {
var sum = 0;
var i = arr.length;
while (--i >= 0)
sum += arr[i] * arr[i];
return sum;
};
// sum of squared errors of prediction (SSE)
jStat.sumsqerr = function sumsqerr(arr) {
var mean = jStat.mean(arr);
var sum = 0;
var i = arr.length;
var tmp;
while (--i >= 0) {
tmp = arr[i] - mean;
sum += tmp * tmp;
}
return sum;
};
// sum of an array in each row
jStat.sumrow = function sumrow(arr) {
var sum = 0;
var i = arr.length;
while (--i >= 0)
sum += arr[i];
return sum;
};
// product of an array
jStat.product = function product(arr) {
var prod = 1;
var i = arr.length;
while (--i >= 0)
prod *= arr[i];
return prod;
};
// minimum value of an array
jStat.min = function min(arr) {
var low = arr[0];
var i = 0;
while (++i < arr.length)
if (arr[i] < low)
low = arr[i];
return low;
};
// maximum value of an array
jStat.max = function max(arr) {
var high = arr[0];
var i = 0;
while (++i < arr.length)
if (arr[i] > high)
high = arr[i];
return high;
};
// unique values of an array
jStat.unique = function unique(arr) {
var hash = {}, _arr = [];
for(var i = 0; i < arr.length; i++) {
if (!hash[arr[i]]) {
hash[arr[i]] = true;
_arr.push(arr[i]);
}
}
return _arr;
};
// mean value of an array
jStat.mean = function mean(arr) {
return jStat.sum(arr) / arr.length;
};
// mean squared error (MSE)
jStat.meansqerr = function meansqerr(arr) {
return jStat.sumsqerr(arr) / arr.length;
};
// geometric mean of an array
jStat.geomean = function geomean(arr) {
return Math.pow(jStat.product(arr), 1 / arr.length);
};
// median of an array
jStat.median = function median(arr) {
var arrlen = arr.length;
var _arr = arr.slice().sort(ascNum);
// check if array is even or odd, then return the appropriate
return !(arrlen & 1)
? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2
: _arr[(arrlen / 2) | 0 ];
};
// cumulative sum of an array
jStat.cumsum = function cumsum(arr) {
return jStat.cumreduce(arr, function (a, b) { return a + b; });
};
// cumulative product of an array
jStat.cumprod = function cumprod(arr) {
return jStat.cumreduce(arr, function (a, b) { return a * b; });
};
// successive differences of a sequence
jStat.diff = function diff(arr) {
var diffs = [];
var arrLen = arr.length;
var i;
for (var i = 1; i < arrLen; i++)
diffs.push(arr[i] - arr[i - 1]);
return diffs;
};
// ranks of an array
jStat.rank = function (arr) {
var arrlen = arr.length;
var sorted = arr.slice().sort(ascNum);
var ranks = new Array(arrlen);
for (var i = 0; i < arrlen; i++) {
var first = sorted.indexOf(arr[i]);
var last = sorted.lastIndexOf(arr[i]);
if (first === last) {
var val = first;
} else {
var val = (first + last) / 2;
}
ranks[i] = val + 1;
}
return ranks;
};
// mode of an array
// if there are multiple modes of an array, return all of them
// is this the appropriate way of handling it?
jStat.mode = function mode(arr) {
var arrLen = arr.length;
var _arr = arr.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (var i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
// range of an array
jStat.range = function range(arr) {
return jStat.max(arr) - jStat.min(arr);
};
// variance of an array
// flag = true indicates sample instead of population
jStat.variance = function variance(arr, flag) {
return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0));
};
// pooled variance of an array of arrays
jStat.pooledvariance = function pooledvariance(arr) {
var sumsqerr = arr.reduce(function (a, samples) {return a + jStat.sumsqerr(samples);}, 0);
var count = arr.reduce(function (a, samples) {return a + samples.length;}, 0);
return sumsqerr / (count - arr.length);
};
// deviation of an array
jStat.deviation = function (arr) {
var mean = jStat.mean(arr);
var arrlen = arr.length;
var dev = new Array(arrlen);
for (var i = 0; i < arrlen; i++) {
dev[i] = arr[i] - mean;
}
return dev;
};
// standard deviation of an array
// flag = true indicates sample instead of population
jStat.stdev = function stdev(arr, flag) {
return Math.sqrt(jStat.variance(arr, flag));
};
// pooled standard deviation of an array of arrays
jStat.pooledstdev = function pooledstdev(arr) {
return Math.sqrt(jStat.pooledvariance(arr));
};
// mean deviation (mean absolute deviation) of an array
jStat.meandev = function meandev(arr) {
var mean = jStat.mean(arr);
var a = [];
for (var i = arr.length - 1; i >= 0; i--) {
a.push(Math.abs(arr[i] - mean));
}
return jStat.mean(a);
};
// median deviation (median absolute deviation) of an array
jStat.meddev = function meddev(arr) {
var median = jStat.median(arr);
var a = [];
for (var i = arr.length - 1; i >= 0; i--) {
a.push(Math.abs(arr[i] - median));
}
return jStat.median(a);
};
// coefficient of variation
jStat.coeffvar = function coeffvar(arr) {
return jStat.stdev(arr) / jStat.mean(arr);
};
// quartiles of an array
jStat.quartiles = function quartiles(arr) {
var arrlen = arr.length;
var _arr = arr.slice().sort(ascNum);
return [
_arr[ Math.round((arrlen) / 4) - 1 ],
_arr[ Math.round((arrlen) / 2) - 1 ],
_arr[ Math.round((arrlen) * 3 / 4) - 1 ]
];
};
// Arbitary quantiles of an array. Direct port of the scipy.stats
// implementation by Pierre GF Gerard-Marchant.
jStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) {
var sortedArray = arr.slice().sort(ascNum);
var quantileVals = [quantilesArray.length];
var n = arr.length;
var i, p, m, aleph, k, gamma;
if (typeof alphap === 'undefined')
alphap = 3 / 8;
if (typeof betap === 'undefined')
betap = 3 / 8;
for (var i = 0; i < quantilesArray.length; i++) {
p = quantilesArray[i];
m = alphap + p * (1 - alphap - betap);
aleph = n * p + m;
k = Math.floor(clip(aleph, 1, n - 1));
gamma = clip(aleph - k, 0, 1);
quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k];
}
return quantileVals;
};
// Returns the k-th percentile of values in a range, where k is in the
// range 0..1, exclusive.
jStat.percentile = function percentile(arr, k) {
var _arr = arr.slice().sort(ascNum);
var realIndex = k * (_arr.length - 1);
var index = parseInt(realIndex);
var frac = realIndex - index;
if (index + 1 < _arr.length) {
return _arr[index] * (1 - frac) + _arr[index + 1] * frac;
} else {
return _arr[index];
}
}
// The percentile rank of score in a given array. Returns the percentage
// of all values in the input array that are less than (kind='strict') or
// less or equal than (kind='weak') score. Default is weak.
jStat.percentileOfScore = function percentileOfScore(arr, score, kind) {
var counter = 0;
var len = arr.length;
var strict = false;
var value, i;
if (kind === 'strict')
strict = true;
for (var i = 0; i < len; i++) {
value = arr[i];
if ((strict && value < score) ||
(!strict && value <= score)) {
counter++;
}
}
return counter / len;
};
// Histogram (bin count) data
jStat.histogram = function histogram(arr, bins) {
var first = jStat.min(arr);
var binCnt = bins || 4;
var binWidth = (jStat.max(arr) - first) / binCnt;
var len = arr.length;
var bins = [];
var i;
for (var i = 0; i < binCnt; i++)
bins[i] = 0;
for (var i = 0; i < len; i++)
bins[Math.min(Math.floor(((arr[i] - first) / binWidth)), binCnt - 1)] += 1;
return bins;
};
// covariance of two arrays
jStat.covariance = function covariance(arr1, arr2) {
var u = jStat.mean(arr1);
var v = jStat.mean(arr2);
var arr1Len = arr1.length;
var sq_dev = new Array(arr1Len);
var i;
for (var i = 0; i < arr1Len; i++)
sq_dev[i] = (arr1[i] - u) * (arr2[i] - v);
return jStat.sum(sq_dev) / (arr1Len - 1);
};
// (pearson's) population correlation coefficient, rho
jStat.corrcoeff = function corrcoeff(arr1, arr2) {
return jStat.covariance(arr1, arr2) /
jStat.stdev(arr1, 1) /
jStat.stdev(arr2, 1);
};
// (spearman's) rank correlation coefficient, sp
jStat.spearmancoeff = function (arr1, arr2) {
arr1 = jStat.rank(arr1);
arr2 = jStat.rank(arr2);
//return pearson's correlation of the ranks:
return jStat.corrcoeff(arr1, arr2);
}
// statistical standardized moments (general form of skew/kurt)
jStat.stanMoment = function stanMoment(arr, n) {
var mu = jStat.mean(arr);
var sigma = jStat.stdev(arr);
var len = arr.length;
var skewSum = 0;
for (var i = 0; i < len; i++)
skewSum += Math.pow((arr[i] - mu) / sigma, n);
return skewSum / arr.length;
};
// (pearson's) moment coefficient of skewness
jStat.skewness = function skewness(arr) {
return jStat.stanMoment(arr, 3);
};
// (pearson's) (excess) kurtosis
jStat.kurtosis = function kurtosis(arr) {
return jStat.stanMoment(arr, 4) - 3;
};
var jProto = jStat.prototype;
// Extend jProto with method for calculating cumulative sums and products.
// This differs from the similar extension below as cumsum and cumprod should
// not be run again in the case fullbool === true.
// If a matrix is passed, automatically assume operation should be done on the
// columns.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
// If a matrix is passed, automatically assume operation should be done on
// the columns.
jProto[passfunc] = function(fullbool, func) {
var arr = [];
var i = 0;
var tmpthis = this;
// Assignment reassignation depending on how parameters were passed in.
if (isFunction(fullbool)) {
func = fullbool;
fullbool = false;
}
// Check if a callback was passed with the function.
if (func) {
setTimeout(function() {
func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
});
return this;
}
// Check if matrix and run calculations.
if (this.length > 1) {
tmpthis = fullbool === true ? this : this.transpose();
for (; i < tmpthis.length; i++)
arr[i] = jStat[passfunc](tmpthis[i]);
return arr;
}
// Pass fullbool if only vector, not a matrix. for variance and stdev.
return jStat[passfunc](this[0], fullbool);
};
})(funcs[i]);
})(('cumsum cumprod').split(' '));
// Extend jProto with methods which don't require arguments and work on columns.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
// If a matrix is passed, automatically assume operation should be done on
// the columns.
jProto[passfunc] = function(fullbool, func) {
var arr = [];
var i = 0;
var tmpthis = this;
// Assignment reassignation depending on how parameters were passed in.
if (isFunction(fullbool)) {
func = fullbool;
fullbool = false;
}
// Check if a callback was passed with the function.
if (func) {
setTimeout(function() {
func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
});
return this;
}
// Check if matrix and run calculations.
if (this.length > 1) {
if (passfunc !== 'sumrow')
tmpthis = fullbool === true ? this : this.transpose();
for (; i < tmpthis.length; i++)
arr[i] = jStat[passfunc](tmpthis[i]);
return fullbool === true
? jStat[passfunc](jStat.utils.toVector(arr))
: arr;
}
// Pass fullbool if only vector, not a matrix. for variance and stdev.
return jStat[passfunc](this[0], fullbool);
};
})(funcs[i]);
})(('sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr ' +
'geomean median diff rank mode range variance deviation stdev meandev ' +
'meddev coeffvar quartiles histogram skewness kurtosis').split(' '));
// Extend jProto with functions that take arguments. Operations on matrices are
// done on columns.
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jProto[passfunc] = function() {
var arr = [];
var i = 0;
var tmpthis = this;
var args = Array.prototype.slice.call(arguments);
// If the last argument is a function, we assume it's a callback; we
// strip the callback out and call the function again.
if (isFunction(args[args.length - 1])) {
var callbackFunction = args[args.length - 1];
var argsToPass = args.slice(0, args.length - 1);
setTimeout(function() {
callbackFunction.call(tmpthis,
jProto[passfunc].apply(tmpthis, argsToPass));
});
return this;
// Otherwise we curry the function args and call normally.
} else {
var callbackFunction = undefined;
var curriedFunction = function curriedFunction(vector) {
return jStat[passfunc].apply(tmpthis, [vector].concat(args));
}
}
// If this is a matrix, run column-by-column.
if (this.length > 1) {
tmpthis = tmpthis.transpose();
for (; i < tmpthis.length; i++)
arr[i] = curriedFunction(tmpthis[i]);
return arr;
}
// Otherwise run on the vector.
return curriedFunction(this[0]);
};
})(funcs[i]);
})('quantiles percentileOfScore'.split(' '));
}(jStat, Math));
// Special functions //
(function(jStat, Math) {
// Log-gamma function
jStat.gammaln = function gammaln(x) {
var j = 0;
var cof = [
76.18009172947146, -86.50532032941677, 24.01409824083091,
-1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5
];
var ser = 1.000000000190015;
var xx, y, tmp;
tmp = (y = xx = x) + 5.5;
tmp -= (xx + 0.5) * Math.log(tmp);
for (; j < 6; j++)
ser += cof[j] / ++y;
return Math.log(2.5066282746310005 * ser / xx) - tmp;
};
// gamma of x
jStat.gammafn = function gammafn(x) {
var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563,
629.3311553128184, 866.9662027904133, -31451.272968848367,
-36144.413418691176, 66456.14382024054
];
var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192,
-3107.771671572311, 22538.118420980151, 4755.8462775278811,
-134659.9598649693, -115132.2596755535];
var fact = false;
var n = 0;
var xden = 0;
var xnum = 0;
var y = x;
var i, z, yi, res, sum, ysq;
if (y <= 0) {
res = y % 1 + 3.6e-16;
if (res) {
fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res);
y = 1 - y;
} else {
return Infinity;
}
}
yi = y;
if (y < 1) {
z = y++;
} else {
z = (y -= n = (y | 0) - 1) - 1;
}
for (var i = 0; i < 8; ++i) {
xnum = (xnum + p[i]) * z;
xden = xden * z + q[i];
}
res = xnum / xden + 1;
if (yi < y) {
res /= yi;
} else if (yi > y) {
for (var i = 0; i < n; ++i) {
res *= y;
y++;
}
}
if (fact) {
res = fact / res;
}
return res;
};
// lower incomplete gamma function, which is usually typeset with a
// lower-case greek gamma as the function symbol
jStat.gammap = function gammap(a, x) {
return jStat.lowRegGamma(a, x) * jStat.gammafn(a);
};
// The lower regularized incomplete gamma function, usually written P(a,x)
jStat.lowRegGamma = function lowRegGamma(a, x) {
var aln = jStat.gammaln(a);
var ap = a;
var sum = 1 / a;
var del = sum;
var b = x + 1 - a;
var c = 1 / 1.0e-30;
var d = 1 / b;
var h = d;
var i = 1;
// calculate maximum number of itterations required for a
var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17);
var an, endval;
if (x < 0 || a <= 0) {
return NaN;
} else if (x < a + 1) {
for (; i <= ITMAX; i++) {
sum += del *= x / ++ap;
}
return (sum * Math.exp(-x + a * Math.log(x) - (aln)));
}
for (; i <= ITMAX; i++) {
an = -i * (i - a);
b += 2;
d = an * d + b;
c = b + an / c;
d = 1 / d;
h *= d * c;
}
return (1 - h * Math.exp(-x + a * Math.log(x) - (aln)));
};
// natural log factorial of n
jStat.factorialln = function factorialln(n) {
return n < 0 ? NaN : jStat.gammaln(n + 1);
};
// factorial of n
jStat.factorial = function factorial(n) {
return n < 0 ? NaN : jStat.gammafn(n + 1);
};
// combinations of n, m
jStat.combination = function combination(n, m) {
// make sure n or m don't exceed the upper limit of usable values
return (n > 170 || m > 170)
? Math.exp(jStat.combinationln(n, m))
: (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m);
};
jStat.combinationln = function combinationln(n, m){
return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m);
};
// permutations of n, m
jStat.permutation = function permutation(n, m) {
return jStat.factorial(n) / jStat.factorial(n - m);
};
// beta function
jStat.betafn = function betafn(x, y) {
// ensure arguments are positive
if (x <= 0 || y <= 0)
return undefined;
// make sure x + y doesn't exceed the upper limit of usable values
return (x + y > 170)
? Math.exp(jStat.betaln(x, y))
: jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y);
};
// natural logarithm of beta function
jStat.betaln = function betaln(x, y) {
return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y);
};
// Evaluates the continued fraction for incomplete beta function by modified
// Lentz's method.
jStat.betacf = function betacf(x, a, b) {
var fpmin = 1e-30;
var m = 1;
var qab = a + b;
var qap = a + 1;
var qam = a - 1;
var c = 1;
var d = 1 - qab * x / qap;
var m2, aa, del, h;
// These q's will be used in factors that occur in the coefficients
if (Math.abs(d) < fpmin)
d = fpmin;
d = 1 / d;
h = d;
for (; m <= 100; m++) {
m2 = 2 * m;
aa = m * (b - m) * x / ((qam + m2) * (a + m2));
// One step (the even one) of the recurrence
d = 1 + aa * d;
if (Math.abs(d) < fpmin)
d = fpmin;
c = 1 + aa / c;
if (Math.abs(c) < fpmin)
c = fpmin;
d = 1 / d;
h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
// Next step of the recurrence (the odd one)
d = 1 + aa * d;
if (Math.abs(d) < fpmin)
d = fpmin;
c = 1 + aa / c;
if (Math.abs(c) < fpmin)
c = fpmin;
d = 1 / d;
del = d * c;
h *= del;
if (Math.abs(del - 1.0) < 3e-7)
break;
}
return h;
};
// Returns the inverse of the lower regularized inomplete gamma function
jStat.gammapinv = function gammapinv(p, a) {
var j = 0;
var a1 = a - 1;
var EPS = 1e-8;
var gln = jStat.gammaln(a);
var x, err, t, u, pp, lna1, afac;
if (p >= 1)
return Math.max(100, a + 100 * Math.sqrt(a));
if (p <= 0)
return 0;
if (a > 1) {
lna1 = Math.log(a1);
afac = Math.exp(a1 * (lna1 - 1) - gln);
pp = (p < 0.5) ? p : 1 - p;
t = Math.sqrt(-2 * Math.log(pp));
x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
if (p < 0.5)
x = -x;
x = Math.max(1e-3,
a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3));
} else {
t = 1 - a * (0.253 + a * 0.12);
if (p < t)
x = Math.pow(p / t, 1 / a);
else
x = 1 - Math.log(1 - (p - t) / (1 - t));
}
for(; j < 12; j++) {
if (x <= 0)
return 0;
err = jStat.lowRegGamma(a, x) - p;
if (a > 1)
t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1));
else
t = Math.exp(-x + a1 * Math.log(x) - gln);
u = err / t;
x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1))));
if (x <= 0)
x = 0.5 * (x + t);
if (Math.abs(t) < EPS * x)
break;
}
return x;
};
// Returns the error function erf(x)
jStat.erf = function erf(x) {
var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,
-9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4,
4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6,
1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8,
6.529054439e-9, 5.059343495e-9, -9.91364156e-10,
-2.27365122e-10, 9.6467911e-11, 2.394038e-12,
-6.886027e-12, 8.94487e-13, 3.13092e-13,
-1.12708e-13, 3.81e-16, 7.106e-15,
-1.523e-15, -9.4e-17, 1.21e-16,
-2.8e-17];
var j = cof.length - 1;
var isneg = false;
var d = 0;
var dd = 0;
var t, ty, tmp, res;
if (x < 0) {
x = -x;
isneg = true;
}
t = 2 / (2 + x);
ty = 4 * t - 2;
for(; j > 0; j--) {
tmp = d;
d = ty * d - dd + cof[j];
dd = tmp;
}
res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd);
return isneg ? res - 1 : 1 - res;
};
// Returns the complmentary error function erfc(x)
jStat.erfc = function erfc(x) {
return 1 - jStat.erf(x);
};
// Returns the inverse of the complementary error function
jStat.erfcinv = function erfcinv(p) {
var j = 0;
var x, err, t, pp;
if (p >= 2)
return -100;
if (p <= 0)
return 100;
pp = (p < 1) ? p : 2 - p;
t = Math.sqrt(-2 * Math.log(pp / 2));
x = -0.70711 * ((2.30753 + t * 0.27061) /
(1 + t * (0.99229 + t * 0.04481)) - t);
for (; j < 2; j++) {
err = jStat.erfc(x) - pp;
x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err);
}
return (p < 1) ? x : -x;
};
// Returns the inverse of the incomplete beta function
jStat.ibetainv = function ibetainv(p, a, b) {
var EPS = 1e-8;
var a1 = a - 1;
var b1 = b - 1;
var j = 0;
var lna, lnb, pp, t, u, err, x, al, h, w, afac;
if (p <= 0)
return 0;
if (p >= 1)
return 1;
if (a >= 1 && b >= 1) {
pp = (p < 0.5) ? p : 1 - p;
t = Math.sqrt(-2 * Math.log(pp));
x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t;
if (p < 0.5)
x = -x;
al = (x * x - 3) / 6;
h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) *
(al + 5 / 6 - 2 / (3 * h));
x = a / (a + b * Math.exp(2 * w));
} else {
lna = Math.log(a / (a + b));
lnb = Math.log(b / (a + b));
t = Math.exp(a * lna) / a;
u = Math.exp(b * lnb) / b;
w = t + u;
if (p < t / w)
x = Math.pow(a * w * p, 1 / a);
else
x = 1 - Math.pow(b * w * (1 - p), 1 / b);
}
afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b);
for(; j < 10; j++) {
if (x === 0 || x === 1)
return x;
err = jStat.ibeta(x, a, b) - p;
t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac);
u = err / t;
x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))));
if (x <= 0)
x = 0.5 * (x + t);
if (x >= 1)
x = 0.5 * (x + t + 1);
if (Math.abs(t) < EPS * x && j > 0)
break;
}
return x;
};
// Returns the incomplete beta function I_x(a,b)
jStat.ibeta = function ibeta(x, a, b) {
// Factors in front of the continued fraction.
var bt = (x === 0 || x === 1) ? 0 :
Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) -
jStat.gammaln(b) + a * Math.log(x) + b *
Math.log(1 - x));
if (x < 0 || x > 1)
return false;
if (x < (a + 1) / (a + b + 2))
// Use continued fraction directly.
return bt * jStat.betacf(x, a, b) / a;
// else use continued fraction after making the symmetry transformation.
return 1 - bt * jStat.betacf(1 - x, b, a) / b;
};
// Returns a normal deviate (mu=0, sigma=1).
// If n and m are specified it returns a object of normal deviates.
jStat.randn = function randn(n, m) {
var u, v, x, y, q, mat;
if (!m)
m = n;
if (n)
return jStat.create(n, m, function() { return jStat.randn(); });
do {
u = Math.random();
v = 1.7156 * (Math.random() - 0.5);
x = u - 0.449871;
y = Math.abs(v) + 0.386595;
q = x * x + y * (0.19600 * y - 0.25472 * x);
} while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u));
return v / u;
};
// Returns a gamma deviate by the method of Marsaglia and Tsang.
jStat.randg = function randg(shape, n, m) {
var oalph = shape;
var a1, a2, u, v, x, mat;
if (!m)
m = n;
if (!shape)
shape = 1;
if (n) {
mat = jStat.zeros(n,m);
mat.alter(function() { return jStat.randg(shape); });
return mat;
}
if (shape < 1)
shape += 1;
a1 = shape - 1 / 3;
a2 = 1 / Math.sqrt(9 * a1);
do {
do {
x = jStat.randn();
v = 1 + a2 * x;
} while(v <= 0);
v = v * v * v;
u = Math.random();
} while(u > 1 - 0.331 * Math.pow(x, 4) &&
Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v)));
// alpha > 1
if (shape == oalph)
return a1 * v;
// alpha < 1
do {
u = Math.random();
} while(u === 0);
return Math.pow(u, 1 / oalph) * a1 * v;
};
// making use of static methods on the instance
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jStat.fn[passfunc] = function() {
return jStat(
jStat.map(this, function(value) { return jStat[passfunc](value); }));
}
})(funcs[i]);
})('gammaln gammafn factorial factorialln'.split(' '));
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jStat.fn[passfunc] = function() {
return jStat(jStat[passfunc].apply(null, arguments));
};
})(funcs[i]);
})('randn'.split(' '));
}(jStat, Math));
(function(jStat, Math) {
// generate all distribution instance methods
(function(list) {
for (var i = 0; i < list.length; i++) (function(func) {
// distribution instance method
jStat[func] = function(a, b, c) {
if (!(this instanceof arguments.callee))
return new arguments.callee(a, b, c);
this._a = a;
this._b = b;
this._c = c;
return this;
};
// distribution method to be used on a jStat instance
jStat.fn[func] = function(a, b, c) {
var newthis = jStat[func](a, b, c);
newthis.data = this;
return newthis;
};
// sample instance method
jStat[func].prototype.sample = function(arr) {
var a = this._a;
var b = this._b;
var c = this._c;
if (arr)
return jStat.alter(arr, function() {
return jStat[func].sample(a, b, c);
});
else
return jStat[func].sample(a, b, c);
};
// generate the pdf, cdf and inv instance methods
(function(vals) {
for (var i = 0; i < vals.length; i++) (function(fnfunc) {
jStat[func].prototype[fnfunc] = function(x) {
var a = this._a;
var b = this._b;
var c = this._c;
if (!x && x !== 0)
x = this.data;
if (typeof x !== 'number') {
return jStat.fn.map.call(x, function(x) {
return jStat[func][fnfunc](x, a, b, c);
});
}
return jStat[func][fnfunc](x, a, b, c);
};
})(vals[i]);
})('pdf cdf inv'.split(' '));
// generate the mean, median, mode and variance instance methods
(function(vals) {
for (var i = 0; i < vals.length; i++) (function(fnfunc) {
jStat[func].prototype[fnfunc] = function() {
return jStat[func][fnfunc](this._a, this._b, this._c);
};
})(vals[i]);
})('mean median mode variance'.split(' '));
})(list[i]);
})((
'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' +
'laplace lognormal noncentralt normal pareto studentt weibull uniform ' +
'binomial negbin hypgeom poisson triangular tukey arcsine'
).split(' '));
// extend beta function with static methods
jStat.extend(jStat.beta, {
pdf: function pdf(x, alpha, beta) {
// PDF is zero outside the support
if (x > 1 || x < 0)
return 0;
// PDF is one for the uniform case
if (alpha == 1 && beta == 1)
return 1;
if (alpha < 512 && beta < 512) {
return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) /
jStat.betafn(alpha, beta);
} else {
return Math.exp((alpha - 1) * Math.log(x) +
(beta - 1) * Math.log(1 - x) -
jStat.betaln(alpha, beta));
}
},
cdf: function cdf(x, alpha, beta) {
return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta);
},
inv: function inv(x, alpha, beta) {
return jStat.ibetainv(x, alpha, beta);
},
mean: function mean(alpha, beta) {
return alpha / (alpha + beta);
},
median: function median(alpha, beta) {
return jStat.ibetainv(0.5, alpha, beta);
},
mode: function mode(alpha, beta) {
return (alpha - 1 ) / ( alpha + beta - 2);
},
// return a random sample
sample: function sample(alpha, beta) {
var u = jStat.randg(alpha);
return u / (u + jStat.randg(beta));
},
variance: function variance(alpha, beta) {
return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1));
}
});
// extend F function with static methods
jStat.extend(jStat.centralF, {
// This implementation of the pdf function avoids float overflow
// See the way that R calculates this value:
// https://svn.r-project.org/R/trunk/src/nmath/df.c
pdf: function pdf(x, df1, df2) {
var p, q, f;
if (x < 0)
return 0;
if (df1 <= 2) {
if (x === 0 && df1 < 2) {
return Infinity;
}
if (x === 0 && df1 === 2) {
return 1;
}
return (1 / jStat.betafn(df1 / 2, df2 / 2)) *
Math.pow(df1 / df2, df1 / 2) *
Math.pow(x, (df1/2) - 1) *
Math.pow((1 + (df1 / df2) * x), -(df1 + df2) / 2);
}
p = (df1 * x) / (df2 + x * df1);
q = df2 / (df2 + x * df1);
f = df1 * q / 2.0;
return f * jStat.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p);
},
cdf: function cdf(x, df1, df2) {
if (x < 0)
return 0;
return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2);
},
inv: function inv(x, df1, df2) {
return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1));
},
mean: function mean(df1, df2) {
return (df2 > 2) ? df2 / (df2 - 2) : undefined;
},
mode: function mode(df1, df2) {
return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined;
},
// return a random sample
sample: function sample(df1, df2) {
var x1 = jStat.randg(df1 / 2) * 2;
var x2 = jStat.randg(df2 / 2) * 2;
return (x1 / df1) / (x2 / df2);
},
variance: function variance(df1, df2) {
if (df2 <= 4)
return undefined;
return 2 * df2 * df2 * (df1 + df2 - 2) /
(df1 * (df2 - 2) * (df2 - 2) * (df2 - 4));
}
});
// extend cauchy function with static methods
jStat.extend(jStat.cauchy, {
pdf: function pdf(x, local, scale) {
if (scale < 0) { return 0; }
return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI;
},
cdf: function cdf(x, local, scale) {
return Math.atan((x - local) / scale) / Math.PI + 0.5;
},
inv: function(p, local, scale) {
return local + scale * Math.tan(Math.PI * (p - 0.5));
},
median: function median(local, scale) {
return local;
},
mode: function mode(local, scale) {
return local;
},
sample: function sample(local, scale) {
return jStat.randn() *
Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local;
}
});
// extend chisquare function with static methods
jStat.extend(jStat.chisquare, {
pdf: function pdf(x, dof) {
if (x < 0)
return 0;
return (x === 0 && dof === 2) ? 0.5 :
Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) *
Math.log(2) - jStat.gammaln(dof / 2));
},
cdf: function cdf(x, dof) {
if (x < 0)
return 0;
return jStat.lowRegGamma(dof / 2, x / 2);
},
inv: function(p, dof) {
return 2 * jStat.gammapinv(p, 0.5 * dof);
},
mean : function(dof) {
return dof;
},
// TODO: this is an approximation (is there a better way?)
median: function median(dof) {
return dof * Math.pow(1 - (2 / (9 * dof)), 3);
},
mode: function mode(dof) {
return (dof - 2 > 0) ? dof - 2 : 0;
},
sample: function sample(dof) {
return jStat.randg(dof / 2) * 2;
},
variance: function variance(dof) {
return 2 * dof;
}
});
// extend exponential function with static methods
jStat.extend(jStat.exponential, {
pdf: function pdf(x, rate) {
return x < 0 ? 0 : rate * Math.exp(-rate * x);
},
cdf: function cdf(x, rate) {
return x < 0 ? 0 : 1 - Math.exp(-rate * x);
},
inv: function(p, rate) {
return -Math.log(1 - p) / rate;
},
mean : function(rate) {
return 1 / rate;
},
median: function (rate) {
return (1 / rate) * Math.log(2);
},
mode: function mode(rate) {
return 0;
},
sample: function sample(rate) {
return -1 / rate * Math.log(Math.random());
},
variance : function(rate) {
return Math.pow(rate, -2);
}
});
// extend gamma function with static methods
jStat.extend(jStat.gamma, {
pdf: function pdf(x, shape, scale) {
if (x < 0)
return 0;
return (x === 0 && shape === 1) ? 1 / scale :
Math.exp((shape - 1) * Math.log(x) - x / scale -
jStat.gammaln(shape) - shape * Math.log(scale));
},
cdf: function cdf(x, shape, scale) {
if (x < 0)
return 0;
return jStat.lowRegGamma(shape, x / scale);
},
inv: function(p, shape, scale) {
return jStat.gammapinv(p, shape) * scale;
},
mean : function(shape, scale) {
return shape * scale;
},
mode: function mode(shape, scale) {
if(shape > 1) return (shape - 1) * scale;
return undefined;
},
sample: function sample(shape, scale) {
return jStat.randg(shape) * scale;
},
variance: function variance(shape, scale) {
return shape * scale * scale;
}
});
// extend inverse gamma function with static methods
jStat.extend(jStat.invgamma, {
pdf: function pdf(x, shape, scale) {
if (x <= 0)
return 0;
return Math.exp(-(shape + 1) * Math.log(x) - scale / x -
jStat.gammaln(shape) + shape * Math.log(scale));
},
cdf: function cdf(x, shape, scale) {
if (x <= 0)
return 0;
return 1 - jStat.lowRegGamma(shape, scale / x);
},
inv: function(p, shape, scale) {
return scale / jStat.gammapinv(1 - p, shape);
},
mean : function(shape, scale) {
return (shape > 1) ? scale / (shape - 1) : undefined;
},
mode: function mode(shape, scale) {
return scale / (shape + 1);
},
sample: function sample(shape, scale) {
return scale / jStat.randg(shape);
},
variance: function variance(shape, scale) {
if (shape <= 2)
return undefined;
return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2));
}
});
// extend kumaraswamy function with static methods
jStat.extend(jStat.kumaraswamy, {
pdf: function pdf(x, alpha, beta) {
if (x === 0 && alpha === 1)
return beta;
else if (x === 1 && beta === 1)
return alpha;
return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) *
Math.log(x) + (beta - 1) *
Math.log(1 - Math.pow(x, alpha)));
},
cdf: function cdf(x, alpha, beta) {
if (x < 0)
return 0;
else if (x > 1)
return 1;
return (1 - Math.pow(1 - Math.pow(x, alpha), beta));
},
inv: function inv(p, alpha, beta) {
return Math.pow(1 - Math.pow(1 - p, 1 / beta), 1 / alpha);
},
mean : function(alpha, beta) {
return (beta * jStat.gammafn(1 + 1 / alpha) *
jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta));
},
median: function median(alpha, beta) {
return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha);
},
mode: function mode(alpha, beta) {
if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1)))
return undefined;
return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha);
},
variance: function variance(alpha, beta) {
throw new Error('variance not yet implemented');
// TODO: complete this
}
});
// extend lognormal function with static methods
jStat.extend(jStat.lognormal, {
pdf: function pdf(x, mu, sigma) {
if (x <= 0)
return 0;
return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) -
Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) /
(2 * sigma * sigma));
},
cdf: function cdf(x, mu, sigma) {
if (x < 0)
return 0;
return 0.5 +
(0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma)));
},
inv: function(p, mu, sigma) {
return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu);
},
mean: function mean(mu, sigma) {
return Math.exp(mu + sigma * sigma / 2);
},
median: function median(mu, sigma) {
return Math.exp(mu);
},
mode: function mode(mu, sigma) {
return Math.exp(mu - sigma * sigma);
},
sample: function sample(mu, sigma) {
return Math.exp(jStat.randn() * sigma + mu);
},
variance: function variance(mu, sigma) {
return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma);
}
});
// extend noncentralt function with static methods
jStat.extend(jStat.noncentralt, {
pdf: function pdf(x, dof, ncp) {
var tol = 1e-14;
if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
return jStat.studentt.pdf(x, dof)
if (Math.abs(x) < tol) { // different formula for x == 0
return Math.exp(jStat.gammaln((dof + 1) / 2) - ncp * ncp / 2 -
0.5 * Math.log(Math.PI * dof) - jStat.gammaln(dof / 2));
}
// formula for x != 0
return dof / x *
(jStat.noncentralt.cdf(x * Math.sqrt(1 + 2 / dof), dof+2, ncp) -
jStat.noncentralt.cdf(x, dof, ncp));
},
cdf: function cdf(x, dof, ncp) {
var tol = 1e-14;
var min_iterations = 200;
if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
return jStat.studentt.cdf(x, dof);
// turn negative x into positive and flip result afterwards
var flip = false;
if (x < 0) {
flip = true;
ncp = -ncp;
}
var prob = jStat.normal.cdf(-ncp, 0, 1);
var value = tol + 1;
// use value at last two steps to determine convergence
var lastvalue = value;
var y = x * x / (x * x + dof);
var j = 0;
var p = Math.exp(-ncp * ncp / 2);
var q = Math.exp(-ncp * ncp / 2 - 0.5 * Math.log(2) -
jStat.gammaln(3 / 2)) * ncp;
while (j < min_iterations || lastvalue > tol || value > tol) {
lastvalue = value;
if (j > 0) {
p *= (ncp * ncp) / (2 * j);
q *= (ncp * ncp) / (2 * (j + 1 / 2));
}
value = p * jStat.beta.cdf(y, j + 0.5, dof / 2) +
q * jStat.beta.cdf(y, j+1, dof/2);
prob += 0.5 * value;
j++;
}
return flip ? (1 - prob) : prob;
}
});
// extend normal function with static methods
jStat.extend(jStat.normal, {
pdf: function pdf(x, mean, std) {
return Math.exp(-0.5 * Math.log(2 * Math.PI) -
Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std));
},
cdf: function cdf(x, mean, std) {
return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std)));
},
inv: function(p, mean, std) {
return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean;
},
mean : function(mean, std) {
return mean;
},
median: function median(mean, std) {
return mean;
},
mode: function (mean, std) {
return mean;
},
sample: function sample(mean, std) {
return jStat.randn() * std + mean;
},
variance : function(mean, std) {
return std * std;
}
});
// extend pareto function with static methods
jStat.extend(jStat.pareto, {
pdf: function pdf(x, scale, shape) {
if (x < scale)
return 0;
return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1);
},
cdf: function cdf(x, scale, shape) {
if (x < scale)
return 0;
return 1 - Math.pow(scale / x, shape);
},
inv: function inv(p, scale, shape) {
return scale / Math.pow(1 - p, 1 / shape);
},
mean: function mean(scale, shape) {
if (shape <= 1)
return undefined;
return (shape * Math.pow(scale, shape)) / (shape - 1);
},
median: function median(scale, shape) {
return scale * (shape * Math.SQRT2);
},
mode: function mode(scale, shape) {
return scale;
},
variance : function(scale, shape) {
if (shape <= 2)
return undefined;
return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2));
}
});
// extend studentt function with static methods
jStat.extend(jStat.studentt, {
pdf: function pdf(x, dof) {
dof = dof > 1e100 ? 1e100 : dof;
return (1/(Math.sqrt(dof) * jStat.betafn(0.5, dof/2))) *
Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2));
},
cdf: function cdf(x, dof) {
var dof2 = dof / 2;
return jStat.ibeta((x + Math.sqrt(x * x + dof)) /
(2 * Math.sqrt(x * x + dof)), dof2, dof2);
},
inv: function(p, dof) {
var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);
x = Math.sqrt(dof * (1 - x) / x);
return (p > 0.5) ? x : -x;
},
mean: function mean(dof) {
return (dof > 1) ? 0 : undefined;
},
median: function median(dof) {
return 0;
},
mode: function mode(dof) {
return 0;
},
sample: function sample(dof) {
return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2)));
},
variance: function variance(dof) {
return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined;
}
});
// extend weibull function with static methods
jStat.extend(jStat.weibull, {
pdf: function pdf(x, scale, shape) {
if (x < 0 || scale < 0 || shape < 0)
return 0;
return (shape / scale) * Math.pow((x / scale), (shape - 1)) *
Math.exp(-(Math.pow((x / scale), shape)));
},
cdf: function cdf(x, scale, shape) {
return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape));
},
inv: function(p, scale, shape) {
return scale * Math.pow(-Math.log(1 - p), 1 / shape);
},
mean : function(scale, shape) {
return scale * jStat.gammafn(1 + 1 / shape);
},
median: function median(scale, shape) {
return scale * Math.pow(Math.log(2), 1 / shape);
},
mode: function mode(scale, shape) {
if (shape <= 1)
return 0;
return scale * Math.pow((shape - 1) / shape, 1 / shape);
},
sample: function sample(scale, shape) {
return scale * Math.pow(-Math.log(Math.random()), 1 / shape);
},
variance: function variance(scale, shape) {
return scale * scale * jStat.gammafn(1 + 2 / shape) -
Math.pow(jStat.weibull.mean(scale, shape), 2);
}
});
// extend uniform function with static methods
jStat.extend(jStat.uniform, {
pdf: function pdf(x, a, b) {
return (x < a || x > b) ? 0 : 1 / (b - a);
},
cdf: function cdf(x, a, b) {
if (x < a)
return 0;
else if (x < b)
return (x - a) / (b - a);
return 1;
},
inv: function(p, a, b) {
return a + (p * (b - a));
},
mean: function mean(a, b) {
return 0.5 * (a + b);
},
median: function median(a, b) {
return jStat.mean(a, b);
},
mode: function mode(a, b) {
throw new Error('mode is not yet implemented');
},
sample: function sample(a, b) {
return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * Math.random() - 1);
},
variance: function variance(a, b) {
return Math.pow(b - a, 2) / 12;
}
});
// extend uniform function with static methods
jStat.extend(jStat.binomial, {
pdf: function pdf(k, n, p) {
return (p === 0 || p === 1) ?
((n * p) === k ? 1 : 0) :
jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);
},
cdf: function cdf(x, n, p) {
var binomarr = [],
k = 0;
if (x < 0) {
return 0;
}
if (x < n) {
for (; k <= x; k++) {
binomarr[ k ] = jStat.binomial.pdf(k, n, p);
}
return jStat.sum(binomarr);
}
return 1;
}
});
// extend uniform function with static methods
jStat.extend(jStat.negbin, {
pdf: function pdf(k, r, p) {
if (k !== k >>> 0)
return false;
if (k < 0)
return 0;
return jStat.combination(k + r - 1, r - 1) *
Math.pow(1 - p, k) * Math.pow(p, r);
},
cdf: function cdf(x, r, p) {
var sum = 0,
k = 0;
if (x < 0) return 0;
for (; k <= x; k++) {
sum += jStat.negbin.pdf(k, r, p);
}
return sum;
}
});
// extend uniform function with static methods
jStat.extend(jStat.hypgeom, {
pdf: function pdf(k, N, m, n) {
// Hypergeometric PDF.
// A simplification of the CDF algorithm below.
// k = number of successes drawn
// N = population size
// m = number of successes in population
// n = number of items drawn from population
if(k !== k | 0) {
return false;
} else if(k < 0 || k < m - (N - n)) {
// It's impossible to have this few successes drawn.
return 0;
} else if(k > n || k > m) {
// It's impossible to have this many successes drawn.
return 0;
} else if (m * 2 > N) {
// More than half the population is successes.
if(n * 2 > N) {
// More than half the population is sampled.
return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n)
} else {
// Half or less of the population is sampled.
return jStat.hypgeom.pdf(n - k, N, N - m, n);
}
} else if(n * 2 > N) {
// Half or less is successes.
return jStat.hypgeom.pdf(m - k, N, m, N - n);
} else if(m < n) {
// We want to have the number of things sampled to be less than the
// successes available. So swap the definitions of successful and sampled.
return jStat.hypgeom.pdf(k, N, n, m);
} else {
// If we get here, half or less of the population was sampled, half or
// less of it was successes, and we had fewer sampled things than
// successes. Now we can do this complicated iterative algorithm in an
// efficient way.
// The basic premise of the algorithm is that we partially normalize our
// intermediate product to keep it in a numerically good region, and then
// finish the normalization at the end.
// This variable holds the scaled probability of the current number of
// successes.
var scaledPDF = 1;
// This keeps track of how much we have normalized.
var samplesDone = 0;
for(var i = 0; i < k; i++) {
// For every possible number of successes up to that observed...
while(scaledPDF > 1 && samplesDone < n) {
// Intermediate result is growing too big. Apply some of the
// normalization to shrink everything.
scaledPDF *= 1 - (m / (N - samplesDone));
// Say we've normalized by this sample already.
samplesDone++;
}
// Work out the partially-normalized hypergeometric PDF for the next
// number of successes
scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
}
for(; samplesDone < n; samplesDone++) {
// Apply all the rest of the normalization
scaledPDF *= 1 - (m / (N - samplesDone));
}
// Bound answer sanely before returning.
return Math.min(1, Math.max(0, scaledPDF));
}
},
cdf: function cdf(x, N, m, n) {
// Hypergeometric CDF.
// This algorithm is due to Prof. Thomas S. Ferguson, ,
// and comes from his hypergeometric test calculator at
// .
// x = number of successes drawn
// N = population size
// m = number of successes in population
// n = number of items drawn from population
if(x < 0 || x < m - (N - n)) {
// It's impossible to have this few successes drawn or fewer.
return 0;
} else if(x >= n || x >= m) {
// We will always have this many successes or fewer.
return 1;
} else if (m * 2 > N) {
// More than half the population is successes.
if(n * 2 > N) {
// More than half the population is sampled.
return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n)
} else {
// Half or less of the population is sampled.
return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n);
}
} else if(n * 2 > N) {
// Half or less is successes.
return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n);
} else if(m < n) {
// We want to have the number of things sampled to be less than the
// successes available. So swap the definitions of successful and sampled.
return jStat.hypgeom.cdf(x, N, n, m);
} else {
// If we get here, half or less of the population was sampled, half or
// less of it was successes, and we had fewer sampled things than
// successes. Now we can do this complicated iterative algorithm in an
// efficient way.
// The basic premise of the algorithm is that we partially normalize our
// intermediate sum to keep it in a numerically good region, and then
// finish the normalization at the end.
// Holds the intermediate, scaled total CDF.
var scaledCDF = 1;
// This variable holds the scaled probability of the current number of
// successes.
var scaledPDF = 1;
// This keeps track of how much we have normalized.
var samplesDone = 0;
for(var i = 0; i < x; i++) {
// For every possible number of successes up to that observed...
while(scaledCDF > 1 && samplesDone < n) {
// Intermediate result is growing too big. Apply some of the
// normalization to shrink everything.
var factor = 1 - (m / (N - samplesDone));
scaledPDF *= factor;
scaledCDF *= factor;
// Say we've normalized by this sample already.
samplesDone++;
}
// Work out the partially-normalized hypergeometric PDF for the next
// number of successes
scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
// Add to the CDF answer.
scaledCDF += scaledPDF;
}
for(; samplesDone < n; samplesDone++) {
// Apply all the rest of the normalization
scaledCDF *= 1 - (m / (N - samplesDone));
}
// Bound answer sanely before returning.
return Math.min(1, Math.max(0, scaledCDF));
}
}
});
// extend uniform function with static methods
jStat.extend(jStat.poisson, {
pdf: function pdf(k, l) {
if (l < 0 || (k % 1) !== 0 || k < 0) {
return 0;
}
return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k);
},
cdf: function cdf(x, l) {
var sumarr = [],
k = 0;
if (x < 0) return 0;
for (; k <= x; k++) {
sumarr.push(jStat.poisson.pdf(k, l));
}
return jStat.sum(sumarr);
},
mean : function(l) {
return l;
},
variance : function(l) {
return l;
},
sample: function sample(l) {
var p = 1, k = 0, L = Math.exp(-l);
do {
k++;
p *= Math.random();
} while (p > L);
return k - 1;
}
});
// extend triangular function with static methods
jStat.extend(jStat.triangular, {
pdf: function pdf(x, a, b, c) {
if (b <= a || c < a || c > b) {
return NaN;
} else {
if (x < a || x > b) {
return 0;
} else if (x < c) {
return (2 * (x - a)) / ((b - a) * (c - a));
} else if (x === c) {
return (2 / (b - a));
} else { // x > c
return (2 * (b - x)) / ((b - a) * (b - c));
}
}
},
cdf: function cdf(x, a, b, c) {
if (b <= a || c < a || c > b)
return NaN;
if (x <= a)
return 0;
else if (x >= b)
return 1;
if (x <= c)
return Math.pow(x - a, 2) / ((b - a) * (c - a));
else // x > c
return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c));
},
inv: function inv(p, a, b, c) {
if (b <= a || c < a || c > b) {
return NaN;
} else {
if (p <= ((c - a) / (b - a))) {
return a + (b - a) * Math.sqrt(p * ((c - a) / (b - a)));
} else { // p > ((c - a) / (b - a))
return a + (b - a) * (1 - Math.sqrt((1 - p) * (1 - ((c - a) / (b - a)))));
}
}
},
mean: function mean(a, b, c) {
return (a + b + c) / 3;
},
median: function median(a, b, c) {
if (c <= (a + b) / 2) {
return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2);
} else if (c > (a + b) / 2) {
return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2);
}
},
mode: function mode(a, b, c) {
return c;
},
sample: function sample(a, b, c) {
var u = Math.random();
if (u < ((c - a) / (b - a)))
return a + Math.sqrt(u * (b - a) * (c - a))
return b - Math.sqrt((1 - u) * (b - a) * (b - c));
},
variance: function variance(a, b, c) {
return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
}
});
// extend arcsine function with static methods
jStat.extend(jStat.arcsine, {
pdf: function pdf(x, a, b) {
if (b <= a) return NaN;
return (x <= a || x >= b) ? 0 :
(2 / Math.PI) *
Math.pow(Math.pow(b - a, 2) -
Math.pow(2 * x - a - b, 2), -0.5);
},
cdf: function cdf(x, a, b) {
if (x < a)
return 0;
else if (x < b)
return (2 / Math.PI) * Math.asin(Math.sqrt((x - a)/(b - a)));
return 1;
},
inv: function(p, a, b) {
return a + (0.5 - 0.5 * Math.cos(Math.PI * p)) * (b - a);
},
mean: function mean(a, b) {
if (b <= a) return NaN;
return (a + b) / 2;
},
median: function median(a, b) {
if (b <= a) return NaN;
return (a + b) / 2;
},
mode: function mode(a, b) {
throw new Error('mode is not yet implemented');
},
sample: function sample(a, b) {
return ((a + b) / 2) + ((b - a) / 2) *
Math.sin(2 * Math.PI * jStat.uniform.sample(0, 1));
},
variance: function variance(a, b) {
if (b <= a) return NaN;
return Math.pow(b - a, 2) / 8;
}
});
function laplaceSign(x) { return x / Math.abs(x); }
jStat.extend(jStat.laplace, {
pdf: function pdf(x, mu, b) {
return (b <= 0) ? 0 : (Math.exp(-Math.abs(x - mu) / b)) / (2 * b);
},
cdf: function cdf(x, mu, b) {
if (b <= 0) { return 0; }
if(x < mu) {
return 0.5 * Math.exp((x - mu) / b);
} else {
return 1 - 0.5 * Math.exp(- (x - mu) / b);
}
},
mean: function(mu, b) {
return mu;
},
median: function(mu, b) {
return mu;
},
mode: function(mu, b) {
return mu;
},
variance: function(mu, b) {
return 2 * b * b;
},
sample: function sample(mu, b) {
var u = Math.random() - 0.5;
return mu - (b * laplaceSign(u) * Math.log(1 - (2 * Math.abs(u))));
}
});
function tukeyWprob(w, rr, cc) {
var nleg = 12;
var ihalf = 6;
var C1 = -30;
var C2 = -50;
var C3 = 60;
var bb = 8;
var wlar = 3;
var wincr1 = 2;
var wincr2 = 3;
var xleg = [
0.981560634246719250690549090149,
0.904117256370474856678465866119,
0.769902674194304687036893833213,
0.587317954286617447296702418941,
0.367831498998180193752691536644,
0.125233408511468915472441369464
];
var aleg = [
0.047175336386511827194615961485,
0.106939325995318430960254718194,
0.160078328543346226334652529543,
0.203167426723065921749064455810,
0.233492536538354808760849898925,
0.249147045813402785000562436043
];
var qsqz = w * 0.5;
// if w >= 16 then the integral lower bound (occurs for c=20)
// is 0.99999999999995 so return a value of 1.
if (qsqz >= bb)
return 1.0;
// find (f(w/2) - 1) ^ cc
// (first term in integral of hartley's form).
var pr_w = 2 * jStat.normal.cdf(qsqz, 0, 1, 1, 0) - 1; // erf(qsqz / M_SQRT2)
// if pr_w ^ cc < 2e-22 then set pr_w = 0
if (pr_w >= Math.exp(C2 / cc))
pr_w = Math.pow(pr_w, cc);
else
pr_w = 0.0;
// if w is large then the second component of the
// integral is small, so fewer intervals are needed.
var wincr;
if (w > wlar)
wincr = wincr1;
else
wincr = wincr2;
// find the integral of second term of hartley's form
// for the integral of the range for equal-length
// intervals using legendre quadrature. limits of
// integration are from (w/2, 8). two or three
// equal-length intervals are used.
// blb and bub are lower and upper limits of integration.
var blb = qsqz;
var binc = (bb - qsqz) / wincr;
var bub = blb + binc;
var einsum = 0.0;
// integrate over each interval
var cc1 = cc - 1.0;
for (var wi = 1; wi <= wincr; wi++) {
var elsum = 0.0;
var a = 0.5 * (bub + blb);
// legendre quadrature with order = nleg
var b = 0.5 * (bub - blb);
for (var jj = 1; jj <= nleg; jj++) {
var j, xx;
if (ihalf < jj) {
j = (nleg - jj) + 1;
xx = xleg[j-1];
} else {
j = jj;
xx = -xleg[j-1];
}
var c = b * xx;
var ac = a + c;
// if exp(-qexpo/2) < 9e-14,
// then doesn't contribute to integral
var qexpo = ac * ac;
if (qexpo > C3)
break;
var pplus = 2 * jStat.normal.cdf(ac, 0, 1, 1, 0);
var pminus= 2 * jStat.normal.cdf(ac, w, 1, 1, 0);
// if rinsum ^ (cc-1) < 9e-14,
// then doesn't contribute to integral
var rinsum = (pplus * 0.5) - (pminus * 0.5);
if (rinsum >= Math.exp(C1 / cc1)) {
rinsum = (aleg[j-1] * Math.exp(-(0.5 * qexpo))) * Math.pow(rinsum, cc1);
elsum += rinsum;
}
}
elsum *= (((2.0 * b) * cc) / Math.sqrt(2 * Math.PI));
einsum += elsum;
blb = bub;
bub += binc;
}
// if pr_w ^ rr < 9e-14, then return 0
pr_w += einsum;
if (pr_w <= Math.exp(C1 / rr))
return 0;
pr_w = Math.pow(pr_w, rr);
if (pr_w >= 1) // 1 was iMax was eps
return 1;
return pr_w;
}
function tukeyQinv(p, c, v) {
var p0 = 0.322232421088;
var q0 = 0.993484626060e-01;
var p1 = -1.0;
var q1 = 0.588581570495;
var p2 = -0.342242088547;
var q2 = 0.531103462366;
var p3 = -0.204231210125;
var q3 = 0.103537752850;
var p4 = -0.453642210148e-04;
var q4 = 0.38560700634e-02;
var c1 = 0.8832;
var c2 = 0.2368;
var c3 = 1.214;
var c4 = 1.208;
var c5 = 1.4142;
var vmax = 120.0;
var ps = 0.5 - 0.5 * p;
var yi = Math.sqrt(Math.log(1.0 / (ps * ps)));
var t = yi + (((( yi * p4 + p3) * yi + p2) * yi + p1) * yi + p0)
/ (((( yi * q4 + q3) * yi + q2) * yi + q1) * yi + q0);
if (v < vmax) t += (t * t * t + t) / v / 4.0;
var q = c1 - c2 * t;
if (v < vmax) q += -c3 / v + c4 * t / v;
return t * (q * Math.log(c - 1.0) + c5);
}
jStat.extend(jStat.tukey, {
cdf: function cdf(q, nmeans, df) {
// Identical implementation as the R ptukey() function as of commit 68947
var rr = 1;
var cc = nmeans;
var nlegq = 16;
var ihalfq = 8;
var eps1 = -30.0;
var eps2 = 1.0e-14;
var dhaf = 100.0;
var dquar = 800.0;
var deigh = 5000.0;
var dlarg = 25000.0;
var ulen1 = 1.0;
var ulen2 = 0.5;
var ulen3 = 0.25;
var ulen4 = 0.125;
var xlegq = [
0.989400934991649932596154173450,
0.944575023073232576077988415535,
0.865631202387831743880467897712,
0.755404408355003033895101194847,
0.617876244402643748446671764049,
0.458016777657227386342419442984,
0.281603550779258913230460501460,
0.950125098376374401853193354250e-1
];
var alegq = [
0.271524594117540948517805724560e-1,
0.622535239386478928628438369944e-1,
0.951585116824927848099251076022e-1,
0.124628971255533872052476282192,
0.149595988816576732081501730547,
0.169156519395002538189312079030,
0.182603415044923588866763667969,
0.189450610455068496285396723208
];
if (q <= 0)
return 0;
// df must be > 1
// there must be at least two values
if (df < 2 || rr < 1 || cc < 2) return NaN;
if (!Number.isFinite(q))
return 1;
if (df > dlarg)
return tukeyWprob(q, rr, cc);
// calculate leading constant
var f2 = df * 0.5;
var f2lf = ((f2 * Math.log(df)) - (df * Math.log(2))) - jStat.gammaln(f2);
var f21 = f2 - 1.0;
// integral is divided into unit, half-unit, quarter-unit, or
// eighth-unit length intervals depending on the value of the
// degrees of freedom.
var ff4 = df * 0.25;
var ulen;
if (df <= dhaf) ulen = ulen1;
else if (df <= dquar) ulen = ulen2;
else if (df <= deigh) ulen = ulen3;
else ulen = ulen4;
f2lf += Math.log(ulen);
// integrate over each subinterval
var ans = 0.0;
for (var i = 1; i <= 50; i++) {
var otsum = 0.0;
// legendre quadrature with order = nlegq
// nodes (stored in xlegq) are symmetric around zero.
var twa1 = (2 * i - 1) * ulen;
for (var jj = 1; jj <= nlegq; jj++) {
var j, t1;
if (ihalfq < jj) {
j = jj - ihalfq - 1;
t1 = (f2lf + (f21 * Math.log(twa1 + (xlegq[j] * ulen))))
- (((xlegq[j] * ulen) + twa1) * ff4);
} else {
j = jj - 1;
t1 = (f2lf + (f21 * Math.log(twa1 - (xlegq[j] * ulen))))
+ (((xlegq[j] * ulen) - twa1) * ff4);
}
// if exp(t1) < 9e-14, then doesn't contribute to integral
var qsqz;
if (t1 >= eps1) {
if (ihalfq < jj) {
qsqz = q * Math.sqrt(((xlegq[j] * ulen) + twa1) * 0.5);
} else {
qsqz = q * Math.sqrt(((-(xlegq[j] * ulen)) + twa1) * 0.5);
}
// call wprob to find integral of range portion
var wprb = tukeyWprob(qsqz, rr, cc);
var rotsum = (wprb * alegq[j]) * Math.exp(t1);
otsum += rotsum;
}
// end legendre integral for interval i
// L200:
}
// if integral for interval i < 1e-14, then stop.
// However, in order to avoid small area under left tail,
// at least 1 / ulen intervals are calculated.
if (i * ulen >= 1.0 && otsum <= eps2)
break;
// end of interval i
// L330:
ans += otsum;
}
if (otsum > eps2) { // not converged
throw new Error('tukey.cdf failed to converge');
}
if (ans > 1)
ans = 1;
return ans;
},
inv: function(p, nmeans, df) {
// Identical implementation as the R qtukey() function as of commit 68947
var rr = 1;
var cc = nmeans;
var eps = 0.0001;
var maxiter = 50;
// df must be > 1 ; there must be at least two values
if (df < 2 || rr < 1 || cc < 2) return NaN;
if (p < 0 || p > 1) return NaN;
if (p === 0) return 0;
if (p === 1) return Infinity;
// Initial value
var x0 = tukeyQinv(p, cc, df);
// Find prob(value < x0)
var valx0 = jStat.tukey.cdf(x0, nmeans, df) - p;
// Find the second iterate and prob(value < x1).
// If the first iterate has probability value
// exceeding p then second iterate is 1 less than
// first iterate; otherwise it is 1 greater.
var x1;
if (valx0 > 0.0)
x1 = Math.max(0.0, x0 - 1.0);
else
x1 = x0 + 1.0;
var valx1 = jStat.tukey.cdf(x1, nmeans, df) - p;
// Find new iterate
var ans;
for(var iter = 1; iter < maxiter; iter++) {
ans = x1 - ((valx1 * (x1 - x0)) / (valx1 - valx0));
valx0 = valx1;
// New iterate must be >= 0
x0 = x1;
if (ans < 0.0) {
ans = 0.0;
valx1 = -p;
}
// Find prob(value < new iterate)
valx1 = jStat.tukey.cdf(ans, nmeans, df) - p;
x1 = ans;
// If the difference between two successive
// iterates is less than eps, stop
var xabs = Math.abs(x1 - x0);
if (xabs < eps)
return ans;
}
throw new Error('tukey.inv failed to converge');
}
});
}(jStat, Math));
/* Provides functions for the solution of linear system of equations, integration, extrapolation,
* interpolation, eigenvalue problems, differential equations and PCA analysis. */
(function(jStat, Math) {
var push = Array.prototype.push;
var isArray = jStat.utils.isArray;
function isUsable(arg) {
return isArray(arg) || arg instanceof jStat;
}
jStat.extend({
// add a vector/matrix to a vector/matrix or scalar
add: function add(arr, arg) {
// check if arg is a vector or scalar
if (isUsable(arg)) {
if (!isUsable(arg[0])) arg = [ arg ];
return jStat.map(arr, function(value, row, col) {
return value + arg[row][col];
});
}
return jStat.map(arr, function(value) { return value + arg; });
},
// subtract a vector or scalar from the vector
subtract: function subtract(arr, arg) {
// check if arg is a vector or scalar
if (isUsable(arg)) {
if (!isUsable(arg[0])) arg = [ arg ];
return jStat.map(arr, function(value, row, col) {
return value - arg[row][col] || 0;
});
}
return jStat.map(arr, function(value) { return value - arg; });
},
// matrix division
divide: function divide(arr, arg) {
if (isUsable(arg)) {
if (!isUsable(arg[0])) arg = [ arg ];
return jStat.multiply(arr, jStat.inv(arg));
}
return jStat.map(arr, function(value) { return value / arg; });
},
// matrix multiplication
multiply: function multiply(arr, arg) {
var row, col, nrescols, sum, nrow, ncol, res, rescols;
// eg: arr = 2 arg = 3 -> 6 for res[0][0] statement closure
if (arr.length === undefined && arg.length === undefined) {
return arr * arg;
}
nrow = arr.length,
ncol = arr[0].length,
res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol),
rescols = 0;
if (isUsable(arg)) {
for (; rescols < nrescols; rescols++) {
for (row = 0; row < nrow; row++) {
sum = 0;
for (col = 0; col < ncol; col++)
sum += arr[row][col] * arg[col][rescols];
res[row][rescols] = sum;
}
}
return (nrow === 1 && rescols === 1) ? res[0][0] : res;
}
return jStat.map(arr, function(value) { return value * arg; });
},
// outer([1,2,3],[4,5,6])
// ===
// [[1],[2],[3]] times [[4,5,6]]
// ->
// [[4,5,6],[8,10,12],[12,15,18]]
outer:function outer(A, B) {
return jStat.multiply(A.map(function(t){ return [t] }), [B]);
},
// Returns the dot product of two matricies
dot: function dot(arr, arg) {
if (!isUsable(arr[0])) arr = [ arr ];
if (!isUsable(arg[0])) arg = [ arg ];
// convert column to row vector
var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,
right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,
res = [],
row = 0,
nrow = left.length,
ncol = left[0].length,
sum, col;
for (; row < nrow; row++) {
res[row] = [];
sum = 0;
for (col = 0; col < ncol; col++)
sum += left[row][col] * right[row][col];
res[row] = sum;
}
return (res.length === 1) ? res[0] : res;
},
// raise every element by a scalar
pow: function pow(arr, arg) {
return jStat.map(arr, function(value) { return Math.pow(value, arg); });
},
// exponentiate every element
exp: function exp(arr) {
return jStat.map(arr, function(value) { return Math.exp(value); });
},
// generate the natural log of every element
log: function exp(arr) {
return jStat.map(arr, function(value) { return Math.log(value); });
},
// generate the absolute values of the vector
abs: function abs(arr) {
return jStat.map(arr, function(value) { return Math.abs(value); });
},
// computes the p-norm of the vector
// In the case that a matrix is passed, uses the first row as the vector
norm: function norm(arr, p) {
var nnorm = 0,
i = 0;
// check the p-value of the norm, and set for most common case
if (isNaN(p)) p = 2;
// check if multi-dimensional array, and make vector correction
if (isUsable(arr[0])) arr = arr[0];
// vector norm
for (; i < arr.length; i++) {
nnorm += Math.pow(Math.abs(arr[i]), p);
}
return Math.pow(nnorm, 1 / p);
},
// computes the angle between two vectors in rads
// In case a matrix is passed, this uses the first row as the vector
angle: function angle(arr, arg) {
return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg)));
},
// augment one matrix by another
// Note: this function returns a matrix, not a jStat object
aug: function aug(a, b) {
var newarr = [];
for (var i = 0; i < a.length; i++) {
newarr.push(a[i].slice());
}
for (var i = 0; i < newarr.length; i++) {
push.apply(newarr[i], b[i]);
}
return newarr;
},
// The inv() function calculates the inverse of a matrix
// Create the inverse by augmenting the matrix by the identity matrix of the
// appropriate size, and then use G-J elimination on the augmented matrix.
inv: function inv(a) {
var rows = a.length;
var cols = a[0].length;
var b = jStat.identity(rows, cols);
var c = jStat.gauss_jordan(a, b);
var result = [];
var i = 0;
var j;
//We need to copy the inverse portion to a new matrix to rid G-J artifacts
for (; i < rows; i++) {
result[i] = [];
for (j = cols; j < c[0].length; j++)
result[i][j - cols] = c[i][j];
}
return result;
},
// calculate the determinant of a matrix
det: function det(a) {
var alen = a.length,
alend = alen * 2,
vals = new Array(alend),
rowshift = alen - 1,
colshift = alend - 1,
mrow = rowshift - alen + 1,
mcol = colshift,
i = 0,
result = 0,
j;
// check for special 2x2 case
if (alen === 2) {
return a[0][0] * a[1][1] - a[0][1] * a[1][0];
}
for (; i < alend; i++) {
vals[i] = 1;
}
for (var i = 0; i < alen; i++) {
for (j = 0; j < alen; j++) {
vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j];
vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j];
mrow++;
mcol--;
}
mrow = --rowshift - alen + 1;
mcol = --colshift;
}
for (var i = 0; i < alen; i++) {
result += vals[i];
}
for (; i < alend; i++) {
result -= vals[i];
}
return result;
},
gauss_elimination: function gauss_elimination(a, b) {
var i = 0,
j = 0,
n = a.length,
m = a[0].length,
factor = 1,
sum = 0,
x = [],
maug, pivot, temp, k;
a = jStat.aug(a, b);
maug = a[0].length;
for(var i = 0; i < n; i++) {
pivot = a[i][i];
j = i;
for (k = i + 1; k < m; k++) {
if (pivot < Math.abs(a[k][i])) {
pivot = a[k][i];
j = k;
}
}
if (j != i) {
for(k = 0; k < maug; k++) {
temp = a[i][k];
a[i][k] = a[j][k];
a[j][k] = temp;
}
}
for (j = i + 1; j < n; j++) {
factor = a[j][i] / a[i][i];
for(k = i; k < maug; k++) {
a[j][k] = a[j][k] - factor * a[i][k];
}
}
}
for (var i = n - 1; i >= 0; i--) {
sum = 0;
for (j = i + 1; j<= n - 1; j++) {
sum = sum + x[j] * a[i][j];
}
x[i] =(a[i][maug - 1] - sum) / a[i][i];
}
return x;
},
gauss_jordan: function gauss_jordan(a, b) {
var m = jStat.aug(a, b),
h = m.length,
w = m[0].length;
var c = 0;
// find max pivot
for (var y = 0; y < h; y++) {
var maxrow = y;
for (var y2 = y+1; y2 < h; y2++) {
if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y]))
maxrow = y2;
}
var tmp = m[y];
m[y] = m[maxrow];
m[maxrow] = tmp
for (var y2 = y+1; y2 < h; y2++) {
c = m[y2][y] / m[y][y];
for (var x = y; x < w; x++) {
m[y2][x] -= m[y][x] * c;
}
}
}
// backsubstitute
for (var y = h-1; y >= 0; y--) {
c = m[y][y];
for (var y2 = 0; y2 < y; y2++) {
for (var x = w-1; x > y-1; x--) {
m[y2][x] -= m[y][x] * m[y2][y] / c;
}
}
m[y][y] /= c;
for (var x = h; x < w; x++) {
m[y][x] /= c;
}
}
return m;
},
// solve equation
// Ax=b
// A is upper triangular matrix
// A=[[1,2,3],[0,4,5],[0,6,7]]
// b=[1,2,3]
// triaUpSolve(A,b) // -> [2.666,0.1666,1.666]
// if you use matrix style
// A=[[1,2,3],[0,4,5],[0,6,7]]
// b=[[1],[2],[3]]
// will return [[2.666],[0.1666],[1.666]]
triaUpSolve: function triaUpSolve(A, b) {
var size = A[0].length;
var x = jStat.zeros(1, size)[0];
var parts;
var matrix_mode = false;
if (b[0].length != undefined) {
b = b.map(function(i){ return i[0] });
matrix_mode = true;
}
jStat.arange(size - 1, -1, -1).forEach(function(i) {
parts = jStat.arange(i + 1, size).map(function(j) {
return x[j] * A[i][j];
});
x[i] = (b[i] - jStat.sum(parts)) / A[i][i];
});
if (matrix_mode)
return x.map(function(i){ return [i] });
return x;
},
triaLowSolve: function triaLowSolve(A, b) {
// like to triaUpSolve but A is lower triangular matrix
var size = A[0].length;
var x = jStat.zeros(1, size)[0];
var parts;
var matrix_mode=false;
if (b[0].length != undefined) {
b = b.map(function(i){ return i[0] });
matrix_mode = true;
}
jStat.arange(size).forEach(function(i) {
parts = jStat.arange(i).map(function(j) {
return A[i][j] * x[j];
});
x[i] = (b[i] - jStat.sum(parts)) / A[i][i];
})
if (matrix_mode)
return x.map(function(i){ return [i] });
return x;
},
// A -> [L,U]
// A=LU
// L is lower triangular matrix
// U is upper triangular matrix
lu: function lu(A) {
var size = A.length;
//var L=jStat.diagonal(jStat.ones(1,size)[0]);
var L = jStat.identity(size);
var R = jStat.zeros(A.length, A[0].length);
var parts;
jStat.arange(size).forEach(function(t) {
R[0][t] = A[0][t];
});
jStat.arange(1, size).forEach(function(l) {
jStat.arange(l).forEach(function(i) {
parts = jStat.arange(i).map(function(jj) {
return L[l][jj] * R[jj][i];
});
L[l][i] = (A[l][i] - jStat.sum(parts)) / R[i][i];
});
jStat.arange(l, size).forEach(function(j) {
parts = jStat.arange(l).map(function(jj) {
return L[l][jj] * R[jj][j];
});
R[l][j] = A[i][j] - jStat.sum(parts);
});
});
return [L, R];
},
// A -> T
// A=TT'
// T is lower triangular matrix
cholesky: function cholesky(A) {
var size = A.length;
var T = jStat.zeros(A.length, A[0].length);
var parts;
jStat.arange(size).forEach(function(i) {
parts = jStat.arange(i).map(function(t) {
return Math.pow(T[i][t],2);
});
T[i][i] = Math.sqrt(A[i][i] - jStat.sum(parts));
jStat.arange(i + 1, size).forEach(function(j) {
parts = jStat.arange(i).map(function(t) {
return T[i][t] * T[j][t];
});
T[j][i] = (A[i][j] - jStat.sum(parts)) / T[i][i];
});
});
return T;
},
gauss_jacobi: function gauss_jacobi(a, b, x, r) {
var i = 0;
var j = 0;
var n = a.length;
var l = [];
var u = [];
var d = [];
var xv, c, h, xk;
for (; i < n; i++) {
l[i] = [];
u[i] = [];
d[i] = [];
for (j = 0; j < n; j++) {
if (i > j) {
l[i][j] = a[i][j];
u[i][j] = d[i][j] = 0;
} else if (i < j) {
u[i][j] = a[i][j];
l[i][j] = d[i][j] = 0;
} else {
d[i][j] = a[i][j];
l[i][j] = u[i][j] = 0;
}
}
}
h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1);
c = jStat.multiply(jStat.inv(d), b);
xv = x;
xk = jStat.add(jStat.multiply(h, x), c);
i = 2;
while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) {
xv = xk;
xk = jStat.add(jStat.multiply(h, xv), c);
i++;
}
return xk;
},
gauss_seidel: function gauss_seidel(a, b, x, r) {
var i = 0;
var n = a.length;
var l = [];
var u = [];
var d = [];
var j, xv, c, h, xk;
for (; i < n; i++) {
l[i] = [];
u[i] = [];
d[i] = [];
for (j = 0; j < n; j++) {
if (i > j) {
l[i][j] = a[i][j];
u[i][j] = d[i][j] = 0;
} else if (i < j) {
u[i][j] = a[i][j];
l[i][j] = d[i][j] = 0;
} else {
d[i][j] = a[i][j];
l[i][j] = u[i][j] = 0;
}
}
}
h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1);
c = jStat.multiply(jStat.inv(jStat.add(d, l)), b);
xv = x;
xk = jStat.add(jStat.multiply(h, x), c);
i = 2;
while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
xv = xk;
xk = jStat.add(jStat.multiply(h, xv), c);
i = i + 1;
}
return xk;
},
SOR: function SOR(a, b, x, r, w) {
var i = 0;
var n = a.length;
var l = [];
var u = [];
var d = [];
var j, xv, c, h, xk;
for (; i < n; i++) {
l[i] = [];
u[i] = [];
d[i] = [];
for (j = 0; j < n; j++) {
if (i > j) {
l[i][j] = a[i][j];
u[i][j] = d[i][j] = 0;
} else if (i < j) {
u[i][j] = a[i][j];
l[i][j] = d[i][j] = 0;
} else {
d[i][j] = a[i][j];
l[i][j] = u[i][j] = 0;
}
}
}
h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))),
jStat.subtract(jStat.multiply(d, 1 - w),
jStat.multiply(u, w)));
c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d,
jStat.multiply(l, w))), b), w);
xv = x;
xk = jStat.add(jStat.multiply(h, x), c);
i = 2;
while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
xv = xk;
xk = jStat.add(jStat.multiply(h, xv), c);
i++;
}
return xk;
},
householder: function householder(a) {
var m = a.length;
var n = a[0].length;
var i = 0;
var w = [];
var p = [];
var alpha, r, k, j, factor;
for (; i < m - 1; i++) {
alpha = 0;
for (j = i + 1; j < n; j++)
alpha += (a[j][i] * a[j][i]);
factor = (a[i + 1][i] > 0) ? -1 : 1;
alpha = factor * Math.sqrt(alpha);
r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));
w = jStat.zeros(m, 1);
w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r);
p = jStat.subtract(jStat.identity(m, n),
jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));
a = jStat.multiply(p, jStat.multiply(a, p));
}
return a;
},
// A -> [Q,R]
// Q is orthogonal matrix
// R is upper triangular
QR: (function() {
// x -> Q
// find a orthogonal matrix Q st.
// Qx=y
// y is [||x||,0,0,...]
// quick ref
var sum = jStat.sum;
var range = jStat.arange;
function get_Q1(x) {
var size = x.length;
var norm_x = jStat.norm(x, 2);
var e1 = jStat.zeros(1, size)[0];
e1[0] = 1;
var u = jStat.add(jStat.multiply(jStat.multiply(e1, norm_x), -1), x);
var norm_u = jStat.norm(u, 2);
var v = jStat.divide(u, norm_u);
var Q = jStat.subtract(jStat.identity(size),
jStat.multiply(jStat.outer(v, v), 2));
return Q;
}
function qr(A) {
var size = A[0].length;
var QList = [];
jStat.arange(size).forEach(function(i) {
var x = jStat.slice(A, { row: { start: i }, col: i });
var Q = get_Q1(x);
var Qn = jStat.identity(A.length);
Qn = jStat.sliceAssign(Qn, { row: { start: i }, col: { start: i }}, Q);
A = jStat.multiply(Qn, A);
QList.push(Qn);
});
var Q = QList.reduce(function(x, y){ return jStat.multiply(x,y) });
var R = A;
return [Q, R];
}
function qr2(x) {
// quick impletation
// https://www.stat.wisc.edu/~larget/math496/qr.html
var n = x.length;
var p = x[0].length;
x = jStat.copy(x);
r = jStat.zeros(p, p);
var i,j,k;
for(j = 0; j < p; j++){
r[j][j] = Math.sqrt(sum(range(n).map(function(i){
return x[i][j] * x[i][j];
})));
for(i = 0; i < n; i++){
x[i][j] = x[i][j] / r[j][j];
}
for(k = j+1; k < p; k++){
r[j][k] = sum(range(n).map(function(i){
return x[i][j] * x[i][k];
}));
for(i = 0; i < n; i++){
x[i][k] = x[i][k] - x[i][j]*r[j][k];
}
}
}
return [x, r];
}
return qr2;
}()),
lstsq: (function(A, b) {
// solve least squard problem for Ax=b as QR decomposition way if b is
// [[b1],[b2],[b3]] form will return [[x1],[x2],[x3]] array form solution
// else b is [b1,b2,b3] form will return [x1,x2,x3] array form solution
function R_I(A) {
A = jStat.copy(A);
var size = A.length;
var I = jStat.identity(size);
jStat.arange(size - 1, -1, -1).forEach(function(i) {
jStat.sliceAssign(
I, { row: i }, jStat.divide(jStat.slice(I, { row: i }), A[i][i]));
jStat.sliceAssign(
A, { row: i }, jStat.divide(jStat.slice(A, { row: i }), A[i][i]));
jStat.arange(i).forEach(function(j) {
var c = jStat.multiply(A[j][i], -1);
var Aj = jStat.slice(A, { row: j });
var cAi = jStat.multiply(jStat.slice(A, { row: i }), c);
jStat.sliceAssign(A, { row: j }, jStat.add(Aj, cAi));
var Ij = jStat.slice(I, { row: j });
var cIi = jStat.multiply(jStat.slice(I, { row: i }), c);
jStat.sliceAssign(I, { row: j }, jStat.add(Ij, cIi));
})
});
return I;
}
function qr_solve(A, b){
var array_mode = false;
if (b[0].length === undefined) {
// [c1,c2,c3] mode
b = b.map(function(x){ return [x] });
array_mode = true;
}
var QR = jStat.QR(A);
var Q = QR[0];
var R = QR[1];
var attrs = A[0].length;
var Q1 = jStat.slice(Q,{col:{end:attrs}});
var R1 = jStat.slice(R,{row:{end:attrs}});
var RI = R_I(R1);
var Q2 = jStat.transpose(Q1);
if(Q2[0].length === undefined){
Q2 = [Q2]; // The confusing jStat.multifly implementation threat nature process again.
}
var x = jStat.multiply(jStat.multiply(RI, Q2), b);
if(x.length === undefined){
x = [[x]]; // The confusing jStat.multifly implementation threat nature process again.
}
if (array_mode)
return x.map(function(i){ return i[0] });
return x;
}
return qr_solve;
}()),
jacobi: function jacobi(a) {
var condition = 1;
var count = 0;
var n = a.length;
var e = jStat.identity(n, n);
var ev = [];
var b, i, j, p, q, maxim, theta, s;
// condition === 1 only if tolerance is not reached
while (condition === 1) {
count++;
maxim = a[0][1];
p = 0;
q = 1;
for (var i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i != j) {
if (maxim < Math.abs(a[i][j])) {
maxim = Math.abs(a[i][j]);
p = i;
q = j;
}
}
}
}
if (a[p][p] === a[q][q])
theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4;
else
theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2;
s = jStat.identity(n, n);
s[p][p] = Math.cos(theta);
s[p][q] = -Math.sin(theta);
s[q][p] = Math.sin(theta);
s[q][q] = Math.cos(theta);
// eigen vector matrix
e = jStat.multiply(e, s);
b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s);
a = b;
condition = 0;
for (var i = 1; i < n; i++) {
for (j = 1; j < n; j++) {
if (i != j && Math.abs(a[i][j]) > 0.001) {
condition = 1;
}
}
}
}
for (var i = 0; i < n; i++) ev.push(a[i][i]);
//returns both the eigenvalue and eigenmatrix
return [e, ev];
},
rungekutta: function rungekutta(f, h, p, t_j, u_j, order) {
var k1, k2, u_j1, k3, k4;
if (order === 2) {
while (t_j <= p) {
k1 = h * f(t_j, u_j);
k2 = h * f(t_j + h, u_j + k1);
u_j1 = u_j + (k1 + k2) / 2;
u_j = u_j1;
t_j = t_j + h;
}
}
if (order === 4) {
while (t_j <= p) {
k1 = h * f(t_j, u_j);
k2 = h * f(t_j + h / 2, u_j + k1 / 2);
k3 = h * f(t_j + h / 2, u_j + k2 / 2);
k4 = h * f(t_j +h, u_j + k3);
u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
u_j = u_j1;
t_j = t_j + h;
}
}
return u_j;
},
romberg: function romberg(f, a, b, order) {
var i = 0;
var h = (b - a) / 2;
var x = [];
var h1 = [];
var g = [];
var m, a1, j, k, I, d;
while (i < order / 2) {
I = f(a);
for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j;
m = x.length;
for (j = 1; j < m - 1; j++) {
I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]);
}
I = (h / 3) * (I + f(b));
g[i] = I;
h /= 2;
i++;
}
a1 = g.length;
m = 1;
while (a1 !== 1) {
for (j = 0; j < a1 - 1; j++)
h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
a1 = h1.length;
g = h1;
h1 = [];
m++;
}
return g;
},
richardson: function richardson(X, f, x, h) {
function pos(X, x) {
var i = 0;
var n = X.length;
var p;
for (; i < n; i++)
if (X[i] === x) p = i;
return p;
}
var n = X.length,
h_min = Math.abs(x - X[pos(X, x) + 1]),
i = 0,
g = [],
h1 = [],
y1, y2, m, a, j;
while (h >= h_min) {
y1 = pos(X, x + h);
y2 = pos(X, x);
g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h);
h /= 2;
i++;
}
a = g.length;
m = 1;
while (a != 1) {
for (j = 0; j < a - 1; j++)
h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
a = h1.length;
g = h1;
h1 = [];
m++;
}
return g;
},
simpson: function simpson(f, a, b, n) {
var h = (b - a) / n;
var I = f(a);
var x = [];
var j = a;
var k = 0;
var i = 1;
var m;
for (; j <= b; j = j + h, k++)
x[k] = j;
m = x.length;
for (; i < m - 1; i++) {
I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]);
}
return (h / 3) * (I + f(b));
},
hermite: function hermite(X, F, dF, value) {
var n = X.length;
var p = 0;
var i = 0;
var l = [];
var dl = [];
var A = [];
var B = [];
var j;
for (; i < n; i++) {
l[i] = 1;
for (j = 0; j < n; j++) {
if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]);
}
dl[i] = 0;
for (j = 0; j < n; j++) {
if (i != j) dl[i] += 1 / (X [i] - X[j]);
}
A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]);
B[i] = (value - X[i]) * (l[i] * l[i]);
p += (A[i] * F[i] + B[i] * dF[i]);
}
return p;
},
lagrange: function lagrange(X, F, value) {
var p = 0;
var i = 0;
var j, l;
var n = X.length;
for (; i < n; i++) {
l = F[i];
for (j = 0; j < n; j++) {
// calculating the lagrange polynomial L_i
if (i != j) l *= (value - X[j]) / (X[i] - X[j]);
}
// adding the lagrange polynomials found above
p += l;
}
return p;
},
cubic_spline: function cubic_spline(X, F, value) {
var n = X.length;
var i = 0, j;
var A = [];
var B = [];
var alpha = [];
var c = [];
var h = [];
var b = [];
var d = [];
for (; i < n - 1; i++)
h[i] = X[i + 1] - X[i];
alpha[0] = 0;
for (var i = 1; i < n - 1; i++) {
alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) -
(3 / h[i-1]) * (F[i] - F[i-1]);
}
for (var i = 1; i < n - 1; i++) {
A[i] = [];
B[i] = [];
A[i][i-1] = h[i-1];
A[i][i] = 2 * (h[i - 1] + h[i]);
A[i][i+1] = h[i];
B[i][0] = alpha[i];
}
c = jStat.multiply(jStat.inv(A), B);
for (j = 0; j < n - 1; j++) {
b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3;
d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]);
}
for (j = 0; j < n; j++) {
if (X[j] > value) break;
}
j -= 1;
return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) *
c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j];
},
gauss_quadrature: function gauss_quadrature() {
throw new Error('gauss_quadrature not yet implemented');
},
PCA: function PCA(X) {
var m = X.length;
var n = X[0].length;
var flag = false;
var i = 0;
var j, temp1;
var u = [];
var D = [];
var result = [];
var temp2 = [];
var Y = [];
var Bt = [];
var B = [];
var C = [];
var V = [];
var Vt = [];
for (var i = 0; i < m; i++) {
u[i] = jStat.sum(X[i]) / n;
}
for (var i = 0; i < n; i++) {
B[i] = [];
for(j = 0; j < m; j++) {
B[i][j] = X[j][i] - u[j];
}
}
B = jStat.transpose(B);
for (var i = 0; i < m; i++) {
C[i] = [];
for (j = 0; j < m; j++) {
C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1);
}
}
result = jStat.jacobi(C);
V = result[0];
D = result[1];
Vt = jStat.transpose(V);
for (var i = 0; i < D.length; i++) {
for (j = i; j < D.length; j++) {
if(D[i] < D[j]) {
temp1 = D[i];
D[i] = D[j];
D[j] = temp1;
temp2 = Vt[i];
Vt[i] = Vt[j];
Vt[j] = temp2;
}
}
}
Bt = jStat.transpose(B);
for (var i = 0; i < m; i++) {
Y[i] = [];
for (j = 0; j < Bt.length; j++) {
Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]);
}
}
return [X, D, Vt, Y];
}
});
// extend jStat.fn with methods that require one argument
(function(funcs) {
for (var i = 0; i < funcs.length; i++) (function(passfunc) {
jStat.fn[passfunc] = function(arg, func) {
var tmpthis = this;
// check for callback
if (func) {
setTimeout(function() {
func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg));
}, 15);
return this;
}
if (typeof jStat[passfunc](this, arg) === 'number')
return jStat[passfunc](this, arg);
else
return jStat(jStat[passfunc](this, arg));
};
}(funcs[i]));
}('add divide multiply subtract dot pow exp log abs norm angle'.split(' ')));
}(jStat, Math));
(function(jStat, Math) {
var slice = [].slice;
var isNumber = jStat.utils.isNumber;
var isArray = jStat.utils.isArray;
// flag==true denotes use of sample standard deviation
// Z Statistics
jStat.extend({
// 2 different parameter lists:
// (value, mean, sd)
// (value, array, flag)
zscore: function zscore() {
var args = slice.call(arguments);
if (isNumber(args[1])) {
return (args[0] - args[1]) / args[2];
}
return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]);
},
// 3 different paramter lists:
// (value, mean, sd, sides)
// (zscore, sides)
// (value, array, sides, flag)
ztest: function ztest() {
var args = slice.call(arguments);
var z;
if (isArray(args[1])) {
// (value, array, sides, flag)
z = jStat.zscore(args[0],args[1],args[3]);
return (args[2] === 1) ?
(jStat.normal.cdf(-Math.abs(z), 0, 1)) :
(jStat.normal.cdf(-Math.abs(z), 0, 1)*2);
} else {
if (args.length > 2) {
// (value, mean, sd, sides)
z = jStat.zscore(args[0],args[1],args[2]);
return (args[3] === 1) ?
(jStat.normal.cdf(-Math.abs(z),0,1)) :
(jStat.normal.cdf(-Math.abs(z),0,1)* 2);
} else {
// (zscore, sides)
z = args[0];
return (args[1] === 1) ?
(jStat.normal.cdf(-Math.abs(z),0,1)) :
(jStat.normal.cdf(-Math.abs(z),0,1)*2);
}
}
}
});
jStat.extend(jStat.fn, {
zscore: function zscore(value, flag) {
return (value - this.mean()) / this.stdev(flag);
},
ztest: function ztest(value, sides, flag) {
var zscore = Math.abs(this.zscore(value, flag));
return (sides === 1) ?
(jStat.normal.cdf(-zscore, 0, 1)) :
(jStat.normal.cdf(-zscore, 0, 1) * 2);
}
});
// T Statistics
jStat.extend({
// 2 parameter lists
// (value, mean, sd, n)
// (value, array)
tscore: function tscore() {
var args = slice.call(arguments);
return (args.length === 4) ?
((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) :
((args[0] - jStat.mean(args[1])) /
(jStat.stdev(args[1], true) / Math.sqrt(args[1].length)));
},
// 3 different paramter lists:
// (value, mean, sd, n, sides)
// (tscore, n, sides)
// (value, array, sides)
ttest: function ttest() {
var args = slice.call(arguments);
var tscore;
if (args.length === 5) {
tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3]));
return (args[4] === 1) ?
(jStat.studentt.cdf(-tscore, args[3]-1)) :
(jStat.studentt.cdf(-tscore, args[3]-1)*2);
}
if (isNumber(args[1])) {
tscore = Math.abs(args[0])
return (args[2] == 1) ?
(jStat.studentt.cdf(-tscore, args[1]-1)) :
(jStat.studentt.cdf(-tscore, args[1]-1) * 2);
}
tscore = Math.abs(jStat.tscore(args[0], args[1]))
return (args[2] == 1) ?
(jStat.studentt.cdf(-tscore, args[1].length-1)) :
(jStat.studentt.cdf(-tscore, args[1].length-1) * 2);
}
});
jStat.extend(jStat.fn, {
tscore: function tscore(value) {
return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols()));
},
ttest: function ttest(value, sides) {
return (sides === 1) ?
(1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) :
(jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2);
}
});
// F Statistics
jStat.extend({
// Paramter list is as follows:
// (array1, array2, array3, ...)
// or it is an array of arrays
// array of arrays conversion
anovafscore: function anovafscore() {
var args = slice.call(arguments),
expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
if (args.length === 1) {
tmpargs = new Array(args[0].length);
for (var i = 0; i < args[0].length; i++) {
tmpargs[i] = args[0][i];
}
args = tmpargs;
}
// 2 sample case
if (args.length === 2) {
return jStat.variance(args[0]) / jStat.variance(args[1]);
}
// Builds sample array
sample = new Array();
for (var i = 0; i < args.length; i++) {
sample = sample.concat(args[i]);
}
sampMean = jStat.mean(sample);
// Computes the explained variance
expVar = 0;
for (var i = 0; i < args.length; i++) {
expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2);
}
expVar /= (args.length - 1);
// Computes unexplained variance
unexpVar = 0;
for (var i = 0; i < args.length; i++) {
sampSampMean = jStat.mean(args[i]);
for (j = 0; j < args[i].length; j++) {
unexpVar += Math.pow(args[i][j] - sampSampMean, 2);
}
}
unexpVar /= (sample.length - args.length);
return expVar / unexpVar;
},
// 2 different paramter setups
// (array1, array2, array3, ...)
// (anovafscore, df1, df2)
anovaftest: function anovaftest() {
var args = slice.call(arguments),
df1, df2, n, i;
if (isNumber(args[0])) {
return 1 - jStat.centralF.cdf(args[0], args[1], args[2]);
}
anovafscore = jStat.anovafscore(args);
df1 = args.length - 1;
n = 0;
for (var i = 0; i < args.length; i++) {
n = n + args[i].length;
}
df2 = n - df1 - 1;
return 1 - jStat.centralF.cdf(anovafscore, df1, df2);
},
ftest: function ftest(fscore, df1, df2) {
return 1 - jStat.centralF.cdf(fscore, df1, df2);
}
});
jStat.extend(jStat.fn, {
anovafscore: function anovafscore() {
return jStat.anovafscore(this.toArray());
},
anovaftes: function anovaftes() {
var n = 0;
var i;
for (var i = 0; i < this.length; i++) {
n = n + this[i].length;
}
return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length);
}
});
// Tukey's range test
jStat.extend({
// 2 parameter lists
// (mean1, mean2, n1, n2, sd)
// (array1, array2, sd)
qscore: function qscore() {
var args = slice.call(arguments);
var mean1, mean2, n1, n2, sd;
if (isNumber(args[0])) {
mean1 = args[0];
mean2 = args[1];
n1 = args[2];
n2 = args[3];
sd = args[4];
} else {
mean1 = jStat.mean(args[0]);
mean2 = jStat.mean(args[1]);
n1 = args[0].length;
n2 = args[1].length;
sd = args[2];
}
return Math.abs(mean1 - mean2) / (sd * Math.sqrt((1 / n1 + 1 / n2) / 2));
},
// 3 different parameter lists:
// (qscore, n, k)
// (mean1, mean2, n1, n2, sd, n, k)
// (array1, array2, sd, n, k)
qtest: function qtest() {
var args = slice.call(arguments);
var qscore;
if (args.length === 3) {
qscore = args[0];
args = args.slice(1);
} else if (args.length === 7) {
qscore = jStat.qscore(args[0], args[1], args[2], args[3], args[4]);
args = args.slice(5);
} else {
qscore = jStat.qscore(args[0], args[1], args[2]);
args = args.slice(3);
}
var n = args[0];
var k = args[1];
return 1 - jStat.tukey.cdf(qscore, k, n - k);
},
tukeyhsd: function tukeyhsd(arrays) {
var sd = jStat.pooledstdev(arrays);
var means = arrays.map(function (arr) {return jStat.mean(arr);});
var n = arrays.reduce(function (n, arr) {return n + arr.length;}, 0);
var results = [];
for (var i = 0; i < arrays.length; ++i) {
for (var j = i + 1; j < arrays.length; ++j) {
var p = jStat.qtest(means[i], means[j], arrays[i].length, arrays[j].length, sd, n, arrays.length);
results.push([[i, j], p]);
}
}
return results;
}
});
// Error Bounds
jStat.extend({
// 2 different parameter setups
// (value, alpha, sd, n)
// (value, alpha, array)
normalci: function normalci() {
var args = slice.call(arguments),
ans = new Array(2),
change;
if (args.length === 4) {
change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
args[2] / Math.sqrt(args[3]));
} else {
change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
jStat.stdev(args[2]) / Math.sqrt(args[2].length));
}
ans[0] = args[0] - change;
ans[1] = args[0] + change;
return ans;
},
// 2 different parameter setups
// (value, alpha, sd, n)
// (value, alpha, array)
tci: function tci() {
var args = slice.call(arguments),
ans = new Array(2),
change;
if (args.length === 4) {
change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) *
args[2] / Math.sqrt(args[3]));
} else {
change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) *
jStat.stdev(args[2], true) / Math.sqrt(args[2].length));
}
ans[0] = args[0] - change;
ans[1] = args[0] + change;
return ans;
},
significant: function significant(pvalue, alpha) {
return pvalue < alpha;
}
});
jStat.extend(jStat.fn, {
normalci: function normalci(value, alpha) {
return jStat.normalci(value, alpha, this.toArray());
},
tci: function tci(value, alpha) {
return jStat.tci(value, alpha, this.toArray());
}
});
// internal method for calculating the z-score for a difference of proportions test
function differenceOfProportions(p1, n1, p2, n2) {
if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) {
throw new Error("Proportions should be greater than 0 and less than 1")
}
var pooled = (p1 * n1 + p2 * n2) / (n1 + n2);
var se = Math.sqrt(pooled * (1 - pooled) * ((1/n1) + (1/n2)));
return (p1 - p2) / se;
}
// Difference of Proportions
jStat.extend(jStat.fn, {
oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) {
var z = differenceOfProportions(p1, n1, p2, n2);
return jStat.ztest(z, 1);
},
twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) {
var z = differenceOfProportions(p1, n1, p2, n2);
return jStat.ztest(z, 2);
}
});
}(jStat, Math));
jStat.models = (function(){
function sub_regress(endog, exog) {
return ols(endog, exog);
}
function sub_regress(exog) {
var var_count = exog[0].length;
var modelList = jStat.arange(var_count).map(function(endog_index) {
var exog_index =
jStat.arange(var_count).filter(function(i){return i!==endog_index});
return ols(jStat.col(exog, endog_index).map(function(x){ return x[0] }),
jStat.col(exog, exog_index))
});
return modelList;
}
// do OLS model regress
// exog have include const columns ,it will not generate it .In fact, exog is
// "design matrix" look at
//https://en.wikipedia.org/wiki/Design_matrix
function ols(endog, exog) {
var nobs = endog.length;
var df_model = exog[0].length - 1;
var df_resid = nobs-df_model - 1;
var coef = jStat.lstsq(exog, endog);
var predict =
jStat.multiply(exog, coef.map(function(x) { return [x] }))
.map(function(p) { return p[0] });
var resid = jStat.subtract(endog, predict);
var ybar = jStat.mean(endog);
// constant cause problem
// var SST = jStat.sum(endog.map(function(y) {
// return Math.pow(y-ybar,2);
// }));
var SSE = jStat.sum(predict.map(function(f) {
return Math.pow(f - ybar, 2);
}));
var SSR = jStat.sum(endog.map(function(y, i) {
return Math.pow(y - predict[i], 2);
}));
var SST = SSE + SSR;
var R2 = (SSE / SST);
return {
exog:exog,
endog:endog,
nobs:nobs,
df_model:df_model,
df_resid:df_resid,
coef:coef,
predict:predict,
resid:resid,
ybar:ybar,
SST:SST,
SSE:SSE,
SSR:SSR,
R2:R2
};
}
// H0: b_I=0
// H1: b_I!=0
function t_test(model) {
var subModelList = sub_regress(model.exog);
//var sigmaHat=jStat.stdev(model.resid);
var sigmaHat = Math.sqrt(model.SSR / (model.df_resid));
var seBetaHat = subModelList.map(function(mod) {
var SST = mod.SST;
var R2 = mod.R2;
return sigmaHat / Math.sqrt(SST * (1 - R2));
});
var tStatistic = model.coef.map(function(coef, i) {
return (coef - 0) / seBetaHat[i];
});
var pValue = tStatistic.map(function(t) {
var leftppf = jStat.studentt.cdf(t, model.df_resid);
return (leftppf > 0.5 ? 1 - leftppf : leftppf) * 2;
});
var c = jStat.studentt.inv(0.975, model.df_resid);
var interval95 = model.coef.map(function(coef, i) {
var d = c * seBetaHat[i];
return [coef - d, coef + d];
})
return {
se: seBetaHat,
t: tStatistic,
p: pValue,
sigmaHat: sigmaHat,
interval95: interval95
};
}
function F_test(model) {
var F_statistic =
(model.R2 / model.df_model) / ((1 - model.R2) / model.df_resid);
var fcdf = function(x, n1, n2) {
return jStat.beta.cdf(x / (n2 / n1 + x), n1 / 2, n2 / 2)
}
var pvalue = 1 - fcdf(F_statistic, model.df_model, model.df_resid);
return { F_statistic: F_statistic, pvalue: pvalue };
}
function ols_wrap(endog, exog) {
var model = ols(endog,exog);
var ttest = t_test(model);
var ftest = F_test(model);
// Provide the Wherry / Ezekiel / McNemar / Cohen Adjusted R^2
// Which matches the 'adjusted R^2' provided by R's lm package
var adjust_R2 =
1 - (1 - model.R2) * ((model.nobs - 1) / (model.df_resid));
model.t = ttest;
model.f = ftest;
model.adjust_R2 = adjust_R2;
return model;
}
return { ols: ols_wrap };
})();
// Make it compatible with previous version.
jStat.jStat = jStat;
return jStat;
});
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var utils = __webpack_require__(1);
var numbro = __webpack_require__(9);
var error = __webpack_require__(0);
exports.UNIQUE = function () {
var result = [];
for (var i = 0; i < arguments.length; ++i) {
var hasElement = false;
var element = arguments[i];
// Check if we've already seen this element.
for (var j = 0; j < result.length; ++j) {
hasElement = result[j] === element;
if (hasElement) { break; }
}
// If we did not find it, add it to the result.
if (!hasElement) {
result.push(element);
}
}
return result;
};
exports.FLATTEN = utils.flatten;
exports.ARGS2ARRAY = function () {
return Array.prototype.slice.call(arguments, 0);
};
exports.REFERENCE = function (context, reference) {
if (!arguments.length) {
return error.error;
}
try {
var path = reference.split('.');
var result = context;
for (var i = 0; i < path.length; ++i) {
var step = path[i];
if (step[step.length - 1] === ']') {
var opening = step.indexOf('[');
var index = step.substring(opening + 1, step.length - 1);
result = result[step.substring(0, opening)][index];
} else {
result = result[step];
}
}
return result;
} catch (error) {}
};
exports.JOIN = function (array, separator) {
return array.join(separator);
};
exports.NUMBERS = function () {
var possibleNumbers = utils.flatten(arguments);
return possibleNumbers.filter(function (el) {
return typeof el === 'number';
});
};
exports.NUMERAL = function (number, format) {
return numbro(number).format(format);
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var jStat = __webpack_require__(11).jStat;
var text = __webpack_require__(6);
var utils = __webpack_require__(1);
var bessel = __webpack_require__(28);
function isValidBinaryNumber(number) {
return (/^[01]{1,10}$/).test(number);
}
exports.BESSELI = function(x, n) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
if (utils.anyIsError(x, n)) {
return error.value;
}
return bessel.besseli(x, n);
};
exports.BESSELJ = function(x, n) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
if (utils.anyIsError(x, n)) {
return error.value;
}
return bessel.besselj(x, n);
};
exports.BESSELK = function(x, n) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
if (utils.anyIsError(x, n)) {
return error.value;
}
return bessel.besselk(x, n);
};
exports.BESSELY = function(x, n) {
x = utils.parseNumber(x);
n = utils.parseNumber(n);
if (utils.anyIsError(x, n)) {
return error.value;
}
return bessel.bessely(x, n);
};
exports.BIN2DEC = function(number) {
// Return error if number is not binary or contains more than 10 characters (10 digits)
if (!isValidBinaryNumber(number)) {
return error.num;
}
// Convert binary number to decimal
var result = parseInt(number, 2);
// Handle negative numbers
var stringified = number.toString();
if (stringified.length === 10 && stringified.substring(0, 1) === '1') {
return parseInt(stringified.substring(1), 2) - 512;
} else {
return result;
}
};
exports.BIN2HEX = function(number, places) {
// Return error if number is not binary or contains more than 10 characters (10 digits)
if (!isValidBinaryNumber(number)) {
return error.num;
}
// Ignore places and return a 10-character hexadecimal number if number is negative
var stringified = number.toString();
if (stringified.length === 10 && stringified.substring(0, 1) === '1') {
return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16);
}
// Convert binary number to hexadecimal
var result = parseInt(number, 2).toString(16);
// Return hexadecimal number using the minimum number of characters necessary if places is undefined
if (places === undefined) {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.BIN2OCT = function(number, places) {
// Return error if number is not binary or contains more than 10 characters (10 digits)
if (!isValidBinaryNumber(number)) {
return error.num;
}
// Ignore places and return a 10-character octal number if number is negative
var stringified = number.toString();
if (stringified.length === 10 && stringified.substring(0, 1) === '1') {
return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8);
}
// Convert binary number to octal
var result = parseInt(number, 2).toString(8);
// Return octal number using the minimum number of characters necessary if places is undefined
if (places === undefined) {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.BITAND = function(number1, number2) {
// Return error if either number is a non-numeric value
number1 = utils.parseNumber(number1);
number2 = utils.parseNumber(number2);
if (utils.anyIsError(number1, number2)) {
return error.value;
}
// Return error if either number is less than 0
if (number1 < 0 || number2 < 0) {
return error.num;
}
// Return error if either number is a non-integer
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) {
return error.num;
}
// Return error if either number is greater than (2^48)-1
if (number1 > 281474976710655 || number2 > 281474976710655) {
return error.num;
}
// Return bitwise AND of two numbers
return number1 & number2;
};
exports.BITLSHIFT = function(number, shift) {
number = utils.parseNumber(number);
shift = utils.parseNumber(shift);
if (utils.anyIsError(number, shift)) {
return error.value;
}
// Return error if number is less than 0
if (number < 0) {
return error.num;
}
// Return error if number is a non-integer
if (Math.floor(number) !== number) {
return error.num;
}
// Return error if number is greater than (2^48)-1
if (number > 281474976710655) {
return error.num;
}
// Return error if the absolute value of shift is greater than 53
if (Math.abs(shift) > 53) {
return error.num;
}
// Return number shifted by shift bits to the left or to the right if shift is negative
return (shift >= 0) ? number << shift : number >> -shift;
};
exports.BITOR = function(number1, number2) {
number1 = utils.parseNumber(number1);
number2 = utils.parseNumber(number2);
if (utils.anyIsError(number1, number2)) {
return error.value;
}
// Return error if either number is less than 0
if (number1 < 0 || number2 < 0) {
return error.num;
}
// Return error if either number is a non-integer
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) {
return error.num;
}
// Return error if either number is greater than (2^48)-1
if (number1 > 281474976710655 || number2 > 281474976710655) {
return error.num;
}
// Return bitwise OR of two numbers
return number1 | number2;
};
exports.BITRSHIFT = function(number, shift) {
number = utils.parseNumber(number);
shift = utils.parseNumber(shift);
if (utils.anyIsError(number, shift)) {
return error.value;
}
// Return error if number is less than 0
if (number < 0) {
return error.num;
}
// Return error if number is a non-integer
if (Math.floor(number) !== number) {
return error.num;
}
// Return error if number is greater than (2^48)-1
if (number > 281474976710655) {
return error.num;
}
// Return error if the absolute value of shift is greater than 53
if (Math.abs(shift) > 53) {
return error.num;
}
// Return number shifted by shift bits to the right or to the left if shift is negative
return (shift >= 0) ? number >> shift : number << -shift;
};
exports.BITXOR = function(number1, number2) {
number1 = utils.parseNumber(number1);
number2 = utils.parseNumber(number2);
if (utils.anyIsError(number1, number2)) {
return error.value;
}
// Return error if either number is less than 0
if (number1 < 0 || number2 < 0) {
return error.num;
}
// Return error if either number is a non-integer
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) {
return error.num;
}
// Return error if either number is greater than (2^48)-1
if (number1 > 281474976710655 || number2 > 281474976710655) {
return error.num;
}
// Return bitwise XOR of two numbers
return number1 ^ number2;
};
exports.COMPLEX = function(real, imaginary, suffix) {
real = utils.parseNumber(real);
imaginary = utils.parseNumber(imaginary);
if (utils.anyIsError(real, imaginary)) {
return real;
}
// Set suffix
suffix = (suffix === undefined) ? 'i' : suffix;
// Return error if suffix is neither "i" nor "j"
if (suffix !== 'i' && suffix !== 'j') {
return error.value;
}
// Return complex number
if (real === 0 && imaginary === 0) {
return 0;
} else if (real === 0) {
return (imaginary === 1) ? suffix : imaginary.toString() + suffix;
} else if (imaginary === 0) {
return real.toString();
} else {
var sign = (imaginary > 0) ? '+' : '';
return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix);
}
};
exports.CONVERT = function(number, from_unit, to_unit) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
// List of units supported by CONVERT and units defined by the International System of Units
// [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion ratio]
var units = [
["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34],
["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19],
["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18],
["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11],
["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31],
["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17],
["admiralty knot", "admkn", null, "speed", false, true, 0.514773333],
["ampere", "A", null, "electric_current", true, false, 1],
["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1],
["ångström", "Å", ["ang"], "length", false, true, 1e-10],
["are", "ar", null, "area", false, true, 100],
["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11],
["bar", "bar", null, "pressure", false, false, 100000],
["barn", "b", null, "area", false, false, 1e-28],
["becquerel", "Bq", null, "radioactivity", true, false, 1],
["bit", "bit", ["b"], "information", false, true, 1],
["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262],
["byte", "byte", null, "information", false, true, 8],
["candela", "cd", null, "luminous_intensity", true, false, 1],
["candela per square metre", "cd/m?", null, "luminance", true, false, 1],
["coulomb", "C", null, "electric_charge", true, false, 1],
["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30],
["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592],
["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064],
["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47],
["cubic metre", "m?", null, "volume", true, true, 1],
["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058],
["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208],
["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8],
["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984],
["cup", "cup", null, "volume", false, true, 0.0002365882365],
["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27],
["day", "d", ["day"], "time", false, true, 86400],
["degree", "°", null, "angle", false, false, 0.0174532925199433],
["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556],
["dyne", "dyn", ["dy"], "force", false, true, 0.00001],
["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141],
["ell", "ell", null, "length", false, true, 1.143],
["erg", "erg", ["e"], "energy", false, true, 1e-7],
["farad", "F", null, "electric_capacitance", true, false, 1],
["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625],
["foot", "ft", null, "length", false, true, 0.3048],
["foot-pound", "flb", null, "energy", false, true, 1.3558179483314],
["gal", "Gal", null, "acceleration", false, false, 0.01],
["gallon", "gal", null, "volume", false, true, 0.003785411784],
["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1],
["grain", "grain", null, "mass", false, true, 0.0000647989],
["gram", "g", null, "mass", false, true, 0.001],
["gray", "Gy", null, "absorbed_dose", true, false, 1],
["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592],
["hectare", "ha", null, "area", false, true, 10000],
["henry", "H", null, "inductance", true, false, 1],
["hertz", "Hz", null, "frequency", true, false, 1],
["horsepower", "HP", ["h"], "power", false, true, 745.69987158227],
["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538],
["hour", "h", ["hr"], "time", false, true, 3600],
["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609],
["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345],
["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225],
["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909],
["inch", "in", null, "length", false, true, 0.0254],
["international acre", "uk_acre", null, "area", false, true, 4046.8564224],
["IT calorie", "cal", null, "energy", false, true, 4.1868],
["joule", "J", null, "energy", true, true, 1],
["katal", "kat", null, "catalytic_activity", true, false, 1],
["kelvin", "K", ["kel"], "temperature", true, true, 1],
["kilogram", "kg", null, "mass", true, true, 1],
["knot", "kn", null, "speed", false, true, 0.514444444444444],
["light-year", "ly", null, "length", false, true, 9460730472580800],
["litre", "L", ["l", "lt"], "volume", false, true, 0.001],
["lumen", "lm", null, "luminous_flux", true, false, 1],
["lux", "lx", null, "illuminance", true, false, 1],
["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18],
["measurement ton", "MTON", null, "volume", false, true, 1.13267386368],
["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778],
["meter per second", "m/s", ["m/sec"], "speed", true, true, 1],
["meter per second squared", "m?s??", null, "acceleration", true, false, 1],
["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900],
["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1],
["metre", "m", null, "length", true, true, 1],
["miles per hour", "mph", null, "speed", false, true, 0.44704],
["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322],
["minute", "?", null, "angle", false, false, 0.000290888208665722],
["minute", "min", ["mn"], "time", false, true, 60],
["modern teaspoon", "tspm", null, "volume", false, true, 0.000005],
["mole", "mol", null, "amount_of_substance", true, false, 1],
["morgen", "Morgen", null, "area", false, true, 2500],
["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34],
["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31],
["n.u. of speed", "c?", null, "speed", false, false, 299792458],
["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21],
["nautical mile", "M", ["Nmi"], "length", false, true, 1852],
["newton", "N", null, "force", true, true, 1],
["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477],
["ohm", "Ω", null, "electric_resistance", true, false, 1],
["ounce mass", "ozm", null, "mass", false, true, 0.028349523125],
["pascal", "Pa", null, "pressure", true, false, 1],
["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1],
["pferdestärke", "PS", null, "power", false, true, 735.49875],
["phot", "ph", null, "illuminance", false, false, 0.0001],
["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778],
["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333],
["poise", "P", null, "dynamic_viscosity", false, false, 0.1],
["pond", "pond", null, "force", false, true, 0.00980665],
["pound force", "lbf", null, "force", false, true, 4.4482216152605],
["pound mass", "lbm", null, "mass", false, true, 0.45359237],
["quart", "qt", null, "volume", false, true, 0.000946352946],
["radian", "rad", null, "angle", true, false, 1],
["second", "?", null, "angle", false, false, 0.00000484813681109536],
["second", "s", ["sec"], "time", true, true, 1],
["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237],
["siemens", "S", null, "electrical_conductance", true, false, 1],
["sievert", "Sv", null, "equivalent_dose", true, false, 1],
["slug", "sg", null, "mass", false, true, 14.59390294],
["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20],
["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304],
["square inch", "in2", ["in^2"], "area", false, true, 0.00064516],
["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31],
["square meter", "m?", null, "area", true, true, 1],
["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336],
["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904],
["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111],
["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736],
["statute mile", "mi", null, "length", false, true, 1609.344],
["steradian", "sr", null, "solid_angle", true, false, 1],
["stilb", "sb", null, "luminance", false, false, 0.0001],
["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001],
["stone", "stone", null, "mass", false, true, 6.35029318],
["tablespoon", "tbs", null, "volume", false, true, 0.0000147868],
["teaspoon", "tsp", null, "volume", false, true, 0.00000492892],
["tesla", "T", null, "magnetic_flux_density", true, true, 1],
["thermodynamic calorie", "c", null, "energy", false, true, 4.184],
["ton", "ton", null, "mass", false, true, 907.18474],
["tonne", "t", null, "mass", false, false, 1000],
["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125],
["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907],
["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295],
["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473],
["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219],
["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261],
["volt", "V", null, "voltage", true, false, 1],
["watt", "W", null, "power", true, true, 1],
["watt-hour", "Wh", ["wh"], "energy", false, true, 3600],
["weber", "Wb", null, "magnetic_flux", true, false, 1],
["yard", "yd", null, "length", false, true, 0.9144],
["year", "yr", null, "time", false, true, 31557600]
];
// Binary prefixes
// [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived from]
var binary_prefixes = {
Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"],
Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"],
Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"],
Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"],
Ti: ["tebi", 40, 1099511627776, "Ti", "tera"],
Gi: ["gibi", 30, 1073741824, "Gi", "giga"],
Mi: ["mebi", 20, 1048576, "Mi", "mega"],
ki: ["kibi", 10, 1024, "ki", "kilo"]
};
// Unit prefixes
// [Name, Multiplier, Abbreviation]
var unit_prefixes = {
Y: ["yotta", 1e+24, "Y"],
Z: ["zetta", 1e+21, "Z"],
E: ["exa", 1e+18, "E"],
P: ["peta", 1e+15, "P"],
T: ["tera", 1e+12, "T"],
G: ["giga", 1e+09, "G"],
M: ["mega", 1e+06, "M"],
k: ["kilo", 1e+03, "k"],
h: ["hecto", 1e+02, "h"],
e: ["dekao", 1e+01, "e"],
d: ["deci", 1e-01, "d"],
c: ["centi", 1e-02, "c"],
m: ["milli", 1e-03, "m"],
u: ["micro", 1e-06, "u"],
n: ["nano", 1e-09, "n"],
p: ["pico", 1e-12, "p"],
f: ["femto", 1e-15, "f"],
a: ["atto", 1e-18, "a"],
z: ["zepto", 1e-21, "z"],
y: ["yocto", 1e-24, "y"]
};
// Initialize units and multipliers
var from = null;
var to = null;
var base_from_unit = from_unit;
var base_to_unit = to_unit;
var from_multiplier = 1;
var to_multiplier = 1;
var alt;
// Lookup from and to units
for (var i = 0; i < units.length; i++) {
alt = (units[i][2] === null) ? [] : units[i][2];
if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) {
from = units[i];
}
if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) {
to = units[i];
}
}
// Lookup from prefix
if (from === null) {
var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)];
var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)];
// Handle dekao unit prefix (only unit prefix with two characters)
if (from_unit.substring(0, 2) === 'da') {
from_unit_prefix = ["dekao", 1e+01, "da"];
}
// Handle binary prefixes first (so that 'Yi' is processed before 'Y')
if (from_binary_prefix) {
from_multiplier = from_binary_prefix[2];
base_from_unit = from_unit.substring(2);
} else if (from_unit_prefix) {
from_multiplier = from_unit_prefix[1];
base_from_unit = from_unit.substring(from_unit_prefix[2].length);
}
// Lookup from unit
for (var j = 0; j < units.length; j++) {
alt = (units[j][2] === null) ? [] : units[j][2];
if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) {
from = units[j];
}
}
}
// Lookup to prefix
if (to === null) {
var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)];
var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)];
// Handle dekao unit prefix (only unit prefix with two characters)
if (to_unit.substring(0, 2) === 'da') {
to_unit_prefix = ["dekao", 1e+01, "da"];
}
// Handle binary prefixes first (so that 'Yi' is processed before 'Y')
if (to_binary_prefix) {
to_multiplier = to_binary_prefix[2];
base_to_unit = to_unit.substring(2);
} else if (to_unit_prefix) {
to_multiplier = to_unit_prefix[1];
base_to_unit = to_unit.substring(to_unit_prefix[2].length);
}
// Lookup to unit
for (var k = 0; k < units.length; k++) {
alt = (units[k][2] === null) ? [] : units[k][2];
if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) {
to = units[k];
}
}
}
// Return error if a unit does not exist
if (from === null || to === null) {
return error.na;
}
// Return error if units represent different quantities
if (from[3] !== to[3]) {
return error.na;
}
// Return converted number
return number * from[6] * from_multiplier / (to[6] * to_multiplier);
};
exports.DEC2BIN = function(number, places) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
// Return error if number is not decimal, is lower than -512, or is greater than 511
if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) {
return error.num;
}
// Ignore places and return a 10-character binary number if number is negative
if (number < 0) {
return '1' + text.REPT('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2);
}
// Convert decimal number to binary
var result = parseInt(number, 10).toString(2);
// Return binary number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.DEC2HEX = function(number, places) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
// Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887
if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) {
return error.num;
}
// Ignore places and return a 10-character hexadecimal number if number is negative
if (number < 0) {
return (1099511627776 + number).toString(16);
}
// Convert decimal number to hexadecimal
var result = parseInt(number, 10).toString(16);
// Return hexadecimal number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.DEC2OCT = function(number, places) {
number = utils.parseNumber(number);
if (number instanceof Error) {
return number;
}
// Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887
if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) {
return error.num;
}
// Ignore places and return a 10-character octal number if number is negative
if (number < 0) {
return (1073741824 + number).toString(8);
}
// Convert decimal number to octal
var result = parseInt(number, 10).toString(8);
// Return octal number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.DELTA = function(number1, number2) {
// Set number2 to zero if undefined
number2 = (number2 === undefined) ? 0 : number2;
number1 = utils.parseNumber(number1);
number2 = utils.parseNumber(number2);
if (utils.anyIsError(number1, number2)) {
return error.value;
}
// Return delta
return (number1 === number2) ? 1 : 0;
};
// TODO: why is upper_bound not used ? The excel documentation has no examples with upper_bound
exports.ERF = function(lower_bound, upper_bound) {
// Set number2 to zero if undefined
upper_bound = (upper_bound === undefined) ? 0 : upper_bound;
lower_bound = utils.parseNumber(lower_bound);
upper_bound = utils.parseNumber(upper_bound);
if (utils.anyIsError(lower_bound, upper_bound)) {
return error.value;
}
return jStat.erf(lower_bound);
};
// TODO
exports.ERF.PRECISE = function() {
throw new Error('ERF.PRECISE is not implemented');
};
exports.ERFC = function(x) {
// Return error if x is not a number
if (isNaN(x)) {
return error.value;
}
return jStat.erfc(x);
};
// TODO
exports.ERFC.PRECISE = function() {
throw new Error('ERFC.PRECISE is not implemented');
};
exports.GESTEP = function(number, step) {
step = step || 0;
number = utils.parseNumber(number);
if (utils.anyIsError(step, number)) {
return number;
}
// Return delta
return (number >= step) ? 1 : 0;
};
exports.HEX2BIN = function(number, places) {
// Return error if number is not hexadecimal or contains more than ten characters (10 digits)
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) {
return error.num;
}
// Check if number is negative
var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false;
// Convert hexadecimal number to decimal
var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16);
// Return error if number is lower than -512 or greater than 511
if (decimal < -512 || decimal > 511) {
return error.num;
}
// Ignore places and return a 10-character binary number if number is negative
if (negative) {
return '1' + text.REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2);
}
// Convert decimal number to binary
var result = decimal.toString(2);
// Return binary number using the minimum number of characters necessary if places is undefined
if (places === undefined) {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.HEX2DEC = function(number) {
// Return error if number is not hexadecimal or contains more than ten characters (10 digits)
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) {
return error.num;
}
// Convert hexadecimal number to decimal
var decimal = parseInt(number, 16);
// Return decimal number
return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal;
};
exports.HEX2OCT = function(number, places) {
// Return error if number is not hexadecimal or contains more than ten characters (10 digits)
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) {
return error.num;
}
// Convert hexadecimal number to decimal
var decimal = parseInt(number, 16);
// Return error if number is positive and greater than 0x1fffffff (536870911)
if (decimal > 536870911 && decimal < 1098974756864) {
return error.num;
}
// Ignore places and return a 10-character octal number if number is negative
if (decimal >= 1098974756864) {
return (decimal - 1098437885952).toString(8);
}
// Convert decimal number to octal
var result = decimal.toString(8);
// Return octal number using the minimum number of characters necessary if places is undefined
if (places === undefined) {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.IMABS = function(inumber) {
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
// Return error if either coefficient is not a number
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return absolute value of complex number
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
};
exports.IMAGINARY = function(inumber) {
if (inumber === undefined || inumber === true || inumber === false) {
return error.value;
}
// Return 0 if inumber is equal to 0
if (inumber === 0 || inumber === '0') {
return 0;
}
// Handle special cases
if (['i', 'j'].indexOf(inumber) >= 0) {
return 1;
}
// Normalize imaginary coefficient
inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j');
// Lookup sign
var plus = inumber.indexOf('+');
var minus = inumber.indexOf('-');
if (plus === 0) {
plus = inumber.indexOf('+', 1);
}
if (minus === 0) {
minus = inumber.indexOf('-', 1);
}
// Lookup imaginary unit
var last = inumber.substring(inumber.length - 1, inumber.length);
var unit = (last === 'i' || last === 'j');
if (plus >= 0 || minus >= 0) {
// Return error if imaginary unit is neither i nor j
if (!unit) {
return error.num;
}
// Return imaginary coefficient of complex number
if (plus >= 0) {
return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ?
error.num :
Number(inumber.substring(plus + 1, inumber.length - 1));
} else {
return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ?
error.num :
-Number(inumber.substring(minus + 1, inumber.length - 1));
}
} else {
if (unit) {
return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : inumber.substring(0, inumber.length - 1);
} else {
return (isNaN(inumber)) ? error.num : 0;
}
}
};
exports.IMARGUMENT = function(inumber) {
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
// Return error if either coefficient is not a number
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return error if inumber is equal to zero
if (x === 0 && y === 0) {
return error.div0;
}
// Return PI/2 if x is equal to zero and y is positive
if (x === 0 && y > 0) {
return Math.PI / 2;
}
// Return -PI/2 if x is equal to zero and y is negative
if (x === 0 && y < 0) {
return -Math.PI / 2;
}
// Return zero if x is negative and y is equal to zero
if (y === 0 && x > 0) {
return 0;
}
// Return zero if x is negative and y is equal to zero
if (y === 0 && x < 0) {
return -Math.PI;
}
// Return argument of complex number
if (x > 0) {
return Math.atan(y / x);
} else if (x < 0 && y >= 0) {
return Math.atan(y / x) + Math.PI;
} else {
return Math.atan(y / x) - Math.PI;
}
};
exports.IMCONJUGATE = function(inumber) {
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return conjugate of complex number
return (y !== 0) ? exports.COMPLEX(x, -y, unit) : inumber;
};
exports.IMCOS = function(inumber) {
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return cosine of complex number
return exports.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit);
};
exports.IMCOSH = function(inumber) {
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return hyperbolic cosine of complex number
return exports.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit);
};
exports.IMCOT = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return cotangent of complex number
return exports.IMDIV(exports.IMCOS(inumber), exports.IMSIN(inumber));
};
exports.IMDIV = function(inumber1, inumber2) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var a = exports.IMREAL(inumber1);
var b = exports.IMAGINARY(inumber1);
var c = exports.IMREAL(inumber2);
var d = exports.IMAGINARY(inumber2);
if (utils.anyIsError(a, b, c, d)) {
return error.value;
}
// Lookup imaginary unit
var unit1 = inumber1.substring(inumber1.length - 1);
var unit2 = inumber2.substring(inumber2.length - 1);
var unit = 'i';
if (unit1 === 'j') {
unit = 'j';
} else if (unit2 === 'j') {
unit = 'j';
}
// Return error if inumber2 is null
if (c === 0 && d === 0) {
return error.num;
}
// Return exponential of complex number
var den = c * c + d * d;
return exports.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit);
};
exports.IMEXP = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return exponential of complex number
var e = Math.exp(x);
return exports.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit);
};
exports.IMLN = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return exponential of complex number
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit);
};
exports.IMLOG10 = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return exponential of complex number
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit);
};
exports.IMLOG2 = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return exponential of complex number
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit);
};
exports.IMPOWER = function(inumber, number) {
number = utils.parseNumber(number);
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(number, x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Calculate power of modulus
var p = Math.pow(exports.IMABS(inumber), number);
// Calculate argument
var t = exports.IMARGUMENT(inumber);
// Return exponential of complex number
return exports.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit);
};
exports.IMPRODUCT = function() {
// Initialize result
var result = arguments[0];
if (!arguments.length) {
return error.value;
}
// Loop on all numbers
for (var i = 1; i < arguments.length; i++) {
// Lookup coefficients of two complex numbers
var a = exports.IMREAL(result);
var b = exports.IMAGINARY(result);
var c = exports.IMREAL(arguments[i]);
var d = exports.IMAGINARY(arguments[i]);
if (utils.anyIsError(a, b, c, d)) {
return error.value;
}
// Complute product of two complex numbers
result = exports.COMPLEX(a * c - b * d, a * d + b * c);
}
// Return product of complex numbers
return result;
};
exports.IMREAL = function(inumber) {
if (inumber === undefined || inumber === true || inumber === false) {
return error.value;
}
// Return 0 if inumber is equal to 0
if (inumber === 0 || inumber === '0') {
return 0;
}
// Handle special cases
if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) {
return 0;
}
// Lookup sign
var plus = inumber.indexOf('+');
var minus = inumber.indexOf('-');
if (plus === 0) {
plus = inumber.indexOf('+', 1);
}
if (minus === 0) {
minus = inumber.indexOf('-', 1);
}
// Lookup imaginary unit
var last = inumber.substring(inumber.length - 1, inumber.length);
var unit = (last === 'i' || last === 'j');
if (plus >= 0 || minus >= 0) {
// Return error if imaginary unit is neither i nor j
if (!unit) {
return error.num;
}
// Return real coefficient of complex number
if (plus >= 0) {
return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ?
error.num :
Number(inumber.substring(0, plus));
} else {
return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ?
error.num :
Number(inumber.substring(0, minus));
}
} else {
if (unit) {
return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : 0;
} else {
return (isNaN(inumber)) ? error.num : inumber;
}
}
};
exports.IMSEC = function(inumber) {
// Return error if inumber is a logical value
if (inumber === true || inumber === false) {
return error.value;
}
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return secant of complex number
return exports.IMDIV('1', exports.IMCOS(inumber));
};
exports.IMSECH = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return hyperbolic secant of complex number
return exports.IMDIV('1', exports.IMCOSH(inumber));
};
exports.IMSIN = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return sine of complex number
return exports.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit);
};
exports.IMSINH = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Return hyperbolic sine of complex number
return exports.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit);
};
exports.IMSQRT = function(inumber) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Lookup imaginary unit
var unit = inumber.substring(inumber.length - 1);
unit = (unit === 'i' || unit === 'j') ? unit : 'i';
// Calculate power of modulus
var s = Math.sqrt(exports.IMABS(inumber));
// Calculate argument
var t = exports.IMARGUMENT(inumber);
// Return exponential of complex number
return exports.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit);
};
exports.IMCSC = function (inumber) {
// Return error if inumber is a logical value
if (inumber === true || inumber === false) {
return error.value;
}
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
// Return error if either coefficient is not a number
if (utils.anyIsError(x, y)) {
return error.num;
}
// Return cosecant of complex number
return exports.IMDIV('1', exports.IMSIN(inumber));
};
exports.IMCSCH = function (inumber) {
// Return error if inumber is a logical value
if (inumber === true || inumber === false) {
return error.value;
}
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
// Return error if either coefficient is not a number
if (utils.anyIsError(x, y)) {
return error.num;
}
// Return hyperbolic cosecant of complex number
return exports.IMDIV('1', exports.IMSINH(inumber));
};
exports.IMSUB = function(inumber1, inumber2) {
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var a = this.IMREAL(inumber1);
var b = this.IMAGINARY(inumber1);
var c = this.IMREAL(inumber2);
var d = this.IMAGINARY(inumber2);
if (utils.anyIsError(a, b, c, d)) {
return error.value;
}
// Lookup imaginary unit
var unit1 = inumber1.substring(inumber1.length - 1);
var unit2 = inumber2.substring(inumber2.length - 1);
var unit = 'i';
if (unit1 === 'j') {
unit = 'j';
} else if (unit2 === 'j') {
unit = 'j';
}
// Return _ of two complex numbers
return this.COMPLEX(a - c, b - d, unit);
};
exports.IMSUM = function() {
if (!arguments.length) {
return error.value;
}
var args = utils.flatten(arguments);
// Initialize result
var result = args[0];
// Loop on all numbers
for (var i = 1; i < args.length; i++) {
// Lookup coefficients of two complex numbers
var a = this.IMREAL(result);
var b = this.IMAGINARY(result);
var c = this.IMREAL(args[i]);
var d = this.IMAGINARY(args[i]);
if (utils.anyIsError(a, b, c, d)) {
return error.value;
}
// Complute product of two complex numbers
result = this.COMPLEX(a + c, b + d);
}
// Return sum of complex numbers
return result;
};
exports.IMTAN = function(inumber) {
// Return error if inumber is a logical value
if (inumber === true || inumber === false) {
return error.value;
}
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org]
var x = exports.IMREAL(inumber);
var y = exports.IMAGINARY(inumber);
if (utils.anyIsError(x, y)) {
return error.value;
}
// Return tangent of complex number
return this.IMDIV(this.IMSIN(inumber), this.IMCOS(inumber));
};
exports.OCT2BIN = function(number, places) {
// Return error if number is not hexadecimal or contains more than ten characters (10 digits)
if (!/^[0-7]{1,10}$/.test(number)) {
return error.num;
}
// Check if number is negative
var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false;
// Convert octal number to decimal
var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8);
// Return error if number is lower than -512 or greater than 511
if (decimal < -512 || decimal > 511) {
return error.num;
}
// Ignore places and return a 10-character binary number if number is negative
if (negative) {
return '1' + text.REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2);
}
// Convert decimal number to binary
var result = decimal.toString(2);
// Return binary number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
exports.OCT2DEC = function(number) {
// Return error if number is not octal or contains more than ten characters (10 digits)
if (!/^[0-7]{1,10}$/.test(number)) {
return error.num;
}
// Convert octal number to decimal
var decimal = parseInt(number, 8);
// Return decimal number
return (decimal >= 536870912) ? decimal - 1073741824 : decimal;
};
exports.OCT2HEX = function(number, places) {
// Return error if number is not octal or contains more than ten characters (10 digits)
if (!/^[0-7]{1,10}$/.test(number)) {
return error.num;
}
// Convert octal number to decimal
var decimal = parseInt(number, 8);
// Ignore places and return a 10-character octal number if number is negative
if (decimal >= 536870912) {
return 'ff' + (decimal + 3221225472).toString(16);
}
// Convert decimal number to hexadecimal
var result = decimal.toString(16);
// Return hexadecimal number using the minimum number of characters necessary if places is undefined
if (places === undefined) {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) {
return error.value;
}
// Return error if places is negative
if (places < 0) {
return error.num;
}
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num;
}
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var SUPPORTED_FORMULAS = ['ABS', 'ACCRINT', 'ACOS', 'ACOSH', 'ACOT', 'ACOTH', 'ADD', 'AGGREGATE', 'AND', 'ARABIC', 'ARGS2ARRAY', 'ASIN', 'ASINH', 'ATAN', 'ATAN2', 'ATANH', 'AVEDEV', 'AVERAGE', 'AVERAGEA', 'AVERAGEIF', 'AVERAGEIFS', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BETADIST', 'BETAINV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.DIST.RANGE', 'BINOM.INV', 'BINOMDIST', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING', 'CEILINGMATH', 'CEILINGPRECISE', 'CHAR', 'CHISQ.DIST', 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHOOSE', 'CHOOSE', 'CLEAN', 'CODE', 'COLUMN', 'COLUMNS', 'COMBIN', 'COMBINA', 'COMPLEX', 'CONCATENATE', 'CONFIDENCE', 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'CONVERT', 'CORREL', 'COS', 'COSH', 'COT', 'COTH', 'COUNT', 'COUNTA', 'COUNTBLANK', 'COUNTIF', 'COUNTIFS', 'COUNTIN', 'COUNTUNIQUE', 'COVARIANCE.P', 'COVARIANCE.S', 'CSC', 'CSCH', 'CUMIPMT', 'CUMPRINC', 'DATE', 'DATEVALUE', 'DAY', 'DAYS', 'DAYS360', 'DB', 'DDB', 'DEC2BIN', 'DEC2HEX', 'DEC2OCT', 'DECIMAL', 'DEGREES', 'DELTA', 'DEVSQ', 'DIVIDE', 'DOLLAR', 'DOLLARDE', 'DOLLARFR', 'E', 'EDATE', 'EFFECT', 'EOMONTH', 'EQ', 'ERF', 'ERFC', 'EVEN', 'EXACT', 'EXP', 'EXPON.DIST', 'EXPONDIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT', 'FACT', 'FACTDOUBLE', 'FALSE', 'FDIST', 'FDISTRT', 'FIND', 'FINV', 'FINVRT', 'FISHER', 'FISHERINV', 'FIXED', 'FLATTEN', 'FLOOR', 'FORECAST', 'FREQUENCY', 'FV', 'FVSCHEDULE', 'GAMMA', 'GAMMA.DIST', 'GAMMA.INV', 'GAMMADIST', 'GAMMAINV', 'GAMMALN', 'GAMMALN.PRECISE', 'GAUSS', 'GCD', 'GEOMEAN', 'GESTEP', 'GROWTH', 'GTE', 'HARMEAN', 'HEX2BIN', 'HEX2DEC', 'HEX2OCT', 'HOUR', 'HTML2TEXT', 'HYPGEOM.DIST', 'HYPGEOMDIST', 'IF', 'IMABS', 'IMAGINARY', 'IMARGUMENT', 'IMCONJUGATE', 'IMCOS', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMDIV', 'IMEXP', 'IMLN', 'IMLOG10', 'IMLOG2', 'IMPOWER', 'IMPRODUCT', 'IMREAL', 'IMSEC', 'IMSECH', 'IMSIN', 'IMSINH', 'IMSQRT', 'IMSUB', 'IMSUM', 'IMTAN', 'INT', 'INTERCEPT', 'INTERVAL', 'IPMT', 'IRR', 'ISBINARY', 'ISBLANK', 'ISEVEN', 'ISLOGICAL', 'ISNONTEXT', 'ISNUMBER', 'ISODD', 'ISODD', 'ISOWEEKNUM', 'ISPMT', 'ISTEXT', 'JOIN', 'KURT', 'LARGE', 'LCM', 'LEFT', 'LEN', 'LINEST', 'LN', 'LOG', 'LOG10', 'LOGEST', 'LOGNORM.DIST', 'LOGNORM.INV', 'LOGNORMDIST', 'LOGNORMINV', 'LOWER', 'LT', 'LTE', 'MATCH', 'MAX', 'MAXA', 'MEDIAN', 'MID', 'MIN', 'MINA', 'MINUS', 'MINUTE', 'MIRR', 'MOD', 'MODE.MULT', 'MODE.SNGL', 'MODEMULT', 'MODESNGL', 'MONTH', 'MROUND', 'MULTINOMIAL', 'MULTIPLY', 'NE', 'NEGBINOM.DIST', 'NEGBINOMDIST', 'NETWORKDAYS', 'NOMINAL', 'NORM.DIST', 'NORM.INV', 'NORM.S.DIST', 'NORM.S.INV', 'NORMDIST', 'NORMINV', 'NORMSDIST', 'NORMSINV', 'NOT', 'NOW', 'NPER', 'NPV', 'NUMBERS', 'NUMERAL', 'OCT2BIN', 'OCT2DEC', 'OCT2HEX', 'ODD', 'OR', 'PDURATION', 'PEARSON', 'PERCENTILEEXC', 'PERCENTILEINC', 'PERCENTRANKEXC', 'PERCENTRANKINC', 'PERMUT', 'PERMUTATIONA', 'PHI', 'PI', 'PMT', 'POISSON.DIST', 'POISSONDIST', 'POW', 'POWER', 'PPMT', 'PROB', 'PRODUCT', 'PROPER', 'PV', 'QUARTILE.EXC', 'QUARTILE.INC', 'QUARTILEEXC', 'QUARTILEINC', 'QUOTIENT', 'RADIANS', 'RAND', 'RANDBETWEEN', 'RANK.AVG', 'RANK.EQ', 'RANKAVG', 'RANKEQ', 'RATE', 'REFERENCE', 'REGEXEXTRACT', 'REGEXMATCH', 'REGEXREPLACE', 'REPLACE', 'REPT', 'RIGHT', 'ROMAN', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'ROW', 'ROWS', 'RRI', 'RSQ', 'SEARCH', 'SEC', 'SECH', 'SECOND', 'SERIESSUM', 'SIGN', 'SIN', 'SINH', 'SKEW', 'SKEW.P', 'SKEWP', 'SLN', 'SLOPE', 'SMALL', 'SPLIT', 'SPLIT', 'SQRT', 'SQRTPI', 'STANDARDIZE', 'STDEV.P', 'STDEV.S', 'STDEVA', 'STDEVP', 'STDEVPA', 'STDEVS', 'STEYX', 'SUBSTITUTE', 'SUBTOTAL', 'SUM', 'SUMIF', 'SUMIFS', 'SUMPRODUCT', 'SUMSQ', 'SUMX2MY2', 'SUMX2PY2', 'SUMXMY2', 'SWITCH', 'SYD', 'T', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'TAN', 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TDIST2T', 'TDISTRT', 'TEXT', 'TIME', 'TIMEVALUE', 'TINV', 'TINV2T', 'TODAY', 'TRANSPOSE', 'TREND', 'TRIM', 'TRIMMEAN', 'TRUE', 'TRUNC', 'UNICHAR', 'UNICODE', 'UNIQUE', 'UPPER', 'VALUE', 'VAR.P', 'VAR.S', 'VARA', 'VARP', 'VARPA', 'VARS', 'WEEKDAY', 'WEEKNUM', 'WEIBULL.DIST', 'WEIBULLDIST', 'WORKDAY', 'XIRR', 'XNPV', 'XOR', 'YEAR', 'YEARFRAC'];
exports['default'] = SUPPORTED_FORMULAS;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.rowLabelToIndex = rowLabelToIndex;
exports.rowIndexToLabel = rowIndexToLabel;
exports.columnLabelToIndex = columnLabelToIndex;
exports.columnIndexToLabel = columnIndexToLabel;
exports.extractLabel = extractLabel;
exports.toLabel = toLabel;
/**
* Convert row label to index.
*
* @param {String} label Row label (eq. '1', '5')
* @returns {Number} Returns -1 if label is not recognized otherwise proper row index.
*/
function rowLabelToIndex(label) {
var result = parseInt(label, 10);
if (isNaN(result)) {
result = -1;
} else {
result = Math.max(result - 1, -1);
}
return result;
}
/**
* Convert row index to label.
*
* @param {Number} row Row index.
* @returns {String} Returns row label (eq. '1', '7').
*/
function rowIndexToLabel(row) {
var result = '';
if (row >= 0) {
result = '' + (row + 1);
}
return result;
}
var COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var COLUMN_LABEL_BASE_LENGTH = COLUMN_LABEL_BASE.length;
/**
* Convert column label to index.
*
* @param {String} label Column label (eq. 'ABB', 'CNQ')
* @returns {Number} Returns -1 if label is not recognized otherwise proper column index.
*/
function columnLabelToIndex(label) {
var result = 0;
if (typeof label === 'string') {
label = label.toUpperCase();
for (var i = 0, j = label.length - 1; i < label.length; i += 1, j -= 1) {
result += Math.pow(COLUMN_LABEL_BASE_LENGTH, j) * (COLUMN_LABEL_BASE.indexOf(label[i]) + 1);
}
}
--result;
return result;
}
/**
* Convert column index to label.
*
* @param {Number} column Column index.
* @returns {String} Returns column label (eq. 'ABB', 'CNQ').
*/
function columnIndexToLabel(column) {
var result = '';
while (column >= 0) {
result = String.fromCharCode(column % COLUMN_LABEL_BASE_LENGTH + 97) + result;
column = Math.floor(column / COLUMN_LABEL_BASE_LENGTH) - 1;
}
return result.toUpperCase();
}
var LABEL_EXTRACT_REGEXP = /^([$])?([A-Za-z]+)([$])?([0-9]+)$/;
/**
* Extract cell coordinates.
*
* @param {String} label Cell coordinates (eq. 'A1', '$B6', '$N$98').
* @returns {Array} Returns an array of objects.
*/
function extractLabel(label) {
if (typeof label !== 'string' || !LABEL_EXTRACT_REGEXP.test(label)) {
return [];
}
var _label$toUpperCase$ma = label.toUpperCase().match(LABEL_EXTRACT_REGEXP),
columnAbs = _label$toUpperCase$ma[1],
column = _label$toUpperCase$ma[2],
rowAbs = _label$toUpperCase$ma[3],
row = _label$toUpperCase$ma[4];
return [{
index: rowLabelToIndex(row),
label: row,
isAbsolute: rowAbs === '$'
}, {
index: columnLabelToIndex(column),
label: column,
isAbsolute: columnAbs === '$'
}];
}
/**
* Convert row and column indexes into cell label.
*
* @param {Object} row Object with `index` and `isAbsolute` properties.
* @param {Object} column Object with `index` and `isAbsolute` properties.
* @returns {String} Returns cell label.
*/
function toLabel(row, column) {
var rowLabel = (row.isAbsolute ? '$' : '') + rowIndexToLabel(row.index);
var columnLabel = (column.isAbsolute ? '$' : '') + columnIndexToLabel(column.index);
return columnLabel + rowLabel;
}
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.rowLabelToIndex = exports.rowIndexToLabel = exports.columnLabelToIndex = exports.columnIndexToLabel = exports.toLabel = exports.extractLabel = exports.error = exports.Parser = exports.ERROR_VALUE = exports.ERROR_REF = exports.ERROR_NUM = exports.ERROR_NULL = exports.ERROR_NOT_AVAILABLE = exports.ERROR_NAME = exports.ERROR_DIV_ZERO = exports.ERROR = exports.SUPPORTED_FORMULAS = undefined;
var _parser = __webpack_require__(17);
var _parser2 = _interopRequireDefault(_parser);
var _supportedFormulas = __webpack_require__(14);
var _supportedFormulas2 = _interopRequireDefault(_supportedFormulas);
var _error = __webpack_require__(2);
var _error2 = _interopRequireDefault(_error);
var _cell = __webpack_require__(15);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
exports.SUPPORTED_FORMULAS = _supportedFormulas2['default'];
exports.ERROR = _error.ERROR;
exports.ERROR_DIV_ZERO = _error.ERROR_DIV_ZERO;
exports.ERROR_NAME = _error.ERROR_NAME;
exports.ERROR_NOT_AVAILABLE = _error.ERROR_NOT_AVAILABLE;
exports.ERROR_NULL = _error.ERROR_NULL;
exports.ERROR_NUM = _error.ERROR_NUM;
exports.ERROR_REF = _error.ERROR_REF;
exports.ERROR_VALUE = _error.ERROR_VALUE;
exports.Parser = _parser2['default'];
exports.error = _error2['default'];
exports.extractLabel = _cell.extractLabel;
exports.toLabel = _cell.toLabel;
exports.columnIndexToLabel = _cell.columnIndexToLabel;
exports.columnLabelToIndex = _cell.columnLabelToIndex;
exports.rowIndexToLabel = _cell.rowIndexToLabel;
exports.rowLabelToIndex = _cell.rowLabelToIndex;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _tinyEmitter = __webpack_require__(18);
var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);
var _evaluateByOperator = __webpack_require__(19);
var _evaluateByOperator2 = _interopRequireDefault(_evaluateByOperator);
var _grammarParser = __webpack_require__(41);
var _string = __webpack_require__(43);
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var _error2 = _interopRequireDefault(_error);
var _cell = __webpack_require__(15);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* @class Parser
*/
var Parser = function (_Emitter) {
_inherits(Parser, _Emitter);
function Parser() {
_classCallCheck(this, Parser);
var _this = _possibleConstructorReturn(this, _Emitter.call(this));
_this.parser = new _grammarParser.Parser();
_this.parser.yy = {
toNumber: _number.toNumber,
trimEdges: _string.trimEdges,
invertNumber: _number.invertNumber,
throwError: function throwError(errorName) {
return _this._throwError(errorName);
},
callVariable: function callVariable(variable) {
return _this._callVariable(variable);
},
evaluateByOperator: _evaluateByOperator2['default'],
callFunction: function callFunction(name, params) {
return _this._callFunction(name, params);
},
cellValue: function cellValue(value) {
return _this._callCellValue(value);
},
rangeValue: function rangeValue(start, end) {
return _this._callRangeValue(start, end);
}
};
_this.variables = Object.create(null);
_this.functions = Object.create(null);
_this.setVariable('TRUE', true).setVariable('FALSE', false).setVariable('NULL', null);
return _this;
}
/**
* Parse formula expression.
*
* @param {String} expression to parse.
* @return {*} Returns an object with tow properties `error` and `result`.
*/
Parser.prototype.parse = function parse(expression) {
var result = null;
var error = null;
try {
if (expression === '') {
result = '';
} else {
result = this.parser.parse(expression);
}
} catch (ex) {
var message = (0, _error2['default'])(ex.message);
if (message) {
error = message;
} else {
error = (0, _error2['default'])(_error.ERROR);
}
}
if (result instanceof Error) {
error = (0, _error2['default'])(result.message) || (0, _error2['default'])(_error.ERROR);
result = null;
}
return {
error: error,
result: result
};
};
/**
* Set predefined variable name which can be visible while parsing formula expression.
*
* @param {String} name Variable name.
* @param {*} value Variable value.
* @returns {Parser}
*/
Parser.prototype.setVariable = function setVariable(name, value) {
this.variables[name] = value;
return this;
};
/**
* Get variable name.
*
* @param {String} name Variable name.
* @returns {*}
*/
Parser.prototype.getVariable = function getVariable(name) {
return this.variables[name];
};
/**
* Retrieve variable value by its name.
*
* @param name Variable name.
* @returns {*}
* @private
*/
Parser.prototype._callVariable = function _callVariable(name) {
var value = this.getVariable(name);
this.emit('callVariable', name, function (newValue) {
if (newValue !== void 0) {
value = newValue;
}
});
if (value === void 0) {
throw Error(_error.ERROR_NAME);
}
return value;
};
/**
* Set custom function which can be visible while parsing formula expression.
*
* @param {String} name Custom function name.
* @param {Function} fn Custom function.
* @returns {Parser}
*/
Parser.prototype.setFunction = function setFunction(name, fn) {
this.functions[name] = fn;
return this;
};
/**
* Get custom function.
*
* @param {String} name Custom function name.
* @returns {*}
*/
Parser.prototype.getFunction = function getFunction(name) {
return this.functions[name];
};
/**
* Call function with provided params.
*
* @param name Function name.
* @param params Function params.
* @returns {*}
* @private
*/
Parser.prototype._callFunction = function _callFunction(name) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var fn = this.getFunction(name);
var value = void 0;
if (fn) {
value = fn(params);
}
this.emit('callFunction', name, params, function (newValue) {
if (newValue !== void 0) {
value = newValue;
}
});
return value === void 0 ? (0, _evaluateByOperator2['default'])(name, params) : value;
};
/**
* Retrieve value by its label (`B3`, `B$3`, `B$3`, `$B$3`).
*
* @param {String} label Coordinates.
* @returns {*}
* @private
*/
Parser.prototype._callCellValue = function _callCellValue(label) {
label = label.toUpperCase();
var _extractLabel = (0, _cell.extractLabel)(label),
row = _extractLabel[0],
column = _extractLabel[1];
var value = void 0;
this.emit('callCellValue', { label: label, row: row, column: column }, function (_value) {
value = _value;
});
return value;
};
/**
* Retrieve value by its label (`B3:A1`, `B$3:A1`, `B$3:$A1`, `$B$3:A$1`).
*
* @param {String} startLabel Coordinates of the first cell.
* @param {String} endLabel Coordinates of the last cell.
* @returns {Array} Returns an array of mixed values.
* @private
*/
Parser.prototype._callRangeValue = function _callRangeValue(startLabel, endLabel) {
startLabel = startLabel.toUpperCase();
endLabel = endLabel.toUpperCase();
var _extractLabel2 = (0, _cell.extractLabel)(startLabel),
startRow = _extractLabel2[0],
startColumn = _extractLabel2[1];
var _extractLabel3 = (0, _cell.extractLabel)(endLabel),
endRow = _extractLabel3[0],
endColumn = _extractLabel3[1];
var startCell = {};
var endCell = {};
if (startRow.index <= endRow.index) {
startCell.row = startRow;
endCell.row = endRow;
} else {
startCell.row = endRow;
endCell.row = startRow;
}
if (startColumn.index <= endColumn.index) {
startCell.column = startColumn;
endCell.column = endColumn;
} else {
startCell.column = endColumn;
endCell.column = startColumn;
}
startCell.label = (0, _cell.toLabel)(startCell.row, startCell.column);
endCell.label = (0, _cell.toLabel)(endCell.row, endCell.column);
var value = [];
this.emit('callRangeValue', startCell, endCell, function () {
var _value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
value = _value;
});
return value;
};
/**
* Try to throw error by its name.
*
* @param {String} errorName Error name.
* @returns {String}
* @private
*/
Parser.prototype._throwError = function _throwError(errorName) {
if ((0, _error.isValidStrict)(errorName)) {
throw Error(errorName);
}
throw Error(_error.ERROR);
};
return Parser;
}(_tinyEmitter2['default']);
exports['default'] = Parser;
/***/ }),
/* 18 */
/***/ (function(module, exports) {
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);
};
listener._ = callback
return this.on(name, listener, ctx);
},
emit: function (name) {
var data = [].slice.call(arguments, 1);
var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
var i = 0;
var len = evtArr.length;
for (i; i < len; i++) {
evtArr[i].fn.apply(evtArr[i].ctx, data);
}
return this;
},
off: function (name, callback) {
var e = this.e || (this.e = {});
var evts = e[name];
var liveEvents = [];
if (evts && callback) {
for (var i = 0, len = evts.length; i < len; i++) {
if (evts[i].fn !== callback && evts[i].fn._ !== callback)
liveEvents.push(evts[i]);
}
}
// Remove event from queue to prevent memory leak
// Suggested by https://github.com/lazd
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
(liveEvents.length)
? e[name] = liveEvents
: delete e[name];
return this;
}
};
module.exports = E;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = evaluateByOperator;
exports.registerOperation = registerOperation;
var _add = __webpack_require__(20);
var _add2 = _interopRequireDefault(_add);
var _ampersand = __webpack_require__(21);
var _ampersand2 = _interopRequireDefault(_ampersand);
var _divide = __webpack_require__(22);
var _divide2 = _interopRequireDefault(_divide);
var _equal = __webpack_require__(23);
var _equal2 = _interopRequireDefault(_equal);
var _formulaFunction = __webpack_require__(24);
var _formulaFunction2 = _interopRequireDefault(_formulaFunction);
var _greaterThan = __webpack_require__(33);
var _greaterThan2 = _interopRequireDefault(_greaterThan);
var _greaterThanOrEqual = __webpack_require__(34);
var _greaterThanOrEqual2 = _interopRequireDefault(_greaterThanOrEqual);
var _lessThan = __webpack_require__(35);
var _lessThan2 = _interopRequireDefault(_lessThan);
var _lessThanOrEqual = __webpack_require__(36);
var _lessThanOrEqual2 = _interopRequireDefault(_lessThanOrEqual);
var _minus = __webpack_require__(37);
var _minus2 = _interopRequireDefault(_minus);
var _multiply = __webpack_require__(38);
var _multiply2 = _interopRequireDefault(_multiply);
var _notEqual = __webpack_require__(39);
var _notEqual2 = _interopRequireDefault(_notEqual);
var _power = __webpack_require__(40);
var _power2 = _interopRequireDefault(_power);
var _error = __webpack_require__(2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/* eslint-disable import/no-named-as-default-member */
var availableOperators = Object.create(null);
/**
* Evaluate values by operator id.git
*
* @param {String} operator Operator id.
* @param {Array} [params=[]] Arguments to evaluate.
* @returns {*}
*/
function evaluateByOperator(operator) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
operator = operator.toUpperCase();
if (!availableOperators[operator]) {
throw Error(_error.ERROR_NAME);
}
return availableOperators[operator].apply(availableOperators, params);
}
/**
* Register operator.
*
* @param {String|Array} symbol Symbol to register.
* @param {Function} func Logic to register for this symbol.
*/
function registerOperation(symbol, func) {
if (!Array.isArray(symbol)) {
symbol = [symbol.toUpperCase()];
}
symbol.forEach(function (s) {
if (func.isFactory) {
availableOperators[s] = func(s);
} else {
availableOperators[s] = func;
}
});
}
registerOperation(_add2['default'].SYMBOL, _add2['default']);
registerOperation(_ampersand2['default'].SYMBOL, _ampersand2['default']);
registerOperation(_divide2['default'].SYMBOL, _divide2['default']);
registerOperation(_equal2['default'].SYMBOL, _equal2['default']);
registerOperation(_power2['default'].SYMBOL, _power2['default']);
registerOperation(_formulaFunction2['default'].SYMBOL, _formulaFunction2['default']);
registerOperation(_greaterThan2['default'].SYMBOL, _greaterThan2['default']);
registerOperation(_greaterThanOrEqual2['default'].SYMBOL, _greaterThanOrEqual2['default']);
registerOperation(_lessThan2['default'].SYMBOL, _lessThan2['default']);
registerOperation(_lessThanOrEqual2['default'].SYMBOL, _lessThanOrEqual2['default']);
registerOperation(_multiply2['default'].SYMBOL, _multiply2['default']);
registerOperation(_notEqual2['default'].SYMBOL, _notEqual2['default']);
registerOperation(_minus2['default'].SYMBOL, _minus2['default']);
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var SYMBOL = exports.SYMBOL = '+';
function func(first) {
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var result = rest.reduce(function (acc, value) {
return acc + (0, _number.toNumber)(value);
}, (0, _number.toNumber)(first));
if (isNaN(result)) {
throw Error(_error.ERROR_VALUE);
}
return result;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '&';
function func() {
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
return params.reduce(function (acc, value) {
return acc + value.toString();
}, '');
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var SYMBOL = exports.SYMBOL = '/';
function func(first) {
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var result = rest.reduce(function (acc, value) {
return acc / (0, _number.toNumber)(value);
}, (0, _number.toNumber)(first));
if (result === Infinity) {
throw Error(_error.ERROR_DIV_ZERO);
}
if (isNaN(result)) {
throw Error(_error.ERROR_VALUE);
}
return result;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '=';
function func(exp1, exp2) {
return exp1 === exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _formulajs = __webpack_require__(25);
var formulajs = _interopRequireWildcard(_formulajs);
var _supportedFormulas = __webpack_require__(14);
var _supportedFormulas2 = _interopRequireDefault(_supportedFormulas);
var _error = __webpack_require__(2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var SYMBOL = exports.SYMBOL = _supportedFormulas2['default'];
function func(symbol) {
return function __formulaFunction() {
symbol = symbol.toUpperCase();
var symbolParts = symbol.split('.');
var foundFormula = false;
var result = void 0;
if (symbolParts.length === 1) {
if (formulajs[symbolParts[0]]) {
foundFormula = true;
result = formulajs[symbolParts[0]].apply(formulajs, arguments);
}
} else {
var length = symbolParts.length;
var index = 0;
var nestedFormula = formulajs;
while (index < length) {
nestedFormula = nestedFormula[symbolParts[index]];
index++;
if (!nestedFormula) {
nestedFormula = null;
break;
}
}
if (nestedFormula) {
foundFormula = true;
result = nestedFormula.apply(undefined, arguments);
}
}
if (!foundFormula) {
throw Error(_error.ERROR_NAME);
}
return result;
};
}
func.isFactory = true;
func.SYMBOL = SYMBOL;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var categories = [
__webpack_require__(26),
__webpack_require__(29),
__webpack_require__(13),
__webpack_require__(30),
__webpack_require__(4),
__webpack_require__(6),
__webpack_require__(8),
__webpack_require__(31),
__webpack_require__(7),
__webpack_require__(32),
__webpack_require__(5),
__webpack_require__(12)
];
for (var c in categories) {
var category = categories[c];
for (var f in category) {
exports[f] = exports[f] || category[f];
}
}
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var mathTrig = __webpack_require__(4);
var statistical = __webpack_require__(5);
var engineering = __webpack_require__(13);
var dateTime = __webpack_require__(8);
function set(fn, root) {
if (root) {
for (var i in root) {
fn[i] = root[i];
}
}
return fn;
}
exports.BETADIST = statistical.BETA.DIST;
exports.BETAINV = statistical.BETA.INV;
exports.BINOMDIST = statistical.BINOM.DIST;
exports.CEILING = exports.ISOCEILING = set(mathTrig.CEILING.MATH, mathTrig.CEILING);
exports.CEILINGMATH = mathTrig.CEILING.MATH;
exports.CEILINGPRECISE = mathTrig.CEILING.PRECISE;
exports.CHIDIST = statistical.CHISQ.DIST;
exports.CHIDISTRT = statistical.CHISQ.DIST.RT;
exports.CHIINV = statistical.CHISQ.INV;
exports.CHIINVRT = statistical.CHISQ.INV.RT;
exports.CHITEST = statistical.CHISQ.TEST;
exports.CONFIDENCE = set(statistical.CONFIDENCE.NORM, statistical.CONFIDENCE);
exports.COVAR = statistical.COVARIANCE.P;
exports.COVARIANCEP = statistical.COVARIANCE.P;
exports.COVARIANCES = statistical.COVARIANCE.S;
exports.CRITBINOM = statistical.BINOM.INV;
exports.EXPONDIST = statistical.EXPON.DIST;
exports.ERFCPRECISE = engineering.ERFC.PRECISE;
exports.ERFPRECISE = engineering.ERF.PRECISE;
exports.FDIST = statistical.F.DIST;
exports.FDISTRT = statistical.F.DIST.RT;
exports.FINVRT = statistical.F.INV.RT;
exports.FINV = statistical.F.INV;
exports.FLOOR = set(mathTrig.FLOOR.MATH, mathTrig.FLOOR);
exports.FLOORMATH = mathTrig.FLOOR.MATH;
exports.FLOORPRECISE = mathTrig.FLOOR.PRECISE;
exports.FTEST = statistical.F.TEST;
exports.GAMMADIST = statistical.GAMMA.DIST;
exports.GAMMAINV = statistical.GAMMA.INV;
exports.GAMMALNPRECISE = statistical.GAMMALN.PRECISE;
exports.HYPGEOMDIST = statistical.HYPGEOM.DIST;
exports.LOGINV = statistical.LOGNORM.INV;
exports.LOGNORMINV = statistical.LOGNORM.INV;
exports.LOGNORMDIST = statistical.LOGNORM.DIST;
exports.MODE = set(statistical.MODE.SNGL, statistical.MODE);
exports.MODEMULT = statistical.MODE.MULT;
exports.MODESNGL = statistical.MODE.SNGL;
exports.NEGBINOMDIST = statistical.NEGBINOM.DIST;
exports.NETWORKDAYSINTL = dateTime.NETWORKDAYS.INTL;
exports.NORMDIST = statistical.NORM.DIST;
exports.NORMINV = statistical.NORM.INV;
exports.NORMSDIST = statistical.NORM.S.DIST;
exports.NORMSINV = statistical.NORM.S.INV;
exports.PERCENTILE = set(statistical.PERCENTILE.EXC, statistical.PERCENTILE);
exports.PERCENTILEEXC = statistical.PERCENTILE.EXC;
exports.PERCENTILEINC = statistical.PERCENTILE.INC;
exports.PERCENTRANK = set(statistical.PERCENTRANK.INC, statistical.PERCENTRANK);
exports.PERCENTRANKEXC = statistical.PERCENTRANK.EXC;
exports.PERCENTRANKINC = statistical.PERCENTRANK.INC;
exports.POISSON = set(statistical.POISSON.DIST, statistical.POISSON);
exports.POISSONDIST = statistical.POISSON.DIST;
exports.QUARTILE = set(statistical.QUARTILE.INC, statistical.QUARTILE);
exports.QUARTILEEXC = statistical.QUARTILE.EXC;
exports.QUARTILEINC = statistical.QUARTILE.INC;
exports.RANK = set(statistical.RANK.EQ, statistical.RANK);
exports.RANKAVG = statistical.RANK.AVG;
exports.RANKEQ = statistical.RANK.EQ;
exports.SKEWP = statistical.SKEW.P;
exports.STDEV = set(statistical.STDEV.S, statistical.STDEV);
exports.STDEVP = statistical.STDEV.P;
exports.STDEVS = statistical.STDEV.S;
exports.TDIST = statistical.T.DIST;
exports.TDISTRT = statistical.T.DIST.RT;
exports.TINV = statistical.T.INV;
exports.TTEST = statistical.T.TEST;
exports.VAR = set(statistical.VAR.S, statistical.VAR);
exports.VARP = statistical.VAR.P;
exports.VARS = statistical.VAR.S;
exports.WEIBULL = set(statistical.WEIBULL.DIST, statistical.WEIBULL);
exports.WEIBULLDIST = statistical.WEIBULL.DIST;
exports.WORKDAYINTL = dateTime.WORKDAY.INTL;
exports.ZTEST = statistical.Z.TEST;
/***/ }),
/* 27 */
/***/ (function(module, exports) {
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var M = Math;
function _horner(arr, v) { return arr.reduce(function(z,w){return v * z + w;},0); };
function _bessel_iter(x, n, f0, f1, sign) {
if(!sign) sign = -1;
var tdx = 2 / x, f2;
if(n === 0) return f0;
if(n === 1) return f1;
for(var o = 1; o != n; ++o) {
f2 = f1 * o * tdx + sign * f0;
f0 = f1; f1 = f2;
}
return f1;
}
function _bessel_wrap(bessel0, bessel1, name, nonzero, sign) {
return function bessel(x,n) {
if(n === 0) return bessel0(x);
if(n === 1) return bessel1(x);
if(n < 0) throw name + ': Order (' + n + ') must be nonnegative';
if(nonzero == 1 && x === 0) throw name + ': Undefined when x == 0';
if(nonzero == 2 && x <= 0) throw name + ': Undefined when x <= 0';
var b0 = bessel0(x), b1 = bessel1(x);
return _bessel_iter(x, n, b0, b1, sign);
};
}
var besselj = (function() {
var b0_a1a = [57568490574.0,-13362590354.0,651619640.7,-11214424.18,77392.33017,-184.9052456].reverse();
var b0_a2a = [57568490411.0,1029532985.0,9494680.718,59272.64853,267.8532712,1.0].reverse();
var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse();
var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934935152e-7].reverse();
var W = 0.636619772; // 2 / Math.PI
function bessel0(x) {
var a, a1, a2, y = x * x, xx = M.abs(x) - 0.785398164;
if(M.abs(x) < 8) {
a1 = _horner(b0_a1a, y);
a2 = _horner(b0_a2a, y);
a = a1/a2;
}
else {
y = 64 / y;
a1 = _horner(b0_a1b, y);
a2 = _horner(b0_a2b, y);
a = M.sqrt(W/M.abs(x))*(M.cos(xx)*a1-M.sin(xx)*a2*8/M.abs(x));
}
return a;
}
var b1_a1a = [72362614232.0,-7895059235.0,242396853.1,-2972611.439, 15704.48260, -30.16036606].reverse();
var b1_a2a = [144725228442.0, 2300535178.0, 18583304.74, 99447.43394, 376.9991397, 1.0].reverse();
var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse();
var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse();
function bessel1(x) {
var a, a1, a2, y = x*x, xx = M.abs(x) - 2.356194491;
if(Math.abs(x)< 8) {
a1 = x*_horner(b1_a1a, y);
a2 = _horner(b1_a2a, y);
a = a1 / a2;
} else {
y = 64 / y;
a1=_horner(b1_a1b, y);
a2=_horner(b1_a2b, y);
a=M.sqrt(W/M.abs(x))*(M.cos(xx)*a1-M.sin(xx)*a2*8/M.abs(x));
if(x < 0) a = -a;
}
return a;
}
return function besselj(x, n) {
n = Math.round(n);
if(n === 0) return bessel0(M.abs(x));
if(n === 1) return bessel1(M.abs(x));
if(n < 0) throw 'BESSELJ: Order (' + n + ') must be nonnegative';
if(M.abs(x) === 0) return 0;
var ret, j, tox = 2 / M.abs(x), m, jsum, sum, bjp, bj, bjm;
if(M.abs(x) > n) {
ret = _bessel_iter(x, n, bessel0(M.abs(x)), bessel1(M.abs(x)),-1);
} else {
m=2*M.floor((n+M.floor(M.sqrt(40*n)))/2);
jsum=0;
bjp=ret=sum=0.0;
bj=1.0;
for (j=m;j>0;j--) {
bjm=j*tox*bj-bjp;
bjp=bj;
bj=bjm;
if (M.abs(bj) > 1E10) {
bj *= 1E-10;
bjp *= 1E-10;
ret *= 1E-10;
sum *= 1E-10;
}
if (jsum) sum += bj;
jsum=!jsum;
if (j == n) ret=bjp;
}
sum=2.0*sum-bj;
ret /= sum;
}
return x < 0 && (n%2) ? -ret : ret;
};
})();
var bessely = (function() {
var b0_a1a = [-2957821389.0, 7062834065.0, -512359803.6, 10879881.29, -86327.92757, 228.4622733].reverse();
var b0_a2a = [40076544269.0, 745249964.8, 7189466.438, 47447.26470, 226.1030244, 1.0].reverse();
var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse();
var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934945152e-7].reverse();
var W = 0.636619772;
function bessel0(x) {
var a, a1, a2, y = x * x, xx = x - 0.785398164;
if(x < 8) {
a1 = _horner(b0_a1a, y);
a2 = _horner(b0_a2a, y);
a = a1/a2 + W * besselj(x,0) * M.log(x);
} else {
y = 64 / y;
a1 = _horner(b0_a1b, y);
a2 = _horner(b0_a2b, y);
a = M.sqrt(W/x)*(M.sin(xx)*a1+M.cos(xx)*a2*8/x);
}
return a;
}
var b1_a1a = [-0.4900604943e13, 0.1275274390e13, -0.5153438139e11, 0.7349264551e9, -0.4237922726e7, 0.8511937935e4].reverse();
var b1_a2a = [0.2499580570e14, 0.4244419664e12, 0.3733650367e10, 0.2245904002e8, 0.1020426050e6, 0.3549632885e3, 1].reverse();
var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse();
var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse();
function bessel1(x) {
var a, a1, a2, y = x*x, xx = x - 2.356194491;
if(x < 8) {
a1 = x*_horner(b1_a1a, y);
a2 = _horner(b1_a2a, y);
a = a1/a2 + W * (besselj(x,1) * M.log(x) - 1 / x);
} else {
y = 64 / y;
a1=_horner(b1_a1b, y);
a2=_horner(b1_a2b, y);
a=M.sqrt(W/x)*(M.sin(xx)*a1+M.cos(xx)*a2*8/x);
}
return a;
}
return _bessel_wrap(bessel0, bessel1, 'BESSELY', 1, -1);
})();
var besseli = (function() {
var b0_a = [1.0, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.360768e-1, 0.45813e-2].reverse();
var b0_b = [0.39894228, 0.1328592e-1, 0.225319e-2, -0.157565e-2, 0.916281e-2, -0.2057706e-1, 0.2635537e-1, -0.1647633e-1, 0.392377e-2].reverse();
function bessel0(x) {
if(x <= 3.75) return _horner(b0_a, x*x/(3.75*3.75));
return M.exp(M.abs(x))/M.sqrt(M.abs(x))*_horner(b0_b, 3.75/M.abs(x));
}
var b1_a = [0.5, 0.87890594, 0.51498869, 0.15084934, 0.2658733e-1, 0.301532e-2, 0.32411e-3].reverse();
var b1_b = [0.39894228, -0.3988024e-1, -0.362018e-2, 0.163801e-2, -0.1031555e-1, 0.2282967e-1, -0.2895312e-1, 0.1787654e-1, -0.420059e-2].reverse();
function bessel1(x) {
if(x < 3.75) return x * _horner(b1_a, x*x/(3.75*3.75));
return (x < 0 ? -1 : 1) * M.exp(M.abs(x))/M.sqrt(M.abs(x))*_horner(b1_b, 3.75/M.abs(x));
}
return function besseli(x, n) {
n = Math.round(n);
if(n === 0) return bessel0(x);
if(n == 1) return bessel1(x);
if(n < 0) throw 'BESSELI Order (' + n + ') must be nonnegative';
if(M.abs(x) === 0) return 0;
var ret, j, tox = 2 / M.abs(x), m, bip, bi, bim;
m=2*M.round((n+M.round(M.sqrt(40*n)))/2);
bip=ret=0.0;
bi=1.0;
for (j=m;j>0;j--) {
bim=j*tox*bi + bip;
bip=bi; bi=bim;
if (M.abs(bi) > 1E10) {
bi *= 1E-10;
bip *= 1E-10;
ret *= 1E-10;
}
if(j == n) ret = bip;
}
ret *= besseli(x, 0) / bi;
return x < 0 && (n%2) ? -ret : ret;
};
})();
var besselk = (function() {
var b0_a = [-0.57721566, 0.42278420, 0.23069756, 0.3488590e-1, 0.262698e-2, 0.10750e-3, 0.74e-5].reverse();
var b0_b = [1.25331414, -0.7832358e-1, 0.2189568e-1, -0.1062446e-1, 0.587872e-2, -0.251540e-2, 0.53208e-3].reverse();
function bessel0(x) {
if(x <= 2) return -M.log(x/2)*besseli(x,0) + _horner(b0_a, x*x/4);
return M.exp(-x)/M.sqrt(x)*_horner(b0_b, 2/x);
}
var b1_a = [1.0, 0.15443144, -0.67278579, -0.18156897, -0.1919402e-1, -0.110404e-2, -0.4686e-4].reverse();
var b1_b = [1.25331414, 0.23498619, -0.3655620e-1, 0.1504268e-1, -0.780353e-2, 0.325614e-2, -0.68245e-3].reverse();
function bessel1(x) {
if(x <= 2) return M.log(x/2)*besseli(x,1) + (1/x)*_horner(b1_a, x*x/4);
return M.exp(-x)/M.sqrt(x)*_horner(b1_b, 2/x);
}
return _bessel_wrap(bessel0, bessel1, 'BESSELK', 2, 1);
})();
if(true) {
exports.besselj = besselj;
exports.bessely = bessely;
exports.besseli = besseli;
exports.besselk = besselk;
}
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var stats = __webpack_require__(5);
var maths = __webpack_require__(4);
var utils = __webpack_require__(1);
function compact(array) {
var result = [];
utils.arrayEach(array, function(value) {
if (value) {
result.push(value);
}
});
return result;
}
exports.FINDFIELD = function(database, title) {
var index = null;
utils.arrayEach(database, function(value, i) {
if (value[0] === title) {
index = i;
return false;
}
});
// Return error if the input field title is incorrect
if (index == null) {
return error.value;
}
return index;
};
function findResultIndex(database, criterias) {
var matches = {};
for (var i = 1; i < database[0].length; ++i) {
matches[i] = true;
}
var maxCriteriaLength = criterias[0].length;
for (i = 1; i < criterias.length; ++i) {
if (criterias[i].length > maxCriteriaLength) {
maxCriteriaLength = criterias[i].length;
}
}
for (var k = 1; k < database.length; ++k) {
for (var l = 1; l < database[k].length; ++l) {
var currentCriteriaResult = false;
var hasMatchingCriteria = false;
for (var j = 0; j < criterias.length; ++j) {
var criteria = criterias[j];
if (criteria.length < maxCriteriaLength) {
continue;
}
var criteriaField = criteria[0];
if (database[k][0] !== criteriaField) {
continue;
}
hasMatchingCriteria = true;
for (var p = 1; p < criteria.length; ++p) {
currentCriteriaResult = currentCriteriaResult || eval(database[k][l] + criteria[p]); // jshint ignore:line
}
}
if (hasMatchingCriteria) {
matches[l] = matches[l] && currentCriteriaResult;
}
}
}
var result = [];
for (var n = 0; n < database[0].length; ++n) {
if (matches[n]) {
result.push(n - 1);
}
}
return result;
}
// Database functions
exports.DAVERAGE = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var sum = 0;
utils.arrayEach(resultIndexes, function(value) {
sum += targetFields[value];
});
return resultIndexes.length === 0 ? error.div0 : sum / resultIndexes.length;
};
exports.DCOUNT = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
return stats.COUNT(targetValues);
};
exports.DCOUNTA = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
return stats.COUNTA(targetValues);
};
exports.DGET = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
// Return error if no record meets the criteria
if (resultIndexes.length === 0) {
return error.value;
}
// Returns the #NUM! error value because more than one record meets the
// criteria
if (resultIndexes.length > 1) {
return error.num;
}
return targetFields[resultIndexes[0]];
};
exports.DMAX = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var maxValue = targetFields[resultIndexes[0]];
utils.arrayEach(resultIndexes, function(value) {
if (maxValue < targetFields[value]) {
maxValue = targetFields[value];
}
});
return maxValue;
};
exports.DMIN = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var minValue = targetFields[resultIndexes[0]];
utils.arrayEach(resultIndexes, function(value) {
if (minValue > targetFields[value]) {
minValue = targetFields[value];
}
});
return minValue;
};
exports.DPRODUCT = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
targetValues = compact(targetValues);
var result = 1;
utils.arrayEach(targetValues, function(value) {
result *= value;
});
return result;
};
exports.DSTDEV = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
targetValues = compact(targetValues);
return stats.STDEV.S(targetValues);
};
exports.DSTDEVP = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
targetValues = compact(targetValues);
return stats.STDEV.P(targetValues);
};
exports.DSUM = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
return maths.SUM(targetValues);
};
exports.DVAR = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
return stats.VAR.S(targetValues);
};
exports.DVARP = function(database, field, criteria) {
// Return error if field is not a number and not a string
if (isNaN(field) && (typeof field !== "string")) {
return error.value;
}
var resultIndexes = findResultIndex(database, criteria);
var targetFields = [];
if (typeof field === "string") {
var index = exports.FINDFIELD(database, field);
targetFields = utils.rest(database[index]);
} else {
targetFields = utils.rest(database[field]);
}
var targetValues = [];
utils.arrayEach(resultIndexes, function(value) {
targetValues.push(targetFields[value]);
});
return stats.VAR.P(targetValues);
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var utils = __webpack_require__(1);
var information = __webpack_require__(7);
exports.AND = function() {
var args = utils.flatten(arguments);
var result = true;
for (var i = 0; i < args.length; i++) {
if (!args[i]) {
result = false;
}
}
return result;
};
exports.CHOOSE = function() {
if (arguments.length < 2) {
return error.na;
}
var index = arguments[0];
if (index < 1 || index > 254) {
return error.value;
}
if (arguments.length < index + 1) {
return error.value;
}
return arguments[index];
};
exports.FALSE = function() {
return false;
};
exports.IF = function(test, then_value, otherwise_value) {
return test ? then_value : otherwise_value;
};
exports.IFERROR = function(value, valueIfError) {
if (information.ISERROR(value)) {
return valueIfError;
}
return value;
};
exports.IFNA = function(value, value_if_na) {
return value === error.na ? value_if_na : value;
};
exports.NOT = function(logical) {
return !logical;
};
exports.OR = function() {
var args = utils.flatten(arguments);
var result = false;
for (var i = 0; i < args.length; i++) {
if (args[i]) {
result = true;
}
}
return result;
};
exports.TRUE = function() {
return true;
};
exports.XOR = function() {
var args = utils.flatten(arguments);
var result = 0;
for (var i = 0; i < args.length; i++) {
if (args[i]) {
result++;
}
}
return (Math.floor(Math.abs(result)) & 1) ? true : false;
};
exports.SWITCH = function () {
var result;
if (arguments.length > 0) {
var targetValue = arguments[0];
var argc = arguments.length - 1;
var switchCount = Math.floor(argc / 2);
var switchSatisfied = false;
var hasDefaultClause = argc % 2 !== 0;
var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1];
if (switchCount) {
for (var index = 0; index < switchCount; index++) {
if (targetValue === arguments[index * 2 + 1]) {
result = arguments[index * 2 + 2];
switchSatisfied = true;
break;
}
}
}
if (!switchSatisfied) {
result = hasDefaultClause ? defaultClause : error.na;
}
} else {
result = error.value;
}
return result;
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var dateTime = __webpack_require__(8);
var utils = __webpack_require__(1);
function validDate(d) {
return d && d.getTime && !isNaN(d.getTime());
}
function ensureDate(d) {
return (d instanceof Date)?d:new Date(d);
}
exports.ACCRINT = function(issue, first, settlement, rate, par, frequency, basis) {
// Return error if either date is invalid
issue = ensureDate(issue);
first = ensureDate(first);
settlement = ensureDate(settlement);
if (!validDate(issue) || !validDate(first) || !validDate(settlement)) {
return error.value;
}
// Return error if either rate or par are lower than or equal to zero
if (rate <= 0 || par <= 0) {
return error.num;
}
// Return error if frequency is neither 1, 2, or 4
if ([1, 2, 4].indexOf(frequency) === -1) {
return error.num;
}
// Return error if basis is neither 0, 1, 2, 3, or 4
if ([0, 1, 2, 3, 4].indexOf(basis) === -1) {
return error.num;
}
// Return error if settlement is before or equal to issue
if (settlement <= issue) {
return error.num;
}
// Set default values
par = par || 0;
basis = basis || 0;
// Compute accrued interest
return par * rate * dateTime.YEARFRAC(issue, settlement, basis);
};
// TODO
exports.ACCRINTM = function() {
throw new Error('ACCRINTM is not implemented');
};
// TODO
exports.AMORDEGRC = function() {
throw new Error('AMORDEGRC is not implemented');
};
// TODO
exports.AMORLINC = function() {
throw new Error('AMORLINC is not implemented');
};
// TODO
exports.COUPDAYBS = function() {
throw new Error('COUPDAYBS is not implemented');
};
// TODO
exports.COUPDAYS = function() {
throw new Error('COUPDAYS is not implemented');
};
// TODO
exports.COUPDAYSNC = function() {
throw new Error('COUPDAYSNC is not implemented');
};
// TODO
exports.COUPNCD = function() {
throw new Error('COUPNCD is not implemented');
};
// TODO
exports.COUPNUM = function() {
throw new Error('COUPNUM is not implemented');
};
// TODO
exports.COUPPCD = function() {
throw new Error('COUPPCD is not implemented');
};
exports.CUMIPMT = function(rate, periods, value, start, end, type) {
// Credits: algorithm inspired by Apache OpenOffice
// Credits: Hannes Stiebitzhofer for the translations of function and variable names
// Requires exports.FV() and exports.PMT() from exports.js [http://stoic.com/exports/]
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
value = utils.parseNumber(value);
if (utils.anyIsError(rate, periods, value)) {
return error.value;
}
// Return error if either rate, periods, or value are lower than or equal to zero
if (rate <= 0 || periods <= 0 || value <= 0) {
return error.num;
}
// Return error if start < 1, end < 1, or start > end
if (start < 1 || end < 1 || start > end) {
return error.num;
}
// Return error if type is neither 0 nor 1
if (type !== 0 && type !== 1) {
return error.num;
}
// Compute cumulative interest
var payment = exports.PMT(rate, periods, value, 0, type);
var interest = 0;
if (start === 1) {
if (type === 0) {
interest = -value;
start++;
}
}
for (var i = start; i <= end; i++) {
if (type === 1) {
interest += exports.FV(rate, i - 2, payment, value, 1) - payment;
} else {
interest += exports.FV(rate, i - 1, payment, value, 0);
}
}
interest *= rate;
// Return cumulative interest
return interest;
};
exports.CUMPRINC = function(rate, periods, value, start, end, type) {
// Credits: algorithm inspired by Apache OpenOffice
// Credits: Hannes Stiebitzhofer for the translations of function and variable names
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
value = utils.parseNumber(value);
if (utils.anyIsError(rate, periods, value)) {
return error.value;
}
// Return error if either rate, periods, or value are lower than or equal to zero
if (rate <= 0 || periods <= 0 || value <= 0) {
return error.num;
}
// Return error if start < 1, end < 1, or start > end
if (start < 1 || end < 1 || start > end) {
return error.num;
}
// Return error if type is neither 0 nor 1
if (type !== 0 && type !== 1) {
return error.num;
}
// Compute cumulative principal
var payment = exports.PMT(rate, periods, value, 0, type);
var principal = 0;
if (start === 1) {
if (type === 0) {
principal = payment + value * rate;
} else {
principal = payment;
}
start++;
}
for (var i = start; i <= end; i++) {
if (type > 0) {
principal += payment - (exports.FV(rate, i - 2, payment, value, 1) - payment) * rate;
} else {
principal += payment - exports.FV(rate, i - 1, payment, value, 0) * rate;
}
}
// Return cumulative principal
return principal;
};
exports.DB = function(cost, salvage, life, period, month) {
// Initialize month
month = (month === undefined) ? 12 : month;
cost = utils.parseNumber(cost);
salvage = utils.parseNumber(salvage);
life = utils.parseNumber(life);
period = utils.parseNumber(period);
month = utils.parseNumber(month);
if (utils.anyIsError(cost, salvage, life, period, month)) {
return error.value;
}
// Return error if any of the parameters is negative
if (cost < 0 || salvage < 0 || life < 0 || period < 0) {
return error.num;
}
// Return error if month is not an integer between 1 and 12
if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) {
return error.num;
}
// Return error if period is greater than life
if (period > life) {
return error.num;
}
// Return 0 (zero) if salvage is greater than or equal to cost
if (salvage >= cost) {
return 0;
}
// Rate is rounded to three decimals places
var rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3);
// Compute initial depreciation
var initial = cost * rate * month / 12;
// Compute total depreciation
var total = initial;
var current = 0;
var ceiling = (period === life) ? life - 1 : period;
for (var i = 2; i <= ceiling; i++) {
current = (cost - total) * rate;
total += current;
}
// Depreciation for the first and last periods are special cases
if (period === 1) {
// First period
return initial;
} else if (period === life) {
// Last period
return (cost - total) * rate;
} else {
return current;
}
};
exports.DDB = function(cost, salvage, life, period, factor) {
// Initialize factor
factor = (factor === undefined) ? 2 : factor;
cost = utils.parseNumber(cost);
salvage = utils.parseNumber(salvage);
life = utils.parseNumber(life);
period = utils.parseNumber(period);
factor = utils.parseNumber(factor);
if (utils.anyIsError(cost, salvage, life, period, factor)) {
return error.value;
}
// Return error if any of the parameters is negative or if factor is null
if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) {
return error.num;
}
// Return error if period is greater than life
if (period > life) {
return error.num;
}
// Return 0 (zero) if salvage is greater than or equal to cost
if (salvage >= cost) {
return 0;
}
// Compute depreciation
var total = 0;
var current = 0;
for (var i = 1; i <= period; i++) {
current = Math.min((cost - total) * (factor / life), (cost - salvage - total));
total += current;
}
// Return depreciation
return current;
};
// TODO
exports.DISC = function() {
throw new Error('DISC is not implemented');
};
exports.DOLLARDE = function(dollar, fraction) {
// Credits: algorithm inspired by Apache OpenOffice
dollar = utils.parseNumber(dollar);
fraction = utils.parseNumber(fraction);
if (utils.anyIsError(dollar, fraction)) {
return error.value;
}
// Return error if fraction is negative
if (fraction < 0) {
return error.num;
}
// Return error if fraction is greater than or equal to 0 and less than 1
if (fraction >= 0 && fraction < 1) {
return error.div0;
}
// Truncate fraction if it is not an integer
fraction = parseInt(fraction, 10);
// Compute integer part
var result = parseInt(dollar, 10);
// Add decimal part
result += (dollar % 1) * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction;
// Round result
var power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1);
result = Math.round(result * power) / power;
// Return converted dollar price
return result;
};
exports.DOLLARFR = function(dollar, fraction) {
// Credits: algorithm inspired by Apache OpenOffice
dollar = utils.parseNumber(dollar);
fraction = utils.parseNumber(fraction);
if (utils.anyIsError(dollar, fraction)) {
return error.value;
}
// Return error if fraction is negative
if (fraction < 0) {
return error.num;
}
// Return error if fraction is greater than or equal to 0 and less than 1
if (fraction >= 0 && fraction < 1) {
return error.div0;
}
// Truncate fraction if it is not an integer
fraction = parseInt(fraction, 10);
// Compute integer part
var result = parseInt(dollar, 10);
// Add decimal part
result += (dollar % 1) * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction;
// Return converted dollar price
return result;
};
// TODO
exports.DURATION = function() {
throw new Error('DURATION is not implemented');
};
exports.EFFECT = function(rate, periods) {
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
if (utils.anyIsError(rate, periods)) {
return error.value;
}
// Return error if rate <=0 or periods < 1
if (rate <= 0 || periods < 1) {
return error.num;
}
// Truncate periods if it is not an integer
periods = parseInt(periods, 10);
// Return effective annual interest rate
return Math.pow(1 + rate / periods, periods) - 1;
};
exports.FV = function(rate, periods, payment, value, type) {
// Credits: algorithm inspired by Apache OpenOffice
value = value || 0;
type = type || 0;
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
payment = utils.parseNumber(payment);
value = utils.parseNumber(value);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, periods, payment, value, type)) {
return error.value;
}
// Return future value
var result;
if (rate === 0) {
result = value + payment * periods;
} else {
var term = Math.pow(1 + rate, periods);
if (type === 1) {
result = value * term + payment * (1 + rate) * (term - 1) / rate;
} else {
result = value * term + payment * (term - 1) / rate;
}
}
return -result;
};
exports.FVSCHEDULE = function(principal, schedule) {
principal = utils.parseNumber(principal);
schedule = utils.parseNumberArray(utils.flatten(schedule));
if (utils.anyIsError(principal, schedule)) {
return error.value;
}
var n = schedule.length;
var future = principal;
// Apply all interests in schedule
for (var i = 0; i < n; i++) {
// Apply scheduled interest
future *= 1 + schedule[i];
}
// Return future value
return future;
};
// TODO
exports.INTRATE = function() {
throw new Error('INTRATE is not implemented');
};
exports.IPMT = function(rate, period, periods, present, future, type) {
// Credits: algorithm inspired by Apache OpenOffice
future = future || 0;
type = type || 0;
rate = utils.parseNumber(rate);
period = utils.parseNumber(period);
periods = utils.parseNumber(periods);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, period, periods, present, future, type)) {
return error.value;
}
// Compute payment
var payment = exports.PMT(rate, periods, present, future, type);
// Compute interest
var interest;
if (period === 1) {
if (type === 1) {
interest = 0;
} else {
interest = -present;
}
} else {
if (type === 1) {
interest = exports.FV(rate, period - 2, payment, present, 1) - payment;
} else {
interest = exports.FV(rate, period - 1, payment, present, 0);
}
}
// Return interest
return interest * rate;
};
exports.IRR = function(values, guess) {
// Credits: algorithm inspired by Apache OpenOffice
guess = guess || 0;
values = utils.parseNumberArray(utils.flatten(values));
guess = utils.parseNumber(guess);
if (utils.anyIsError(values, guess)) {
return error.value;
}
// Calculates the resulting amount
var irrResult = function(values, dates, rate) {
var r = rate + 1;
var result = values[0];
for (var i = 1; i < values.length; i++) {
result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365);
}
return result;
};
// Calculates the first derivation
var irrResultDeriv = function(values, dates, rate) {
var r = rate + 1;
var result = 0;
for (var i = 1; i < values.length; i++) {
var frac = (dates[i] - dates[0]) / 365;
result -= frac * values[i] / Math.pow(r, frac + 1);
}
return result;
};
// Initialize dates and check that values contains at least one positive value and one negative value
var dates = [];
var positive = false;
var negative = false;
for (var i = 0; i < values.length; i++) {
dates[i] = (i === 0) ? 0 : dates[i - 1] + 365;
if (values[i] > 0) {
positive = true;
}
if (values[i] < 0) {
negative = true;
}
}
// Return error if values does not contain at least one positive value and one negative value
if (!positive || !negative) {
return error.num;
}
// Initialize guess and resultRate
guess = (guess === undefined) ? 0.1 : guess;
var resultRate = guess;
// Set maximum epsilon for end of iteration
var epsMax = 1e-10;
// Implement Newton's method
var newRate, epsRate, resultValue;
var contLoop = true;
do {
resultValue = irrResult(values, dates, resultRate);
newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate);
epsRate = Math.abs(newRate - resultRate);
resultRate = newRate;
contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax);
} while (contLoop);
// Return internal rate of return
return resultRate;
};
exports.ISPMT = function(rate, period, periods, value) {
rate = utils.parseNumber(rate);
period = utils.parseNumber(period);
periods = utils.parseNumber(periods);
value = utils.parseNumber(value);
if (utils.anyIsError(rate, period, periods, value)) {
return error.value;
}
// Return interest
return value * rate * (period / periods - 1);
};
// TODO
exports.MDURATION = function() {
throw new Error('MDURATION is not implemented');
};
exports.MIRR = function(values, finance_rate, reinvest_rate) {
values = utils.parseNumberArray(utils.flatten(values));
finance_rate = utils.parseNumber(finance_rate);
reinvest_rate = utils.parseNumber(reinvest_rate);
if (utils.anyIsError(values, finance_rate, reinvest_rate)) {
return error.value;
}
// Initialize number of values
var n = values.length;
// Lookup payments (negative values) and incomes (positive values)
var payments = [];
var incomes = [];
for (var i = 0; i < n; i++) {
if (values[i] < 0) {
payments.push(values[i]);
} else {
incomes.push(values[i]);
}
}
// Return modified internal rate of return
var num = -exports.NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1);
var den = exports.NPV(finance_rate, payments) * (1 + finance_rate);
return Math.pow(num / den, 1 / (n - 1)) - 1;
};
exports.NOMINAL = function(rate, periods) {
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
if (utils.anyIsError(rate, periods)) {
return error.value;
}
// Return error if rate <=0 or periods < 1
if (rate <= 0 || periods < 1) {
return error.num;
}
// Truncate periods if it is not an integer
periods = parseInt(periods, 10);
// Return nominal annual interest rate
return (Math.pow(rate + 1, 1 / periods) - 1) * periods;
};
exports.NPER = function(rate, payment, present, future, type) {
type = (type === undefined) ? 0 : type;
future = (future === undefined) ? 0 : future;
rate = utils.parseNumber(rate);
payment = utils.parseNumber(payment);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, payment, present, future, type)) {
return error.value;
}
// Return number of periods
var num = payment * (1 + rate * type) - future * rate;
var den = (present * rate + payment * (1 + rate * type));
return Math.log(num / den) / Math.log(1 + rate);
};
exports.NPV = function() {
var args = utils.parseNumberArray(utils.flatten(arguments));
if (args instanceof Error) {
return args;
}
// Lookup rate
var rate = args[0];
// Initialize net present value
var value = 0;
// Loop on all values
for (var j = 1; j < args.length; j++) {
value += args[j] / Math.pow(1 + rate, j);
}
// Return net present value
return value;
};
// TODO
exports.ODDFPRICE = function() {
throw new Error('ODDFPRICE is not implemented');
};
// TODO
exports.ODDFYIELD = function() {
throw new Error('ODDFYIELD is not implemented');
};
// TODO
exports.ODDLPRICE = function() {
throw new Error('ODDLPRICE is not implemented');
};
// TODO
exports.ODDLYIELD = function() {
throw new Error('ODDLYIELD is not implemented');
};
exports.PDURATION = function(rate, present, future) {
rate = utils.parseNumber(rate);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
if (utils.anyIsError(rate, present, future)) {
return error.value;
}
// Return error if rate <=0
if (rate <= 0) {
return error.num;
}
// Return number of periods
return (Math.log(future) - Math.log(present)) / Math.log(1 + rate);
};
exports.PMT = function(rate, periods, present, future, type) {
// Credits: algorithm inspired by Apache OpenOffice
future = future || 0;
type = type || 0;
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, periods, present, future, type)) {
return error.value;
}
// Return payment
var result;
if (rate === 0) {
result = (present + future) / periods;
} else {
var term = Math.pow(1 + rate, periods);
if (type === 1) {
result = (future * rate / (term - 1) + present * rate / (1 - 1 / term)) / (1 + rate);
} else {
result = future * rate / (term - 1) + present * rate / (1 - 1 / term);
}
}
return -result;
};
exports.PPMT = function(rate, period, periods, present, future, type) {
future = future || 0;
type = type || 0;
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, periods, present, future, type)) {
return error.value;
}
return exports.PMT(rate, periods, present, future, type) - exports.IPMT(rate, period, periods, present, future, type);
};
// TODO
exports.PRICE = function() {
throw new Error('PRICE is not implemented');
};
// TODO
exports.PRICEDISC = function() {
throw new Error('PRICEDISC is not implemented');
};
// TODO
exports.PRICEMAT = function() {
throw new Error('PRICEMAT is not implemented');
};
exports.PV = function(rate, periods, payment, future, type) {
future = future || 0;
type = type || 0;
rate = utils.parseNumber(rate);
periods = utils.parseNumber(periods);
payment = utils.parseNumber(payment);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
if (utils.anyIsError(rate, periods, payment, future, type)) {
return error.value;
}
// Return present value
if (rate === 0) {
return -payment * periods - future;
} else {
return (((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) / Math.pow(1 + rate, periods);
}
};
exports.RATE = function(periods, payment, present, future, type, guess) {
// Credits: rabugento
guess = (guess === undefined) ? 0.01 : guess;
future = (future === undefined) ? 0 : future;
type = (type === undefined) ? 0 : type;
periods = utils.parseNumber(periods);
payment = utils.parseNumber(payment);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
type = utils.parseNumber(type);
guess = utils.parseNumber(guess);
if (utils.anyIsError(periods, payment, present, future, type, guess)) {
return error.value;
}
// Set maximum epsilon for end of iteration
var epsMax = 1e-10;
// Set maximum number of iterations
var iterMax = 50;
// Implement Newton's method
var y, y0, y1, x0, x1 = 0,
f = 0,
i = 0;
var rate = guess;
if (Math.abs(rate) < epsMax) {
y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future;
} else {
f = Math.exp(periods * Math.log(1 + rate));
y = present * f + payment * (1 / rate + type) * (f - 1) + future;
}
y0 = present + payment * periods + future;
y1 = present * f + payment * (1 / rate + type) * (f - 1) + future;
i = x0 = 0;
x1 = rate;
while ((Math.abs(y0 - y1) > epsMax) && (i < iterMax)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < epsMax) {
y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future;
} else {
f = Math.exp(periods * Math.log(1 + rate));
y = present * f + payment * (1 / rate + type) * (f - 1) + future;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
};
// TODO
exports.RECEIVED = function() {
throw new Error('RECEIVED is not implemented');
};
exports.RRI = function(periods, present, future) {
periods = utils.parseNumber(periods);
present = utils.parseNumber(present);
future = utils.parseNumber(future);
if (utils.anyIsError(periods, present, future)) {
return error.value;
}
// Return error if periods or present is equal to 0 (zero)
if (periods === 0 || present === 0) {
return error.num;
}
// Return equivalent interest rate
return Math.pow(future / present, 1 / periods) - 1;
};
exports.SLN = function(cost, salvage, life) {
cost = utils.parseNumber(cost);
salvage = utils.parseNumber(salvage);
life = utils.parseNumber(life);
if (utils.anyIsError(cost, salvage, life)) {
return error.value;
}
// Return error if life equal to 0 (zero)
if (life === 0) {
return error.num;
}
// Return straight-line depreciation
return (cost - salvage) / life;
};
exports.SYD = function(cost, salvage, life, period) {
// Return error if any of the parameters is not a number
cost = utils.parseNumber(cost);
salvage = utils.parseNumber(salvage);
life = utils.parseNumber(life);
period = utils.parseNumber(period);
if (utils.anyIsError(cost, salvage, life, period)) {
return error.value;
}
// Return error if life equal to 0 (zero)
if (life === 0) {
return error.num;
}
// Return error if period is lower than 1 or greater than life
if (period < 1 || period > life) {
return error.num;
}
// Truncate period if it is not an integer
period = parseInt(period, 10);
// Return straight-line depreciation
return ((cost - salvage) * (life - period + 1) * 2) / (life * (life + 1));
};
exports.TBILLEQ = function(settlement, maturity, discount) {
settlement = utils.parseDate(settlement);
maturity = utils.parseDate(maturity);
discount = utils.parseNumber(discount);
if (utils.anyIsError(settlement, maturity, discount)) {
return error.value;
}
// Return error if discount is lower than or equal to zero
if (discount <= 0) {
return error.num;
}
// Return error if settlement is greater than maturity
if (settlement > maturity) {
return error.num;
}
// Return error if maturity is more than one year after settlement
if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
return error.num;
}
// Return bond-equivalent yield
return (365 * discount) / (360 - discount * dateTime.DAYS360(settlement, maturity, false));
};
exports.TBILLPRICE = function(settlement, maturity, discount) {
settlement = utils.parseDate(settlement);
maturity = utils.parseDate(maturity);
discount = utils.parseNumber(discount);
if (utils.anyIsError(settlement, maturity, discount)) {
return error.value;
}
// Return error if discount is lower than or equal to zero
if (discount <= 0) {
return error.num;
}
// Return error if settlement is greater than maturity
if (settlement > maturity) {
return error.num;
}
// Return error if maturity is more than one year after settlement
if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
return error.num;
}
// Return bond-equivalent yield
return 100 * (1 - discount * dateTime.DAYS360(settlement, maturity, false) / 360);
};
exports.TBILLYIELD = function(settlement, maturity, price) {
settlement = utils.parseDate(settlement);
maturity = utils.parseDate(maturity);
price = utils.parseNumber(price);
if (utils.anyIsError(settlement, maturity, price)) {
return error.value;
}
// Return error if price is lower than or equal to zero
if (price <= 0) {
return error.num;
}
// Return error if settlement is greater than maturity
if (settlement > maturity) {
return error.num;
}
// Return error if maturity is more than one year after settlement
if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) {
return error.num;
}
// Return bond-equivalent yield
return (100 - price) * 360 / (price * dateTime.DAYS360(settlement, maturity, false));
};
// TODO
exports.VDB = function() {
throw new Error('VDB is not implemented');
};
// TODO needs better support for date
// exports.XIRR = function(values, dates, guess) {
// // Credits: algorithm inspired by Apache OpenOffice
//
// values = utils.parseNumberArray(utils.flatten(values));
// dates = utils.parseDateArray(utils.flatten(dates));
// guess = utils.parseNumber(guess);
//
// if (utils.anyIsError(values, dates, guess)) {
// return error.value;
// }
//
// // Calculates the resulting amount
// var irrResult = function(values, dates, rate) {
// var r = rate + 1;
// var result = values[0];
// for (var i = 1; i < values.length; i++) {
// result += values[i] / Math.pow(r, dateTime.DAYS(dates[i], dates[0]) / 365);
// }
// return result;
// };
//
// // Calculates the first derivation
// var irrResultDeriv = function(values, dates, rate) {
// var r = rate + 1;
// var result = 0;
// for (var i = 1; i < values.length; i++) {
// var frac = dateTime.DAYS(dates[i], dates[0]) / 365;
// result -= frac * values[i] / Math.pow(r, frac + 1);
// }
// return result;
// };
//
// // Check that values contains at least one positive value and one negative value
// var positive = false;
// var negative = false;
// for (var i = 0; i < values.length; i++) {
// if (values[i] > 0) {
// positive = true;
// }
// if (values[i] < 0) {
// negative = true;
// }
// }
//
// // Return error if values does not contain at least one positive value and one negative value
// if (!positive || !negative) {
// return error.num;
// }
//
// // Initialize guess and resultRate
// guess = guess || 0.1;
// var resultRate = guess;
//
// // Set maximum epsilon for end of iteration
// var epsMax = 1e-10;
//
// // Implement Newton's method
// var newRate, epsRate, resultValue;
// var contLoop = true;
// do {
// resultValue = irrResult(values, dates, resultRate);
// newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate);
// epsRate = Math.abs(newRate - resultRate);
// resultRate = newRate;
// contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax);
// } while (contLoop);
//
// // Return internal rate of return
// return resultRate;
// };
exports.XNPV = function(rate, values, dates) {
rate = utils.parseNumber(rate);
values = utils.parseNumberArray(utils.flatten(values));
dates = utils.parseDateArray(utils.flatten(dates));
if (utils.anyIsError(rate, values, dates)) {
return error.value;
}
var result = 0;
for (var i = 0; i < values.length; i++) {
result += values[i] / Math.pow(1 + rate, dateTime.DAYS(dates[i], dates[0]) / 365);
}
return result;
};
// TODO
exports.YIELD = function() {
throw new Error('YIELD is not implemented');
};
// TODO
exports.YIELDDISC = function() {
throw new Error('YIELDDISC is not implemented');
};
// TODO
exports.YIELDMAT = function() {
throw new Error('YIELDMAT is not implemented');
};
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
var error = __webpack_require__(0);
var utils = __webpack_require__(1);
exports.MATCH = function(lookupValue, lookupArray, matchType) {
if (!lookupValue && !lookupArray) {
return error.na;
}
if (arguments.length === 2) {
matchType = 1;
}
if (!(lookupArray instanceof Array)) {
return error.na;
}
if (matchType !== -1 && matchType !== 0 && matchType !== 1) {
return error.na;
}
var index;
var indexValue;
for (var idx = 0; idx < lookupArray.length; idx++) {
if (matchType === 1) {
if (lookupArray[idx] === lookupValue) {
return idx + 1;
} else if (lookupArray[idx] < lookupValue) {
if (!indexValue) {
index = idx + 1;
indexValue = lookupArray[idx];
} else if (lookupArray[idx] > indexValue) {
index = idx + 1;
indexValue = lookupArray[idx];
}
}
} else if (matchType === 0) {
if (typeof lookupValue === 'string') {
lookupValue = lookupValue.replace(/\?/g, '.');
if (lookupArray[idx].toLowerCase().match(lookupValue.toLowerCase())) {
return idx + 1;
}
} else {
if (lookupArray[idx] === lookupValue) {
return idx + 1;
}
}
} else if (matchType === -1) {
if (lookupArray[idx] === lookupValue) {
return idx + 1;
} else if (lookupArray[idx] > lookupValue) {
if (!indexValue) {
index = idx + 1;
indexValue = lookupArray[idx];
} else if (lookupArray[idx] < indexValue) {
index = idx + 1;
indexValue = lookupArray[idx];
}
}
}
}
return index ? index : error.na;
};
exports.VLOOKUP = function (needle, table, index, rangeLookup) {
if (!needle || !table || !index) {
return error.na;
}
rangeLookup = rangeLookup || false;
for (var i = 0; i < table.length; i++) {
var row = table[i];
if ((!rangeLookup && row[0] === needle) ||
((row[0] === needle) ||
(rangeLookup && typeof row[0] === "string" && row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1))) {
return (index < (row.length + 1) ? row[index - 1] : error.ref);
}
}
return error.na;
};
exports.HLOOKUP = function (needle, table, index, rangeLookup) {
if (!needle || !table || !index) {
return error.na;
}
rangeLookup = rangeLookup || false;
var transposedTable = utils.transpose(table);
for (var i = 0; i < transposedTable.length; i++) {
var row = transposedTable[i];
if ((!rangeLookup && row[0] === needle) ||
((row[0] === needle) ||
(rangeLookup && typeof row[0] === "string" && row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1))) {
return (index < (row.length + 1) ? row[index - 1] : error.ref);
}
}
return error.na;
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '>';
function func(exp1, exp2) {
return exp1 > exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '>=';
function func(exp1, exp2) {
return exp1 >= exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '<';
function func(exp1, exp2) {
return exp1 < exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '<=';
function func(exp1, exp2) {
return exp1 <= exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var SYMBOL = exports.SYMBOL = '-';
function func(first) {
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var result = rest.reduce(function (acc, value) {
return acc - (0, _number.toNumber)(value);
}, (0, _number.toNumber)(first));
if (isNaN(result)) {
throw Error(_error.ERROR_VALUE);
}
return result;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var SYMBOL = exports.SYMBOL = '*';
function func(first) {
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var result = rest.reduce(function (acc, value) {
return acc * (0, _number.toNumber)(value);
}, (0, _number.toNumber)(first));
if (isNaN(result)) {
throw Error(_error.ERROR_VALUE);
}
return result;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports['default'] = func;
var SYMBOL = exports.SYMBOL = '<>';
function func(exp1, exp2) {
return exp1 !== exp2;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SYMBOL = undefined;
exports['default'] = func;
var _number = __webpack_require__(3);
var _error = __webpack_require__(2);
var SYMBOL = exports.SYMBOL = '^';
function func(exp1, exp2) {
var result = Math.pow((0, _number.toNumber)(exp1), (0, _number.toNumber)(exp2));
if (isNaN(result)) {
throw Error(_error.ERROR_VALUE);
}
return result;
}
func.SYMBOL = SYMBOL;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, process) {/* parser generated by jison 0.4.17 */
/*
Returns a Parser object of the following structure:
Parser: {
yy: {}
}
Parser.prototype: {
yy: {},
trace: function(),
symbols_: {associative list: name ==> number},
terminals_: {associative list: number ==> name},
productions_: [...],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
table: [...],
defaultActions: {...},
parseError: function(str, hash),
parse: function(input),
lexer: {
EOF: 1,
parseError: function(str, hash),
setInput: function(input),
input: function(),
unput: function(str),
more: function(),
less: function(n),
pastInput: function(),
upcomingInput: function(),
showPosition: function(),
test_match: function(regex_match_array, rule_index),
next: function(),
lex: function(),
begin: function(condition),
popState: function(),
_currentRules: function(),
topState: function(),
pushState: function(condition),
options: {
ranges: boolean (optional: true ==> token location info will include a .range[] member)
flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
},
performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
rules: [...],
conditions: {associative list: name ==> set},
}
}
token location info (@$, _$, etc.): {
first_line: n,
last_line: n,
first_column: n,
last_column: n,
range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)
}
the parseError function receives a 'hash' object with these members for lexer and parser errors: {
text: (matched text)
token: (the produced terminal token, if any)
line: (yylineno)
}
while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
loc: (yylloc)
expected: (string describing the set of expected tokens)
recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
}
*/
var grammarParser = (function(){
var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,8],$V2=[1,6],$V3=[1,7],$V4=[1,9],$V5=[1,14],$V6=[1,15],$V7=[1,16],$V8=[1,12],$V9=[1,13],$Va=[1,17],$Vb=[1,19],$Vc=[1,20],$Vd=[1,21],$Ve=[1,22],$Vf=[1,23],$Vg=[1,24],$Vh=[1,25],$Vi=[1,26],$Vj=[1,27],$Vk=[1,28],$Vl=[5,9,10,11,13,14,15,16,17,18,19,20,29,30],$Vm=[5,9,10,11,13,14,15,16,17,18,19,20,29,30,32],$Vn=[5,9,10,11,13,14,15,16,17,18,19,20,29,30,34],$Vo=[5,10,11,13,14,15,16,17,29,30],$Vp=[5,10,13,14,15,16,29,30],$Vq=[5,10,11,13,14,15,16,17,18,19,29,30],$Vr=[13,29,30];
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"expressions":3,"expression":4,"EOF":5,"variableSequence":6,"number":7,"STRING":8,"&":9,"=":10,"+":11,"(":12,")":13,"<":14,">":15,"NOT":16,"-":17,"*":18,"/":19,"^":20,"FUNCTION":21,"expseq":22,"cell":23,"ABSOLUTE_CELL":24,"RELATIVE_CELL":25,"MIXED_CELL":26,":":27,"ARRAY":28,";":29,",":30,"VARIABLE":31,"DECIMAL":32,"NUMBER":33,"%":34,"ERROR":35,"$accept":0,"$end":1},
terminals_: {5:"EOF",8:"STRING",9:"&",10:"=",11:"+",12:"(",13:")",14:"<",15:">",16:"NOT",17:"-",18:"*",19:"/",20:"^",21:"FUNCTION",24:"ABSOLUTE_CELL",25:"RELATIVE_CELL",26:"MIXED_CELL",27:":",28:"ARRAY",29:";",30:",",31:"VARIABLE",32:"DECIMAL",33:"NUMBER",34:"%",35:"ERROR"},
productions_: [0,[3,2],[4,1],[4,1],[4,1],[4,3],[4,3],[4,3],[4,3],[4,4],[4,4],[4,4],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,2],[4,2],[4,3],[4,4],[4,1],[4,1],[4,2],[23,1],[23,1],[23,1],[23,3],[23,3],[23,3],[23,3],[23,3],[23,3],[23,3],[23,3],[23,3],[22,1],[22,1],[22,3],[22,3],[6,1],[6,3],[7,1],[7,3],[7,2],[2,1]],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {
/* this == yyval */
var $0 = $$.length - 1;
switch (yystate) {
case 1:
return $$[$0-1];
break;
case 2:
this.$ = yy.callVariable($$[$0][0]);
break;
case 3:
this.$ = yy.toNumber($$[$0]);
break;
case 4:
this.$ = yy.trimEdges($$[$0]);
break;
case 5:
this.$ = yy.evaluateByOperator('&', [$$[$0-2], $$[$0]]);
break;
case 6:
this.$ = yy.evaluateByOperator('=', [$$[$0-2], $$[$0]]);
break;
case 7:
this.$ = yy.evaluateByOperator('+', [$$[$0-2], $$[$0]]);
break;
case 8:
this.$ = $$[$0-1];
break;
case 9:
this.$ = yy.evaluateByOperator('<=', [$$[$0-3], $$[$0]]);
break;
case 10:
this.$ = yy.evaluateByOperator('>=', [$$[$0-3], $$[$0]]);
break;
case 11:
this.$ = yy.evaluateByOperator('<>', [$$[$0-3], $$[$0]]);
break;
case 12:
this.$ = yy.evaluateByOperator('NOT', [$$[$0-2], $$[$0]]);
break;
case 13:
this.$ = yy.evaluateByOperator('>', [$$[$0-2], $$[$0]]);
break;
case 14:
this.$ = yy.evaluateByOperator('<', [$$[$0-2], $$[$0]]);
break;
case 15:
this.$ = yy.evaluateByOperator('-', [$$[$0-2], $$[$0]]);
break;
case 16:
this.$ = yy.evaluateByOperator('*', [$$[$0-2], $$[$0]]);
break;
case 17:
this.$ = yy.evaluateByOperator('/', [$$[$0-2], $$[$0]]);
break;
case 18:
this.$ = yy.evaluateByOperator('^', [$$[$0-2], $$[$0]]);
break;
case 19:
var n1 = yy.invertNumber($$[$0]);
this.$ = n1;
if (isNaN(this.$)) {
this.$ = 0;
}
break;
case 20:
var n1 = yy.toNumber($$[$0]);
this.$ = n1;
if (isNaN(this.$)) {
this.$ = 0;
}
break;
case 21:
this.$ = yy.callFunction($$[$0-2]);
break;
case 22:
this.$ = yy.callFunction($$[$0-3], $$[$0-1]);
break;
case 26: case 27: case 28:
this.$ = yy.cellValue($$[$0]);
break;
case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37:
this.$ = yy.rangeValue($$[$0-2], $$[$0]);
break;
case 38: case 42:
this.$ = [$$[$0]];
break;
case 39:
var result = [];
var arr = eval("[" + yytext + "]");
arr.forEach(function(item) {
result.push(item);
});
this.$ = result;
break;
case 40: case 41:
$$[$0-2].push($$[$0]);
this.$ = $$[$0-2];
break;
case 43:
this.$ = (Array.isArray($$[$0-2]) ? $$[$0-2] : [$$[$0-2]]);
this.$.push($$[$0]);
break;
case 44:
this.$ = $$[$0];
break;
case 45:
this.$ = ($$[$0-2] + '.' + $$[$0]) * 1;
break;
case 46:
this.$ = $$[$0-1] * 0.01;
break;
case 47:
this.$ = yy.throwError($$[$0]);
break;
}
},
table: [{2:11,3:1,4:2,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{1:[3]},{5:[1,18],9:$Vb,10:$Vc,11:$Vd,14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk},o($Vl,[2,2],{32:[1,29]}),o($Vl,[2,3],{34:[1,30]}),o($Vl,[2,4]),{2:11,4:31,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:32,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:33,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{12:[1,34]},o($Vl,[2,23]),o($Vl,[2,24],{2:35,35:$Va}),o($Vm,[2,42]),o($Vn,[2,44],{32:[1,36]}),o($Vl,[2,26],{27:[1,37]}),o($Vl,[2,27],{27:[1,38]}),o($Vl,[2,28],{27:[1,39]}),o([5,9,10,11,13,14,15,16,17,18,19,20,29,30,35],[2,47]),{1:[2,1]},{2:11,4:40,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:41,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:42,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:45,6:3,7:4,8:$V0,10:[1,43],11:$V1,12:$V2,15:[1,44],17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:47,6:3,7:4,8:$V0,10:[1,46],11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:48,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:49,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:50,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:51,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:52,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{31:[1,53]},o($Vn,[2,46]),{9:$Vb,10:$Vc,11:$Vd,13:[1,54],14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk},o($Vo,[2,19],{9:$Vb,18:$Vi,19:$Vj,20:$Vk}),o($Vo,[2,20],{9:$Vb,18:$Vi,19:$Vj,20:$Vk}),{2:11,4:57,6:3,7:4,8:$V0,11:$V1,12:$V2,13:[1,55],17:$V3,21:$V4,22:56,23:10,24:$V5,25:$V6,26:$V7,28:[1,58],31:$V8,33:$V9,35:$Va},o($Vl,[2,25]),{33:[1,59]},{24:[1,60],25:[1,61],26:[1,62]},{24:[1,63],25:[1,64],26:[1,65]},{24:[1,66],25:[1,67],26:[1,68]},o($Vl,[2,5]),o([5,10,13,29,30],[2,6],{9:$Vb,11:$Vd,14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vo,[2,7],{9:$Vb,18:$Vi,19:$Vj,20:$Vk}),{2:11,4:69,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:70,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},o($Vp,[2,14],{9:$Vb,11:$Vd,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),{2:11,4:71,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},o($Vp,[2,13],{9:$Vb,11:$Vd,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o([5,10,13,16,29,30],[2,12],{9:$Vb,11:$Vd,14:$Ve,15:$Vf,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vo,[2,15],{9:$Vb,18:$Vi,19:$Vj,20:$Vk}),o($Vq,[2,16],{9:$Vb,20:$Vk}),o($Vq,[2,17],{9:$Vb,20:$Vk}),o([5,10,11,13,14,15,16,17,18,19,20,29,30],[2,18],{9:$Vb}),o($Vm,[2,43]),o($Vl,[2,8]),o($Vl,[2,21]),{13:[1,72],29:[1,73],30:[1,74]},o($Vr,[2,38],{9:$Vb,10:$Vc,11:$Vd,14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vr,[2,39]),o($Vn,[2,45]),o($Vl,[2,29]),o($Vl,[2,30]),o($Vl,[2,31]),o($Vl,[2,32]),o($Vl,[2,33]),o($Vl,[2,34]),o($Vl,[2,35]),o($Vl,[2,36]),o($Vl,[2,37]),o($Vp,[2,9],{9:$Vb,11:$Vd,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vp,[2,11],{9:$Vb,11:$Vd,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vp,[2,10],{9:$Vb,11:$Vd,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vl,[2,22]),{2:11,4:75,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},{2:11,4:76,6:3,7:4,8:$V0,11:$V1,12:$V2,17:$V3,21:$V4,23:10,24:$V5,25:$V6,26:$V7,31:$V8,33:$V9,35:$Va},o($Vr,[2,40],{9:$Vb,10:$Vc,11:$Vd,14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk}),o($Vr,[2,41],{9:$Vb,10:$Vc,11:$Vd,14:$Ve,15:$Vf,16:$Vg,17:$Vh,18:$Vi,19:$Vj,20:$Vk})],
defaultActions: {18:[2,1]},
parseError: function parseError(str, hash) {
if (hash.recoverable) {
this.trace(str);
} else {
function _parseError (msg, hash) {
this.message = msg;
this.hash = hash;
}
_parseError.prototype = Error;
throw new _parseError(str, hash);
}
},
parse: function parse(input) {
var self = this,
stack = [0],
tstack = [], // token stack
vstack = [null], // semantic value stack
lstack = [], // location stack
table = this.table,
yytext = '',
yylineno = 0,
yyleng = 0,
recovering = 0,
TERROR = 2,
EOF = 1;
var args = lstack.slice.call(arguments, 1);
//this.reductionCount = this.shiftCount = 0;
var lexer = Object.create(this.lexer);
var sharedState = { yy: {} };
// copy state
for (var k in this.yy) {
if (Object.prototype.hasOwnProperty.call(this.yy, k)) {
sharedState.yy[k] = this.yy[k];
}
}
lexer.setInput(input, sharedState.yy);
sharedState.yy.lexer = lexer;
sharedState.yy.parser = this;
if (typeof lexer.yylloc == 'undefined') {
lexer.yylloc = {};
}
var yyloc = lexer.yylloc;
lstack.push(yyloc);
var ranges = lexer.options && lexer.options.ranges;
if (typeof sharedState.yy.parseError === 'function') {
this.parseError = sharedState.yy.parseError;
} else {
this.parseError = Object.getPrototypeOf(this).parseError;
}
function popStack (n) {
stack.length = stack.length - 2 * n;
vstack.length = vstack.length - n;
lstack.length = lstack.length - n;
}
var lex = function () {
var token;
token = lexer.lex() || EOF;
// if token isn't its numeric value, convert
if (typeof token !== 'number') {
token = self.symbols_[token] || token;
}
return token;
}
var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
while (true) {
// retreive state number from top of stack
state = stack[stack.length - 1];
// use default actions if available
if (this.defaultActions[state]) {
action = this.defaultActions[state];
} else {
if (symbol === null || typeof symbol == 'undefined') {
symbol = lex();
}
// read action for current state and first input
action = table[state] && table[state][symbol];
}
// handle parse error
if (typeof action === 'undefined' || !action.length || !action[0]) {
var error_rule_depth;
var errStr = '';
// Return the rule stack depth where the nearest error rule can be found.
// Return FALSE when no error recovery rule was found.
function locateNearestErrorRecoveryRule(state) {
var stack_probe = stack.length - 1;
var depth = 0;
// try to recover from error
for(;;) {
// check for error recovery rule in this state
if ((TERROR.toString()) in table[state]) {
return depth;
}
if (state === 0 || stack_probe < 2) {
return false; // No suitable error recovery rule available.
}
stack_probe -= 2; // popStack(1): [symbol, action]
state = stack[stack_probe];
++depth;
}
}
if (!recovering) {
// first see if there's any chance at hitting an error recovery rule:
error_rule_depth = locateNearestErrorRecoveryRule(state);
// Report error
expected = [];
for (p in table[state]) {
if (this.terminals_[p] && p > TERROR) {
expected.push("'"+this.terminals_[p]+"'");
}
}
if (lexer.showPosition) {
errStr = 'Parse error on line '+(yylineno+1)+":\n"+lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + (this.terminals_[symbol] || symbol)+ "'";
} else {
errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
(symbol == EOF ? "end of input" :
("'"+(this.terminals_[symbol] || symbol)+"'"));
}
this.parseError(errStr, {
text: lexer.match,
token: this.terminals_[symbol] || symbol,
line: lexer.yylineno,
loc: yyloc,
expected: expected,
recoverable: (error_rule_depth !== false)
});
} else if (preErrorSymbol !== EOF) {
error_rule_depth = locateNearestErrorRecoveryRule(state);
}
// just recovered from another error
if (recovering == 3) {
if (symbol === EOF || preErrorSymbol === EOF) {
throw new Error(errStr || 'Parsing halted while starting to recover from another error.');
}
// discard current lookahead and grab another
yyleng = lexer.yyleng;
yytext = lexer.yytext;
yylineno = lexer.yylineno;
yyloc = lexer.yylloc;
symbol = lex();
}
// try to recover from error
if (error_rule_depth === false) {
throw new Error(errStr || 'Parsing halted. No suitable error recovery rule available.');
}
popStack(error_rule_depth);
preErrorSymbol = (symbol == TERROR ? null : symbol); // save the lookahead token
symbol = TERROR; // insert generic error symbol as new lookahead
state = stack[stack.length-1];
action = table[state] && table[state][TERROR];
recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
}
// this shouldn't happen, unless resolve defaults are off
if (action[0] instanceof Array && action.length > 1) {
throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
}
switch (action[0]) {
case 1: // shift
//this.shiftCount++;
stack.push(symbol);
vstack.push(lexer.yytext);
lstack.push(lexer.yylloc);
stack.push(action[1]); // push state
symbol = null;
if (!preErrorSymbol) { // normal execution/no error
yyleng = lexer.yyleng;
yytext = lexer.yytext;
yylineno = lexer.yylineno;
yyloc = lexer.yylloc;
if (recovering > 0) {
recovering--;
}
} else {
// error just occurred, resume old lookahead f/ before error
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2:
// reduce
//this.reductionCount++;
len = this.productions_[action[1]][1];
// perform semantic action
yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
// default location, uses first token for firsts, last for lasts
yyval._$ = {
first_line: lstack[lstack.length-(len||1)].first_line,
last_line: lstack[lstack.length-1].last_line,
first_column: lstack[lstack.length-(len||1)].first_column,
last_column: lstack[lstack.length-1].last_column
};
if (ranges) {
yyval._$.range = [lstack[lstack.length-(len||1)].range[0], lstack[lstack.length-1].range[1]];
}
r = this.performAction.apply(yyval, [yytext, yyleng, yylineno, sharedState.yy, action[1], vstack, lstack].concat(args));
if (typeof r !== 'undefined') {
return r;
}
// pop off stack
if (len) {
stack = stack.slice(0,-1*len*2);
vstack = vstack.slice(0, -1*len);
lstack = lstack.slice(0, -1*len);
}
stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)
vstack.push(yyval.$);
lstack.push(yyval._$);
// goto new state = table[STATE][NONTERMINAL]
newState = table[stack[stack.length-2]][stack[stack.length-1]];
stack.push(newState);
break;
case 3:
// accept
return true;
}
}
return true;
}};
/* generated by jison-lex 0.3.4 */
var lexer = (function(){
var lexer = ({
EOF:1,
parseError:function parseError(str, hash) {
if (this.yy.parser) {
this.yy.parser.parseError(str, hash);
} else {
throw new Error(str);
}
},
// resets the lexer, sets new input
setInput:function (input, yy) {
this.yy = yy || this.yy || {};
this._input = input;
this._more = this._backtrack = this.done = false;
this.yylineno = this.yyleng = 0;
this.yytext = this.matched = this.match = '';
this.conditionStack = ['INITIAL'];
this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
};
if (this.options.ranges) {
this.yylloc.range = [0,0];
}
this.offset = 0;
return this;
},
// consumes and returns one char from the input
input:function () {
var ch = this._input[0];
this.yytext += ch;
this.yyleng++;
this.offset++;
this.match += ch;
this.matched += ch;
var lines = ch.match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno++;
this.yylloc.last_line++;
} else {
this.yylloc.last_column++;
}
if (this.options.ranges) {
this.yylloc.range[1]++;
}
this._input = this._input.slice(1);
return ch;
},
// unshifts one char (or a string) into the input
unput:function (ch) {
var len = ch.length;
var lines = ch.split(/(?:\r\n?|\n)/g);
this._input = ch + this._input;
this.yytext = this.yytext.substr(0, this.yytext.length - len);
//this.yyleng -= len;
this.offset -= len;
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
this.match = this.match.substr(0, this.match.length - 1);
this.matched = this.matched.substr(0, this.matched.length - 1);
if (lines.length - 1) {
this.yylineno -= lines.length - 1;
}
var r = this.yylloc.range;
this.yylloc = {
first_line: this.yylloc.first_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.first_column,
last_column: lines ?
(lines.length === oldLines.length ? this.yylloc.first_column : 0)
+ oldLines[oldLines.length - lines.length].length - lines[0].length :
this.yylloc.first_column - len
};
if (this.options.ranges) {
this.yylloc.range = [r[0], r[0] + this.yyleng - len];
}
this.yyleng = this.yytext.length;
return this;
},
// When called from action, caches matched text and appends it on next action
more:function () {
this._more = true;
return this;
},
// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
reject:function () {
if (this.options.backtrack_lexer) {
this._backtrack = true;
} else {
return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
return this;
},
// retain first n characters of the match
less:function (n) {
this.unput(this.match.slice(n));
},
// displays already matched input, i.e. for error messages
pastInput:function () {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
},
// displays upcoming input, i.e. for error messages
upcomingInput:function () {
var next = this.match;
if (next.length < 20) {
next += this._input.substr(0, 20-next.length);
}
return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
},
// displays the character position where the lexing error occurred, i.e. for error messages
showPosition:function () {
var pre = this.pastInput();
var c = new Array(pre.length + 1).join("-");
return pre + this.upcomingInput() + "\n" + c + "^";
},
// test the lexed token: return FALSE when not a match, otherwise return token
test_match:function (match, indexed_rule) {
var token,
lines,
backup;
if (this.options.backtrack_lexer) {
// save context
backup = {
yylineno: this.yylineno,
yylloc: {
first_line: this.yylloc.first_line,
last_line: this.last_line,
first_column: this.yylloc.first_column,
last_column: this.yylloc.last_column
},
yytext: this.yytext,
match: this.match,
matches: this.matches,
matched: this.matched,
yyleng: this.yyleng,
offset: this.offset,
_more: this._more,
_input: this._input,
yy: this.yy,
conditionStack: this.conditionStack.slice(0),
done: this.done
};
if (this.options.ranges) {
backup.yylloc.range = this.yylloc.range.slice(0);
}
}
lines = match[0].match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno += lines.length;
}
this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: lines ?
lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length :
this.yylloc.last_column + match[0].length
};
this.yytext += match[0];
this.match += match[0];
this.matches = match;
this.yyleng = this.yytext.length;
if (this.options.ranges) {
this.yylloc.range = [this.offset, this.offset += this.yyleng];
}
this._more = false;
this._backtrack = false;
this._input = this._input.slice(match[0].length);
this.matched += match[0];
token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);
if (this.done && this._input) {
this.done = false;
}
if (token) {
return token;
} else if (this._backtrack) {
// recover context
for (var k in backup) {
this[k] = backup[k];
}
return false; // rule action called reject() implying the next rule should be tested instead.
}
return false;
},
// return next match in input
next:function () {
if (this.done) {
return this.EOF;
}
if (!this._input) {
this.done = true;
}
var token,
match,
tempMatch,
index;
if (!this._more) {
this.yytext = '';
this.match = '';
}
var rules = this._currentRules();
for (var i = 0; i < rules.length; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (this.options.backtrack_lexer) {
token = this.test_match(tempMatch, rules[i]);
if (token !== false) {
return token;
} else if (this._backtrack) {
match = false;
continue; // rule action called reject() implying a rule MISmatch.
} else {
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
} else if (!this.options.flex) {
break;
}
}
}
if (match) {
token = this.test_match(match, rules[index]);
if (token !== false) {
return token;
}
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
if (this._input === "") {
return this.EOF;
} else {
return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
},
// return next match that has a token
lex:function lex() {
var r = this.next();
if (r) {
return r;
} else {
return this.lex();
}
},
// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
begin:function begin(condition) {
this.conditionStack.push(condition);
},
// pop the previously active lexer condition state off the condition stack
popState:function popState() {
var n = this.conditionStack.length - 1;
if (n > 0) {
return this.conditionStack.pop();
} else {
return this.conditionStack[0];
}
},
// produce the lexer rule set which is active for the currently active lexer condition state
_currentRules:function _currentRules() {
if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
} else {
return this.conditions["INITIAL"].rules;
}
},
// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
topState:function topState(n) {
n = this.conditionStack.length - 1 - Math.abs(n || 0);
if (n >= 0) {
return this.conditionStack[n];
} else {
return "INITIAL";
}
},
// alias for begin(condition)
pushState:function pushState(condition) {
this.begin(condition);
},
// return the number of states currently on the stack
stateStackSize:function stateStackSize() {
return this.conditionStack.length;
},
options: {},
performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
var YYSTATE=YY_START;
switch($avoiding_name_collisions) {
case 0:/* skip whitespace */
break;
case 1:return 8;
break;
case 2:return 8;
break;
case 3:return 21;
break;
case 4:return 35;
break;
case 5:return 24;
break;
case 6:return 26;
break;
case 7:return 26;
break;
case 8:return 25;
break;
case 9:return 21;
break;
case 10:return 31;
break;
case 11:return 31;
break;
case 12:return 33;
break;
case 13:return 28;
break;
case 14:return 9;
break;
case 15:return ' ';
break;
case 16:return 32;
break;
case 17:return 27;
break;
case 18:return 29;
break;
case 19:return 30;
break;
case 20:return 18;
break;
case 21:return 19;
break;
case 22:return 17;
break;
case 23:return 11;
break;
case 24:return 20;
break;
case 25:return 12;
break;
case 26:return 13;
break;
case 27:return 15;
break;
case 28:return 14;
break;
case 29:return 16;
break;
case 30:return '"';
break;
case 31:return "'";
break;
case 32:return "!";
break;
case 33:return 10;
break;
case 34:return 34;
break;
case 35:return '#';
break;
case 36:return 5;
break;
}
},
rules: [/^(?:\s+)/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:[A-Za-z]{1,}[A-Za-z_0-9\.]+(?=[(]))/,/^(?:#[A-Z0-9\/]+(!|\?)?)/,/^(?:\$[A-Za-z]+\$[0-9]+)/,/^(?:\$[A-Za-z]+[0-9]+)/,/^(?:[A-Za-z]+\$[0-9]+)/,/^(?:[A-Za-z]+[0-9]+)/,/^(?:[A-Za-z\.]+(?=[(]))/,/^(?:[A-Za-z]{1,}[A-Za-z_0-9]+)/,/^(?:[A-Za-z_]+)/,/^(?:[0-9]+)/,/^(?:\[(.*)?\])/,/^(?:&)/,/^(?: )/,/^(?:[.])/,/^(?::)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\/)/,/^(?:-)/,/^(?:\+)/,/^(?:\^)/,/^(?:\()/,/^(?:\))/,/^(?:>)/,/^(?:<)/,/^(?:NOT\b)/,/^(?:")/,/^(?:')/,/^(?:!)/,/^(?:=)/,/^(?:%)/,/^(?:[#])/,/^(?:$)/],
conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"inclusive":true}}
});
return lexer;
})();
parser.lexer = lexer;
function Parser () {
this.yy = {};
}
Parser.prototype = parser;parser.Parser = Parser;
return new Parser;
})();
if (true) {
exports.parser = grammarParser;
exports.Parser = grammarParser.Parser;
exports.parse = function () { return grammarParser.parse.apply(grammarParser, arguments); };
if (typeof module !== 'undefined' && __webpack_require__.c[__webpack_require__.s] === module) {
exports.main(process.argv.slice(1));
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(42)(module), __webpack_require__(10)))
/***/ }),
/* 42 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.trimEdges = trimEdges;
/* eslint-disable import/prefer-default-export */
/**
* Trim value by cutting character starting from the beginning and ending at the same time.
*
* @param {String} string String to trimming.
* @param {Number} [margin=1] Number of character to cut.
* @returns {String}
*/
function trimEdges(string) {
var margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
string = string.substring(margin, string.length - margin);
return string;
}
/***/ })
/******/ ]);
});
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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 _hotFormulaParser = __webpack_require__(66);
var _array = __webpack_require__(0);
var _object = __webpack_require__(1);
var _localHooks = __webpack_require__(21);
var _localHooks2 = _interopRequireDefault(_localHooks);
var _utils = __webpack_require__(37);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var BARE_CELL_STRICT_REGEX = /^\$?[A-Z]+\$?\d+$/;
var BARE_CELL_REGEX = /\$?[A-Z]+\$?\d+/;
var CELL_REGEX = /(?:[^0-9A-Z$: ]|^)\s*(\$?[A-Z]+\$?\d+)\s*(?![0-9A-Z_: ])/g;
var RANGE_REGEX = /\$?[A-Z]+\$?\d+\s*:\s*\$?[A-Z]+\$?\d+/g;
var CELL_AND_RANGE_REGEX = /((?:[^0-9A-Z$: ]|^)\s*(\$?[A-Z]+\$?\d+)\s*(?![0-9A-Z_: ]))|(\$?[A-Z]+\$?\d+\s*:\s*\$?[A-Z]+\$?\d+)/g;
/**
* Component adds an ability to parse and modify formula expressions. It is designed for translating cell
* coordinates and cell ranges in any direction. By default, component translates only relative coordinates but this
* behavior can be overwritten by passing custom modifier which controls translating process.
*
* @class ExpressionModifier
* @util
*/
var ExpressionModifier = function () {
function ExpressionModifier(expression) {
_classCallCheck(this, ExpressionModifier);
/**
* Formula expression to modify.
*
* @type {String}
*/
this.expression = '';
/**
* Extracted cells and cells ranges.
*
* @type {Array}
*/
this.cells = [];
/**
* Function which can modify default behaviour of how cells and cell ranges will be translated.
*
* @type {null|Function}
*/
this.customModifier = null;
if (typeof expression === 'string') {
this.setExpression(expression);
}
}
/**
* Set formula expression to modify.
*
* @param {String} expression Formula expression to process.
* @returns {ExpressionModifier}
*/
_createClass(ExpressionModifier, [{
key: 'setExpression',
value: function setExpression(expression) {
this.cells.length = 0;
this.expression = (0, _utils.toUpperCaseFormula)(expression);
this._extractCells();
this._extractCellsRange();
return this;
}
/**
* Set function which can modify default behavior of how cells and cell ranges will be translated.
* The passed function will be called with 4 arguments:
* - cell, A cell object with structure
* like this: {start: {row, column}, end: {row, column}, origLabel, type: 'cell|range', refError, toLabel: () => {}}
* - axis, Type of currently processing axis ('row' or 'column')
* - delta, Number as distance to translate. Can be positive or negative.
* - startFromIndex, Base index which translation will be applied from.
*
* the function must return an array with 3 items, where:
* [
* deltaStart, Number as a delta to translate first part of coordinates.
* deltaEnd, Number as a delta to translate second part of coordinates (if cell range is modified).
* refError, Defines an error which refers to the situation when translated cell overcrossed the data boundary.
* ]
*
*
* @param {Function} customModifier Function with custom logic.
*/
}, {
key: 'useCustomModifier',
value: function useCustomModifier(customModifier) {
this.customModifier = customModifier;
}
/**
* Translate formula expression cells.
*
* @param {Object} delta Distance to move in proper direction.
* @param {Object} [startFrom] Coordinates which translation will be applied from.
* @returns {ExpressionModifier}
*/
}, {
key: 'translate',
value: function translate(_ref) {
var _this = this;
var deltaRow = _ref.row,
deltaColumn = _ref.column;
var startFrom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _array.arrayEach)(this.cells, function (cell) {
if (deltaRow != null) {
_this._translateCell(cell, 'row', deltaRow, startFrom.row);
}
if (deltaColumn != null) {
_this._translateCell(cell, 'column', deltaColumn, startFrom.column);
}
});
return this;
}
/**
* Translate object into string representation.
*
* @returns {String}
*/
}, {
key: 'toString',
value: function toString() {
var _this2 = this;
var expression = this.expression.replace(CELL_AND_RANGE_REGEX, function (match, p1, p2) {
var isSingleCell = match.indexOf(':') === -1;
var result = match;
var cellLabel = match;
var translatedCellLabel = null;
if (isSingleCell) {
cellLabel = BARE_CELL_STRICT_REGEX.test(p1) ? p1 : p2;
}
var cell = _this2._searchCell(cellLabel);
if (cell) {
translatedCellLabel = cell.refError ? (0, _hotFormulaParser.error)(_hotFormulaParser.ERROR_REF) : cell.toLabel();
if (isSingleCell) {
result = match.replace(cellLabel, translatedCellLabel);
} else {
result = translatedCellLabel;
}
}
return result;
});
if (!expression.startsWith('=')) {
expression = '=' + expression;
}
return expression;
}
/**
* Translate single cell.
*
* @param {Object} cell Cell object.
* @param {String} axis Axis to modify.
* @param {Number} delta Distance to move.
* @param {Number} [startFromIndex] Base index which translation will be applied from.
* @private
*/
}, {
key: '_translateCell',
value: function _translateCell(cell, axis, delta, startFromIndex) {
var start = cell.start,
end = cell.end;
var startIndex = start[axis].index;
var endIndex = end[axis].index;
var deltaStart = delta;
var deltaEnd = delta;
var refError = false;
if (this.customModifier) {
var _customModifier = this.customModifier(cell, axis, delta, startFromIndex);
var _customModifier2 = _slicedToArray(_customModifier, 3);
deltaStart = _customModifier2[0];
deltaEnd = _customModifier2[1];
refError = _customModifier2[2];
} else {
// By default only relative cells are translated, if meets absolute reset deltas to 0
if (start[axis].isAbsolute) {
deltaStart = 0;
}
if (end[axis].isAbsolute) {
deltaEnd = 0;
}
}
if (deltaStart && !refError) {
if (startIndex + deltaStart < 0) {
refError = true;
}
start[axis].index = Math.max(startIndex + deltaStart, 0);
}
if (deltaEnd && !refError) {
if (endIndex + deltaEnd < 0) {
refError = true;
}
end[axis].index = Math.max(endIndex + deltaEnd, 0);
}
if (refError) {
cell.refError = true;
}
}
/**
* Extract all cells from the formula expression.
*
* @private
*/
}, {
key: '_extractCells',
value: function _extractCells() {
var _this3 = this;
var matches = this.expression.match(CELL_REGEX);
if (!matches) {
return;
}
(0, _array.arrayEach)(matches, function (coord) {
coord = coord.match(BARE_CELL_REGEX);
if (!coord) {
return;
}
var _extractLabel = (0, _hotFormulaParser.extractLabel)(coord[0]),
_extractLabel2 = _slicedToArray(_extractLabel, 2),
row = _extractLabel2[0],
column = _extractLabel2[1];
_this3.cells.push(_this3._createCell({ row: row, column: column }, { row: row, column: column }, coord[0]));
});
}
/**
* Extract all cells range from the formula expression.
*
* @private
*/
}, {
key: '_extractCellsRange',
value: function _extractCellsRange() {
var _this4 = this;
var matches = this.expression.match(RANGE_REGEX);
if (!matches) {
return;
}
(0, _array.arrayEach)(matches, function (match) {
var _match$split = match.split(':'),
_match$split2 = _slicedToArray(_match$split, 2),
start = _match$split2[0],
end = _match$split2[1];
var _extractLabel3 = (0, _hotFormulaParser.extractLabel)(start),
_extractLabel4 = _slicedToArray(_extractLabel3, 2),
startRow = _extractLabel4[0],
startColumn = _extractLabel4[1];
var _extractLabel5 = (0, _hotFormulaParser.extractLabel)(end),
_extractLabel6 = _slicedToArray(_extractLabel5, 2),
endRow = _extractLabel6[0],
endColumn = _extractLabel6[1];
var startCell = {
row: startRow,
column: startColumn
};
var endCell = {
row: endRow,
column: endColumn
};
_this4.cells.push(_this4._createCell(startCell, endCell, match));
});
}
/**
* Search cell by its label.
*
* @param {String} label Cell label eq. `B4` or `$B$6`.
* @returns {Object|null}
* @private
*/
}, {
key: '_searchCell',
value: function _searchCell(label) {
var _arrayFilter = (0, _array.arrayFilter)(this.cells, function (cell) {
return cell.origLabel === label;
}),
_arrayFilter2 = _slicedToArray(_arrayFilter, 1),
cell = _arrayFilter2[0];
return cell || null;
}
/**
* Create object cell.
*
* @param {Object} start Start coordinates (top-left).
* @param {Object} end End coordinates (bottom-right).
* @param {String} label Original label name.
* @returns {Object}
* @private
*/
}, {
key: '_createCell',
value: function _createCell(start, end, label) {
return {
start: start,
end: end,
origLabel: label,
type: label.indexOf(':') === -1 ? 'cell' : 'range',
refError: false,
toLabel: function toLabel() {
var label = (0, _hotFormulaParser.toLabel)(this.start.row, this.start.column);
if (this.type === 'range') {
label += ':' + (0, _hotFormulaParser.toLabel)(this.end.row, this.end.column);
}
return label;
}
};
}
}]);
return ExpressionModifier;
}();
(0, _object.mixin)(ExpressionModifier, _localHooks2.default);
exports.default = ExpressionModifier;
/***/ }),
/* 68 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(68);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(38);
module.exports = function (target, src, safe) {
for (var key in src) redefine(target, key, src[key], safe);
return target;
};
/***/ }),
/* 71 */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 72 */
/***/ (function(module, exports) {
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(40);
var call = __webpack_require__(168);
var isArrayIter = __webpack_require__(169);
var anObject = __webpack_require__(20);
var toLength = __webpack_require__(28);
var getIterFn = __webpack_require__(170);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/* 74 */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(17);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(38);
var redefineAll = __webpack_require__(70);
var meta = __webpack_require__(42);
var forOf = __webpack_require__(73);
var anInstance = __webpack_require__(72);
var isObject = __webpack_require__(12);
var fails = __webpack_require__(26);
var $iterDetect = __webpack_require__(92);
var setToStringTag = __webpack_require__(58);
var inheritIfRequired = __webpack_require__(479);
module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
var Base = global[NAME];
var C = Base;
var ADDER = IS_MAP ? 'set' : 'add';
var proto = C && C.prototype;
var O = {};
var fixMethod = function (KEY) {
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function (a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a) {
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
}))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
C = wrapper(function (target, iterable) {
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base(), target, C);
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && proto.clear) delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(59);
var createDesc = __webpack_require__(56);
var toIObject = __webpack_require__(27);
var toPrimitive = __webpack_require__(86);
var has = __webpack_require__(32);
var IE8_DOM_DEFINE = __webpack_require__(164);
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(25) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(40);
var IObject = __webpack_require__(88);
var toObject = __webpack_require__(41);
var toLength = __webpack_require__(28);
var asc = __webpack_require__(480);
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ }),
/* 78 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hide = __webpack_require__(39);
var redefine = __webpack_require__(38);
var fails = __webpack_require__(26);
var defined = __webpack_require__(47);
var wks = __webpack_require__(16);
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var fns = exec(defined, SYMBOL, ''[KEY]);
var strfn = fns[0];
var rxfn = fns[1];
if (fails(function () {
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
})) {
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__(52);
var step = __webpack_require__(174);
var Iterators = __webpack_require__(57);
var toIObject = __webpack_require__(27);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(172)(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.spreadsheetColumnLabel = spreadsheetColumnLabel;
exports.spreadsheetColumnIndex = spreadsheetColumnIndex;
exports.createSpreadsheetData = createSpreadsheetData;
exports.createSpreadsheetObjectData = createSpreadsheetObjectData;
exports.createEmptySpreadsheetData = createEmptySpreadsheetData;
exports.translateRowsToColumns = translateRowsToColumns;
exports.cellMethodLookupFactory = cellMethodLookupFactory;
var _cellTypes = __webpack_require__(151);
var _object = __webpack_require__(1);
var COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var COLUMN_LABEL_BASE_LENGTH = COLUMN_LABEL_BASE.length;
/**
* Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc.
*
* @param {Number} index Column index.
* @returns {String}
*/
function spreadsheetColumnLabel(index) {
var dividend = index + 1;
var columnLabel = '';
var modulo = void 0;
while (dividend > 0) {
modulo = (dividend - 1) % COLUMN_LABEL_BASE_LENGTH;
columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
dividend = parseInt((dividend - modulo) / COLUMN_LABEL_BASE_LENGTH, 10);
}
return columnLabel;
}
/**
* Generates spreadsheet-like column index from theirs labels: A, B, C ...., Z, AA, AB, etc.
*
* @param {String} label Column label.
* @returns {Number}
*/
function spreadsheetColumnIndex(label) {
var result = 0;
if (label) {
for (var i = 0, j = label.length - 1; i < label.length; i += 1, j -= 1) {
result += Math.pow(COLUMN_LABEL_BASE_LENGTH, j) * (COLUMN_LABEL_BASE.indexOf(label[i]) + 1);
}
}
--result;
return result;
}
/**
* Creates 2D array of Excel-like values "A1", "A2", ...
*
* @param {Number} rows Number of rows to generate.
* @param {Number} columns Number of columns to generate.
* @returns {Array}
*/
function createSpreadsheetData() {
var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
var columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
var _rows = [],
i,
j;
for (i = 0; i < rows; i++) {
var row = [];
for (j = 0; j < columns; j++) {
row.push(spreadsheetColumnLabel(j) + (i + 1));
}
_rows.push(row);
}
return _rows;
}
/**
* Creates 2D array of Excel-like values "A1", "A2", as an array of objects.
*
* @param {Number} rows Number of rows to generate.
* @param {Number} colCount Number of columns to generate.
* @returns {Array}
*/
function createSpreadsheetObjectData() {
var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
var colCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
var _rows = [],
i,
j;
for (i = 0; i < rows; i++) {
var row = {};
for (j = 0; j < colCount; j++) {
row['prop' + j] = spreadsheetColumnLabel(j) + (i + 1);
}
_rows.push(row);
}
return _rows;
}
/**
* Generates an empty data object.
*
* @param {Number} rows Number of rows to generate.
* @param {Number} columns Number of columns to generate
* @returns {Array}
*/
function createEmptySpreadsheetData(rows, columns) {
var data = [];
var row = void 0;
for (var i = 0; i < rows; i++) {
row = [];
for (var j = 0; j < columns; j++) {
row.push('');
}
data.push(row);
}
return data;
}
function translateRowsToColumns(input) {
var i,
ilen,
j,
jlen,
output = [],
olen = 0;
for (i = 0, ilen = input.length; i < ilen; i++) {
for (j = 0, jlen = input[i].length; j < jlen; j++) {
if (j == olen) {
output.push([]);
olen++;
}
output[j].push(input[i][j]);
}
}
return output;
}
/**
* Factory that produces a function for searching methods (or any properties) which could be defined directly in
* table configuration or implicitly, within cell type definition.
*
* For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
* defined implicitly using "type" property.
*
* Methods/properties defined explicitly always takes precedence over those defined through "type".
*
* If the method/property is not found in an object, searching is continued recursively through prototype chain, until
* it reaches the Object.prototype.
*
*
* @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
* @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
* @returns {Function}
*/
function cellMethodLookupFactory(methodName, allowUndefined) {
allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;
return function cellMethodLookup(row, col) {
return function getMethodFromProperties(properties) {
if (!properties) {
return; // method not found
} else if ((0, _object.hasOwnProperty)(properties, methodName) && properties[methodName] !== void 0) {
// check if it is own and is not empty
return properties[methodName]; // method defined directly
} else if ((0, _object.hasOwnProperty)(properties, 'type') && properties.type) {
// check if it is own and is not empty
var type;
if (typeof properties.type != 'string') {
throw new Error('Cell type must be a string ');
}
type = (0, _cellTypes.getCellType)(properties.type);
if ((0, _object.hasOwnProperty)(type, methodName)) {
return type[methodName]; // method defined in type.
} else if (allowUndefined) {
return; // method does not defined in type (eg. validator), returns undefined
}
}
return getMethodFromProperties(Object.getPrototypeOf(properties));
}(typeof row == 'number' ? this.getCellMeta(row, col) : row);
};
}
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.DEFAULT_LANGUAGE_CODE = exports.getLanguagesDictionaries = exports.getDefaultLanguageDictionary = exports.hasLanguageDictionary = exports.getLanguageDictionary = exports.registerLanguageDictionary = undefined;
var _object = __webpack_require__(1);
var _utils = __webpack_require__(452);
var _staticRegister2 = __webpack_require__(48);
var _staticRegister3 = _interopRequireDefault(_staticRegister2);
var _enUS = __webpack_require__(543);
var _enUS2 = _interopRequireDefault(_enUS);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_LANGUAGE_CODE = _enUS2.default.languageCode;
var _staticRegister = (0, _staticRegister3.default)('languagesDictionaries'),
registerGloballyLanguageDictionary = _staticRegister.register,
getGlobalLanguageDictionary = _staticRegister.getItem,
hasGlobalLanguageDictionary = _staticRegister.hasItem,
getGlobalLanguagesDictionaries = _staticRegister.getValues;
/**
* Register language dictionary for specific language code.
*
* @param {String|Object} languageCodeOrDictionary Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE' or object representing dictionary.
* @param {Object} dictionary Dictionary for specific language (optional if first parameter has already dictionary).
*/
function registerLanguage(languageCodeOrDictionary, dictionary) {
var languageCode = languageCodeOrDictionary;
// Dictionary passed as first argument.
if ((0, _object.isObject)(languageCodeOrDictionary)) {
dictionary = languageCodeOrDictionary;
languageCode = dictionary.languageCode;
}
extendLanguageDictionary(languageCode, dictionary);
registerGloballyLanguageDictionary(languageCode, (0, _object.deepClone)(dictionary));
// We do not allow user to work with dictionary by reference, it can cause lot of bugs.
return (0, _object.deepClone)(dictionary);
};
/**
* Get language dictionary for specific language code.
*
* @param {String} languageCode Language code.
* @returns {Object} Object with constants representing identifiers for translation (as keys) and corresponding translation phrases (as values).
*/
function getLanguage(languageCode) {
if (!hasLanguage(languageCode)) {
return null;
}
return (0, _object.deepClone)(getGlobalLanguageDictionary(languageCode));
}
/**
*
* Get if language with specified language code was registered.
*
* @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
* @returns {Boolean}
*/
function hasLanguage(languageCode) {
return hasGlobalLanguageDictionary(languageCode);
}
/**
* Get default language dictionary.
*
* @returns {Object} Object with constants representing identifiers for translation (as keys) and corresponding translation phrases (as values).
*/
function getDefaultLanguage() {
return _enUS2.default;
}
/**
* Extend handled dictionary by default language dictionary. As result, if any dictionary key isn't defined for specific language, it will be filled with default language value ("dictionary gaps" are supplemented).
*
* @private
* @param {String} languageCode Language code.
* @param {Object} dictionary Dictionary which is extended.
*/
function extendLanguageDictionary(languageCode, dictionary) {
if (languageCode !== DEFAULT_LANGUAGE_CODE) {
(0, _utils.extendNotExistingKeys)(dictionary, getGlobalLanguageDictionary(DEFAULT_LANGUAGE_CODE));
}
}
/**
* Get registered language dictionaries.
*
* @returns {Array}
*/
function getLanguages() {
return getGlobalLanguagesDictionaries();
}
exports.registerLanguageDictionary = registerLanguage;
exports.getLanguageDictionary = getLanguage;
exports.hasLanguageDictionary = hasLanguage;
exports.getDefaultLanguageDictionary = getDefaultLanguage;
exports.getLanguagesDictionaries = getLanguages;
exports.DEFAULT_LANGUAGE_CODE = DEFAULT_LANGUAGE_CODE;
/**
* Automatically registers default dictionary.
*/
registerLanguage(_enUS2.default);
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _array = __webpack_require__(0);
var _object = __webpack_require__(1);
var _localHooks = __webpack_require__(21);
var _localHooks2 = _interopRequireDefault(_localHooks);
var _stateSaver = __webpack_require__(640);
var _stateSaver2 = _interopRequireDefault(_stateSaver);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @plugin Filters
* @class BaseComponent
*/
var BaseComponent = function () {
function BaseComponent(hotInstance) {
_classCallCheck(this, BaseComponent);
this.hot = hotInstance;
/**
* List of registered component UI elements.
*
* @type {Array}
*/
this.elements = [];
/**
* Flag which determines if element is hidden.
*
* @type {Boolean}
*/
this.hidden = false;
}
/**
* Reset elements to their initial state.
*/
_createClass(BaseComponent, [{
key: 'reset',
value: function reset() {
(0, _array.arrayEach)(this.elements, function (ui) {
return ui.reset();
});
}
/**
* Hide component.
*/
}, {
key: 'hide',
value: function hide() {
this.hidden = true;
}
/**
* Show component.
*/
}, {
key: 'show',
value: function show() {
this.hidden = false;
}
/**
* Check if component is hidden.
*
* @returns {Boolean}
*/
}, {
key: 'isHidden',
value: function isHidden() {
return this.hidden;
}
/**
* Destroy element.
*/
}, {
key: 'destroy',
value: function destroy() {
this.clearLocalHooks();
(0, _array.arrayEach)(this.elements, function (ui) {
return ui.destroy();
});
this.elements = null;
this.hot = null;
}
}]);
return BaseComponent;
}();
(0, _object.mixin)(BaseComponent, _localHooks2.default);
(0, _object.mixin)(BaseComponent, _stateSaver2.default);
exports.default = BaseComponent;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strong = __webpack_require__(163);
var validate = __webpack_require__(51);
var MAP = 'Map';
// 23.1 Map Objects
module.exports = __webpack_require__(75)(MAP, function (get) {
return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key) {
var entry = strong.getEntry(validate(this, MAP), key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value) {
return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(12);
var document = __webpack_require__(17).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(12);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(20);
var dPs = __webpack_require__(477);
var enumBugKeys = __webpack_require__(91);
var IE_PROTO = __webpack_require__(89)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(85)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(167).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(49);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(90)('keys');
var uid = __webpack_require__(55);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(17);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
module.exports = function (key) {
return store[key] || (store[key] = {});
};
/***/ }),
/* 91 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(16)('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strong = __webpack_require__(163);
var validate = __webpack_require__(51);
var SET = 'Set';
// 23.2 Set Objects
module.exports = __webpack_require__(75)(SET, function (get) {
return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value) {
return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var each = __webpack_require__(77)(0);
var redefine = __webpack_require__(38);
var meta = __webpack_require__(42);
var assign = __webpack_require__(178);
var weak = __webpack_require__(179);
var isObject = __webpack_require__(12);
var fails = __webpack_require__(26);
var validate = __webpack_require__(51);
var WEAK_MAP = 'WeakMap';
var getWeak = meta.getWeak;
var isExtensible = Object.isExtensible;
var uncaughtFrozenStore = weak.ufstore;
var tmp = {};
var InternalMap;
var wrapper = function (get) {
return function WeakMap() {
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key) {
if (isObject(key)) {
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value) {
return weak.def(validate(this, WEAK_MAP), key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(75)(WEAK_MAP, wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) {
InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function (key) {
var proto = $WeakMap.prototype;
var method = proto[key];
redefine(proto, key, function (a, b) {
// store frozen objects on internal weakmap shim
if (isObject(a) && !isExtensible(a)) {
if (!this._f) this._f = new InternalMap();
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var weak = __webpack_require__(179);
var validate = __webpack_require__(51);
var WEAK_SET = 'WeakSet';
// 23.4 WeakSet Objects
__webpack_require__(75)(WEAK_SET, function (get) {
return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value) {
return weak.def(validate(this, WEAK_SET), value, true);
}
}, weak, false, true);
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(74);
var global = __webpack_require__(17);
var ctx = __webpack_require__(40);
var classof = __webpack_require__(171);
var $export = __webpack_require__(5);
var isObject = __webpack_require__(12);
var aFunction = __webpack_require__(71);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(73);
var speciesConstructor = __webpack_require__(482);
var task = __webpack_require__(97).set;
var microtask = __webpack_require__(484)();
var newPromiseCapabilityModule = __webpack_require__(180);
var perform = __webpack_require__(485);
var promiseResolve = __webpack_require__(486);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[__webpack_require__(16)('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value);
if (domain) domain.exit();
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(70)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(58)($Promise, PROMISE);
__webpack_require__(175)(PROMISE);
Wrapper = __webpack_require__(50)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(92)(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(40);
var invoke = __webpack_require__(483);
var html = __webpack_require__(167);
var cel = __webpack_require__(85);
var global = __webpack_require__(17);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (__webpack_require__(49)(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__(17);
var has = __webpack_require__(32);
var DESCRIPTORS = __webpack_require__(25);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(38);
var META = __webpack_require__(42).KEY;
var $fails = __webpack_require__(26);
var shared = __webpack_require__(90);
var setToStringTag = __webpack_require__(58);
var uid = __webpack_require__(55);
var wks = __webpack_require__(16);
var wksExt = __webpack_require__(181);
var wksDefine = __webpack_require__(487);
var enumKeys = __webpack_require__(488);
var isArray = __webpack_require__(177);
var anObject = __webpack_require__(20);
var isObject = __webpack_require__(12);
var toIObject = __webpack_require__(27);
var toPrimitive = __webpack_require__(86);
var createDesc = __webpack_require__(56);
var _create = __webpack_require__(87);
var gOPNExt = __webpack_require__(182);
var $GOPD = __webpack_require__(76);
var $DP = __webpack_require__(22);
var $keys = __webpack_require__(46);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(99).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(59).f = $propertyIsEnumerable;
__webpack_require__(78).f = $getOwnPropertySymbols;
if (DESCRIPTORS && !__webpack_require__(74)) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(39)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(165);
var hiddenKeys = __webpack_require__(91).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(12);
var meta = __webpack_require__(42).onFreeze;
__webpack_require__(29)('freeze', function ($freeze) {
return function freeze(it) {
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(12);
var meta = __webpack_require__(42).onFreeze;
__webpack_require__(29)('seal', function ($seal) {
return function seal(it) {
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(12);
var meta = __webpack_require__(42).onFreeze;
__webpack_require__(29)('preventExtensions', function ($preventExtensions) {
return function preventExtensions(it) {
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(12);
__webpack_require__(29)('isFrozen', function ($isFrozen) {
return function isFrozen(it) {
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(12);
__webpack_require__(29)('isSealed', function ($isSealed) {
return function isSealed(it) {
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(12);
__webpack_require__(29)('isExtensible', function ($isExtensible) {
return function isExtensible(it) {
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(27);
var $getOwnPropertyDescriptor = __webpack_require__(76).f;
__webpack_require__(29)('getOwnPropertyDescriptor', function () {
return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(41);
var $getPrototypeOf = __webpack_require__(173);
__webpack_require__(29)('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(41);
var $keys = __webpack_require__(46);
__webpack_require__(29)('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(29)('getOwnPropertyNames', function () {
return __webpack_require__(182).f;
});
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(5);
$export($export.S + $export.F, 'Object', { assign: __webpack_require__(178) });
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(5);
$export($export.S, 'Object', { is: __webpack_require__(489) });
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(5);
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(176).set });
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(22).f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || __webpack_require__(25) && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var toIObject = __webpack_require__(27);
var toLength = __webpack_require__(28);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite) {
var tpl = toIObject(callSite.raw);
var len = toLength(tpl.length);
var aLen = arguments.length;
var res = [];
var i = 0;
while (len > i) {
res.push(String(tpl[i++]));
if (i < aLen) res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var toAbsoluteIndex = __webpack_require__(69);
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $at = __webpack_require__(490)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos) {
return $at(this, pos);
}
});
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(183)
});
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
var $export = __webpack_require__(5);
var toLength = __webpack_require__(28);
var context = __webpack_require__(119);
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(120)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(184);
var defined = __webpack_require__(47);
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(16)('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
var $export = __webpack_require__(5);
var toLength = __webpack_require__(28);
var context = __webpack_require__(119);
var ENDS_WITH = 'endsWith';
var $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(120)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /* , endPosition = @length */) {
var that = context(this, searchString, ENDS_WITH);
var endPosition = arguments.length > 1 ? arguments[1] : undefined;
var len = toLength(that.length);
var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
var search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
var $export = __webpack_require__(5);
var context = __webpack_require__(119);
var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(120)(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if (__webpack_require__(25) && /./g.flags != 'g') __webpack_require__(22).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(491)
});
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(79)('match', 1, function (defined, MATCH, $match) {
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(79)('replace', 2, function (defined, REPLACE, $replace) {
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue) {
'use strict';
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(79)('split', 2, function (defined, SPLIT, $split) {
'use strict';
var isRegExp = __webpack_require__(184);
var _split = $split;
var $push = [].push;
var $SPLIT = 'split';
var LENGTH = 'length';
var LAST_INDEX = 'lastIndex';
if (
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
) {
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function (separator, limit) {
var string = String(this);
if (separator === undefined && limit === 0) return [];
// If `separator` is not a regex, use native split
if (!isRegExp(separator)) return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while (match = separatorCopy.exec(string)) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
// eslint-disable-next-line no-loop-func
if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () {
for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined;
});
if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if (output[LENGTH] >= splitLimit) break;
}
if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if (lastLastIndex === string[LENGTH]) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
$split = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit) {
var O = defined(this);
var fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(79)('search', 1, function (defined, SEARCH, $search) {
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp) {
'use strict';
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ctx = __webpack_require__(40);
var $export = __webpack_require__(5);
var toObject = __webpack_require__(41);
var call = __webpack_require__(168);
var isArrayIter = __webpack_require__(169);
var toLength = __webpack_require__(28);
var createProperty = __webpack_require__(129);
var getIterFn = __webpack_require__(170);
$export($export.S + $export.F * !__webpack_require__(92)(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__(22);
var createDesc = __webpack_require__(56);
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var createProperty = __webpack_require__(129);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(26)(function () {
function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */) {
var index = 0;
var aLen = arguments.length;
var result = new (typeof this == 'function' ? this : Array)(aLen);
while (aLen > index) createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(5);
$export($export.P, 'Array', { copyWithin: __webpack_require__(492) });
__webpack_require__(52)('copyWithin');
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(5);
var $find = __webpack_require__(77)(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(52)(KEY);
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(5);
var $find = __webpack_require__(77)(6);
var KEY = 'findIndex';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(52)(KEY);
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(5);
$export($export.P, 'Array', { fill: __webpack_require__(493) });
__webpack_require__(52)('fill');
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(5);
var _isFinite = __webpack_require__(17).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it) {
return typeof it == 'number' && _isFinite(it);
}
});
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(5);
$export($export.S, 'Number', { isInteger: __webpack_require__(185) });
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(5);
var isInteger = __webpack_require__(185);
var abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number) {
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(5);
$export($export.S, 'Number', {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(5);
$export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(5);
$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(5);
$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(5);
var $includes = __webpack_require__(166)(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(52)('includes');
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(5);
var $values = __webpack_require__(186)(false);
$export($export.S, 'Object', {
values: function values(it) {
return $values(it);
}
});
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(5);
var $entries = __webpack_require__(186)(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(5);
var ownKeys = __webpack_require__(494);
var toIObject = __webpack_require__(27);
var gOPD = __webpack_require__(76);
var createProperty = __webpack_require__(129);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIObject(object);
var getDesc = gOPD.f;
var keys = ownKeys(O);
var result = {};
var i = 0;
var key, desc;
while (keys.length > i) {
desc = getDesc(O, key = keys[i++]);
if (desc !== undefined) createProperty(result, key, desc);
}
return result;
}
});
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(5);
var $pad = __webpack_require__(187);
var userAgent = __webpack_require__(188);
// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
padStart: function padStart(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(5);
var $pad = __webpack_require__(187);
var userAgent = __webpack_require__(188);
// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $task = __webpack_require__(97);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(80);
var getKeys = __webpack_require__(46);
var redefine = __webpack_require__(38);
var global = __webpack_require__(17);
var hide = __webpack_require__(39);
var Iterators = __webpack_require__(57);
var wks = __webpack_require__(16);
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;
var DOMIterables = {
CSSRuleList: true, // TODO: Not spec compliant, should be false.
CSSStyleDeclaration: false,
CSSValueList: false,
ClientRectList: false,
DOMRectList: false,
DOMStringList: false,
DOMTokenList: true,
DataTransferItemList: false,
FileList: false,
HTMLAllCollection: false,
HTMLCollection: false,
HTMLFormElement: false,
HTMLSelectElement: false,
MediaList: true, // TODO: Not spec compliant, should be false.
MimeTypeArray: false,
NamedNodeMap: false,
NodeList: true,
PaintRequestList: false,
Plugin: false,
PluginArray: false,
SVGLengthList: false,
SVGNumberList: false,
SVGPathSegList: false,
SVGPointList: false,
SVGStringList: false,
SVGTransformList: false,
SourceBufferList: false,
StyleSheetList: true, // TODO: Not spec compliant, should be false.
TextTrackCueList: false,
TextTrackList: false,
TouchList: false
};
for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
var NAME = collections[i];
var explicit = DOMIterables[NAME];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
var key;
if (proto) {
if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _coords = __webpack_require__(61);
var _coords2 = _interopRequireDefault(_coords);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* A cell range is a set of exactly two CellCoords (that can be the same or different).
*
* @class CellRange
*/
var CellRange = function () {
/**
* @param {CellCoords} highlight Used to draw bold border around a cell where selection was
* started and to edit the cell when you press Enter.
* @param {CellCoords} [from] Usually the same as highlight, but in Excel there is distinction - one can change
* highlight within a selection.
* @param {CellCoords} [to] End selection.
*/
function CellRange(highlight) {
var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : highlight;
var to = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : highlight;
_classCallCheck(this, CellRange);
this.highlight = highlight;
this.from = from;
this.to = to;
}
/**
* Set the new coordinates for highlighting selection.
*
* @param {CellCoords} coords Coordinates to use.
*/
_createClass(CellRange, [{
key: 'setHighlight',
value: function setHighlight(coords) {
this.highlight = coords;
return this;
}
/**
* Set the new coordinates where selection starts from.
*
* @param {CellCoords} coords Coordinates to use.
*/
}, {
key: 'setFrom',
value: function setFrom(coords) {
this.from = coords;
return this;
}
/**
* Set new coordinates where selection ends from.
*
* @param {CellCoords} coords Coordinates to use.
*/
}, {
key: 'setTo',
value: function setTo(coords) {
this.to = coords;
return this;
}
/**
* Checks if given coords are valid in context of a given Walkontable instance
*
* @param {Walkontable} wotInstance
* @returns {Boolean}
*/
}, {
key: 'isValid',
value: function isValid(wotInstance) {
return this.from.isValid(wotInstance) && this.to.isValid(wotInstance);
}
/**
* Checks if this cell range is restricted to one cell
*
* @returns {Boolean}
*/
}, {
key: 'isSingle',
value: function isSingle() {
return this.from.row === this.to.row && this.from.col === this.to.col;
}
/**
* Returns selected range height (in number of rows)
*
* @returns {Number}
*/
}, {
key: 'getHeight',
value: function getHeight() {
return Math.max(this.from.row, this.to.row) - Math.min(this.from.row, this.to.row) + 1;
}
/**
* Returns selected range width (in number of columns)
*
* @returns {Number}
*/
}, {
key: 'getWidth',
value: function getWidth() {
return Math.max(this.from.col, this.to.col) - Math.min(this.from.col, this.to.col) + 1;
}
/**
* Checks if given cell coords is within `from` and `to` cell coords of this range
*
* @param {CellCoords} cellCoords
* @returns {Boolean}
*/
}, {
key: 'includes',
value: function includes(cellCoords) {
var row = cellCoords.row,
col = cellCoords.col;
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
return topLeft.row <= row && bottomRight.row >= row && topLeft.col <= col && bottomRight.col >= col;
}
/**
* Checks if given range is within of this range
*
* @param {CellRange} testedRange
* @returns {Boolean}
*/
}, {
key: 'includesRange',
value: function includesRange(testedRange) {
return this.includes(testedRange.getTopLeftCorner()) && this.includes(testedRange.getBottomRightCorner());
}
/**
* Checks if given range is equal to this range
*
* @param {CellRange} testedRange
* @returns {Boolean}
*/
}, {
key: 'isEqual',
value: function isEqual(testedRange) {
return Math.min(this.from.row, this.to.row) === Math.min(testedRange.from.row, testedRange.to.row) && Math.max(this.from.row, this.to.row) === Math.max(testedRange.from.row, testedRange.to.row) && Math.min(this.from.col, this.to.col) === Math.min(testedRange.from.col, testedRange.to.col) && Math.max(this.from.col, this.to.col) === Math.max(testedRange.from.col, testedRange.to.col);
}
/**
* Checks if tested range overlaps with the range.
* Range A is considered to to be overlapping with range B if intersection of A and B or B and A is not empty.
*
* @param {CellRange} testedRange
* @returns {Boolean}
*/
}, {
key: 'overlaps',
value: function overlaps(testedRange) {
return testedRange.isSouthEastOf(this.getTopLeftCorner()) && testedRange.isNorthWestOf(this.getBottomRightCorner());
}
/**
* @param {CellRange} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isSouthEastOf',
value: function isSouthEastOf(testedCoords) {
return this.getTopLeftCorner().isSouthEastOf(testedCoords) || this.getBottomRightCorner().isSouthEastOf(testedCoords);
}
/**
* @param {CellRange} testedCoords
* @returns {Boolean}
*/
}, {
key: 'isNorthWestOf',
value: function isNorthWestOf(testedCoords) {
return this.getTopLeftCorner().isNorthWestOf(testedCoords) || this.getBottomRightCorner().isNorthWestOf(testedCoords);
}
/**
* Returns `true` if the provided range is overlapping the current range horizontally
* (e.g. the current range's last column is 5 and the provided range's first column is 3).
*
* @param {CellRange} range The range to check against.
* @returns {Boolean}
*/
}, {
key: 'isOverlappingHorizontally',
value: function isOverlappingHorizontally(range) {
return this.getTopRightCorner().col >= range.getTopLeftCorner().col && this.getTopRightCorner().col <= range.getTopRightCorner().col || this.getTopLeftCorner().col <= range.getTopRightCorner().col && this.getTopLeftCorner().col >= range.getTopLeftCorner().col;
}
/**
* Returns `true` if the provided range is overlapping the current range vertically
* (e.g. the current range's last row is 5 and the provided range's first row is 3).
*
* @param {CellRange} range The range to check against.
* @returns {Boolean}
*/
}, {
key: 'isOverlappingVertically',
value: function isOverlappingVertically(range) {
return this.getBottomRightCorner().row >= range.getTopRightCorner().row && this.getBottomRightCorner().row <= range.getBottomRightCorner().row || this.getTopRightCorner().row <= range.getBottomRightCorner().row && this.getTopRightCorner().row >= range.getTopRightCorner().row;
}
/**
* Adds a cell to a range (only if exceeds corners of the range). Returns information if range was expanded
*
* @param {CellCoords} cellCoords
* @returns {Boolean}
*/
}, {
key: 'expand',
value: function expand(cellCoords) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
if (cellCoords.row < topLeft.row || cellCoords.col < topLeft.col || cellCoords.row > bottomRight.row || cellCoords.col > bottomRight.col) {
this.from = new _coords2.default(Math.min(topLeft.row, cellCoords.row), Math.min(topLeft.col, cellCoords.col));
this.to = new _coords2.default(Math.max(bottomRight.row, cellCoords.row), Math.max(bottomRight.col, cellCoords.col));
return true;
}
return false;
}
/**
* @param {CellRange} expandingRange
* @returns {Boolean}
*/
}, {
key: 'expandByRange',
value: function expandByRange(expandingRange) {
if (this.includesRange(expandingRange) || !this.overlaps(expandingRange)) {
return false;
}
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var initialDirection = this.getDirection();
var expandingTopLeft = expandingRange.getTopLeftCorner();
var expandingBottomRight = expandingRange.getBottomRightCorner();
var resultTopRow = Math.min(topLeft.row, expandingTopLeft.row);
var resultTopCol = Math.min(topLeft.col, expandingTopLeft.col);
var resultBottomRow = Math.max(bottomRight.row, expandingBottomRight.row);
var resultBottomCol = Math.max(bottomRight.col, expandingBottomRight.col);
var finalFrom = new _coords2.default(resultTopRow, resultTopCol);
var finalTo = new _coords2.default(resultBottomRow, resultBottomCol);
this.from = finalFrom;
this.to = finalTo;
this.setDirection(initialDirection);
if (this.highlight.row === this.getBottomRightCorner().row && this.getVerticalDirection() === 'N-S') {
this.flipDirectionVertically();
}
if (this.highlight.col === this.getTopRightCorner().col && this.getHorizontalDirection() === 'W-E') {
this.flipDirectionHorizontally();
}
return true;
}
/**
* @returns {String}
*/
}, {
key: 'getDirection',
value: function getDirection() {
if (this.from.isNorthWestOf(this.to)) {
// NorthWest - SouthEast
return 'NW-SE';
} else if (this.from.isNorthEastOf(this.to)) {
// NorthEast - SouthWest
return 'NE-SW';
} else if (this.from.isSouthEastOf(this.to)) {
// SouthEast - NorthWest
return 'SE-NW';
} else if (this.from.isSouthWestOf(this.to)) {
// SouthWest - NorthEast
return 'SW-NE';
}
}
/**
* Get the vertical direction of the range.
*
* @returns {String} Available options: `N-S` (north->south), `S-N` (south->north).
*/
}, {
key: 'getVerticalDirection',
value: function getVerticalDirection() {
return ['NE-SW', 'NW-SE'].indexOf(this.getDirection()) > -1 ? 'N-S' : 'S-N';
}
/**
* Get the horizontal direction of the range.
*
* @returns {String} Available options: `W-E` (west->east), `E-W` (east->west).
*/
}, {
key: 'getHorizontalDirection',
value: function getHorizontalDirection() {
return ['NW-SE', 'SW-NE'].indexOf(this.getDirection()) > -1 ? 'W-E' : 'E-W';
}
/**
* @param {String} direction
*/
}, {
key: 'setDirection',
value: function setDirection(direction) {
switch (direction) {
case 'NW-SE':
var _ref = [this.getTopLeftCorner(), this.getBottomRightCorner()];
this.from = _ref[0];
this.to = _ref[1];
break;
case 'NE-SW':
var _ref2 = [this.getTopRightCorner(), this.getBottomLeftCorner()];
this.from = _ref2[0];
this.to = _ref2[1];
break;
case 'SE-NW':
var _ref3 = [this.getBottomRightCorner(), this.getTopLeftCorner()];
this.from = _ref3[0];
this.to = _ref3[1];
break;
case 'SW-NE':
var _ref4 = [this.getBottomLeftCorner(), this.getTopRightCorner()];
this.from = _ref4[0];
this.to = _ref4[1];
break;
default:
break;
}
}
/**
* Flip the direction vertically. (e.g. `NW-SE` changes to `SW-NE`)
*/
}, {
key: 'flipDirectionVertically',
value: function flipDirectionVertically() {
var direction = this.getDirection();
switch (direction) {
case 'NW-SE':
this.setDirection('SW-NE');
break;
case 'NE-SW':
this.setDirection('SE-NW');
break;
case 'SE-NW':
this.setDirection('NE-SW');
break;
case 'SW-NE':
this.setDirection('NW-SE');
break;
default:
break;
}
}
/**
* Flip the direction horizontally. (e.g. `NW-SE` changes to `NE-SW`)
*/
}, {
key: 'flipDirectionHorizontally',
value: function flipDirectionHorizontally() {
var direction = this.getDirection();
switch (direction) {
case 'NW-SE':
this.setDirection('NE-SW');
break;
case 'NE-SW':
this.setDirection('NW-SE');
break;
case 'SE-NW':
this.setDirection('SW-NE');
break;
case 'SW-NE':
this.setDirection('SE-NW');
break;
default:
break;
}
}
/**
* Get top left corner of this range
*
* @returns {CellCoords}
*/
}, {
key: 'getTopLeftCorner',
value: function getTopLeftCorner() {
return new _coords2.default(Math.min(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
}
/**
* Get bottom right corner of this range
*
* @returns {CellCoords}
*/
}, {
key: 'getBottomRightCorner',
value: function getBottomRightCorner() {
return new _coords2.default(Math.max(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
}
/**
* Get top right corner of this range
*
* @returns {CellCoords}
*/
}, {
key: 'getTopRightCorner',
value: function getTopRightCorner() {
return new _coords2.default(Math.min(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
}
/**
* Get bottom left corner of this range
*
* @returns {CellCoords}
*/
}, {
key: 'getBottomLeftCorner',
value: function getBottomLeftCorner() {
return new _coords2.default(Math.max(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
}
/**
* @param {CellCoords} coords
* @param {CellRange} expandedRange
* @returns {*}
*/
}, {
key: 'isCorner',
value: function isCorner(coords, expandedRange) {
if (expandedRange && expandedRange.includes(coords) && (this.getTopLeftCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.from.col)) || this.getTopRightCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.to.col)) || this.getBottomLeftCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.from.col)) || this.getBottomRightCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.to.col)))) {
return true;
}
return coords.isEqual(this.getTopLeftCorner()) || coords.isEqual(this.getTopRightCorner()) || coords.isEqual(this.getBottomLeftCorner()) || coords.isEqual(this.getBottomRightCorner());
}
/**
* @param {CellCoords} coords
* @param {CellRange} expandedRange
* @returns {CellCoords}
*/
}, {
key: 'getOppositeCorner',
value: function getOppositeCorner(coords, expandedRange) {
if (!(coords instanceof _coords2.default)) {
return false;
}
if (expandedRange) {
if (expandedRange.includes(coords)) {
if (this.getTopLeftCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.from.col))) {
return this.getBottomRightCorner();
}
if (this.getTopRightCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.to.col))) {
return this.getBottomLeftCorner();
}
if (this.getBottomLeftCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.from.col))) {
return this.getTopRightCorner();
}
if (this.getBottomRightCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.to.col))) {
return this.getTopLeftCorner();
}
}
}
if (coords.isEqual(this.getBottomRightCorner())) {
return this.getTopLeftCorner();
} else if (coords.isEqual(this.getTopLeftCorner())) {
return this.getBottomRightCorner();
} else if (coords.isEqual(this.getTopRightCorner())) {
return this.getBottomLeftCorner();
} else if (coords.isEqual(this.getBottomLeftCorner())) {
return this.getTopRightCorner();
}
}
/**
* @param {CellRange} range
* @returns {Array}
*/
}, {
key: 'getBordersSharedWith',
value: function getBordersSharedWith(range) {
if (!this.includesRange(range)) {
return [];
}
var thisBorders = {
top: Math.min(this.from.row, this.to.row),
bottom: Math.max(this.from.row, this.to.row),
left: Math.min(this.from.col, this.to.col),
right: Math.max(this.from.col, this.to.col)
};
var rangeBorders = {
top: Math.min(range.from.row, range.to.row),
bottom: Math.max(range.from.row, range.to.row),
left: Math.min(range.from.col, range.to.col),
right: Math.max(range.from.col, range.to.col)
};
var result = [];
if (thisBorders.top == rangeBorders.top) {
result.push('top');
}
if (thisBorders.right == rangeBorders.right) {
result.push('right');
}
if (thisBorders.bottom == rangeBorders.bottom) {
result.push('bottom');
}
if (thisBorders.left == rangeBorders.left) {
result.push('left');
}
return result;
}
/**
* Get inner selected cell coords defined by this range
*
* @returns {Array}
*/
}, {
key: 'getInner',
value: function getInner() {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (!(this.from.row === r && this.from.col === c) && !(this.to.row === r && this.to.col === c)) {
out.push(new _coords2.default(r, c));
}
}
}
return out;
}
/**
* Get all selected cell coords defined by this range
*
* @returns {Array}
*/
}, {
key: 'getAll',
value: function getAll() {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (topLeft.row === r && topLeft.col === c) {
out.push(topLeft);
} else if (bottomRight.row === r && bottomRight.col === c) {
out.push(bottomRight);
} else {
out.push(new _coords2.default(r, c));
}
}
}
return out;
}
/**
* Runs a callback function against all cells in the range. You can break the iteration by returning
* `false` in the callback function
*
* @param callback {Function}
*/
}, {
key: 'forAll',
value: function forAll(callback) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
var breakIteration = callback(r, c);
if (breakIteration === false) {
return;
}
}
}
}
/**
* Convert CellRange to literal object.
*
* @return {Object} Returns a literal object with `from` and `to` properties which each of that object
* contains `row` and `col` keys.
*/
}, {
key: 'toObject',
value: function toObject() {
return {
from: this.from.toObject(),
to: this.to.toObject()
};
}
}]);
return CellRange;
}();
exports.default = CellRange;
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getRegisteredCellTypes = exports.getRegisteredCellTypeNames = exports.hasCellType = exports.getCellType = exports.registerCellType = undefined;
var _staticRegister2 = __webpack_require__(48);
var _staticRegister3 = _interopRequireDefault(_staticRegister2);
var _editors = __webpack_require__(19);
var _renderers = __webpack_require__(15);
var _validators = __webpack_require__(36);
var _autocompleteType = __webpack_require__(528);
var _autocompleteType2 = _interopRequireDefault(_autocompleteType);
var _checkboxType = __webpack_require__(529);
var _checkboxType2 = _interopRequireDefault(_checkboxType);
var _dateType = __webpack_require__(530);
var _dateType2 = _interopRequireDefault(_dateType);
var _dropdownType = __webpack_require__(531);
var _dropdownType2 = _interopRequireDefault(_dropdownType);
var _handsontableType = __webpack_require__(532);
var _handsontableType2 = _interopRequireDefault(_handsontableType);
var _numericType = __webpack_require__(533);
var _numericType2 = _interopRequireDefault(_numericType);
var _passwordType = __webpack_require__(534);
var _passwordType2 = _interopRequireDefault(_passwordType);
var _textType = __webpack_require__(535);
var _textType2 = _interopRequireDefault(_textType);
var _timeType = __webpack_require__(536);
var _timeType2 = _interopRequireDefault(_timeType);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _staticRegister = (0, _staticRegister3.default)('cellTypes'),
register = _staticRegister.register,
getItem = _staticRegister.getItem,
hasItem = _staticRegister.hasItem,
getNames = _staticRegister.getNames,
getValues = _staticRegister.getValues;
_register('autocomplete', _autocompleteType2.default);
_register('checkbox', _checkboxType2.default);
_register('date', _dateType2.default);
_register('dropdown', _dropdownType2.default);
_register('handsontable', _handsontableType2.default);
_register('numeric', _numericType2.default);
_register('password', _passwordType2.default);
_register('text', _textType2.default);
_register('time', _timeType2.default);
/**
* Retrieve cell type object.
*
* @param {String} name Cell type identification.
* @returns {Object} Returns cell type object.
*/
function _getItem(name) {
if (!hasItem(name)) {
throw Error('You declared cell type "' + name + '" as a string that is not mapped to a known object.\n Cell type must be an object or a string mapped to an object registered by "Handsontable.cellTypes.registerCellType" method');
}
return getItem(name);
}
/**
* Register cell type under specified name.
*
* @param {String} name Cell type identification.
* @param {Object} type An object with contains keys (eq: `editor`, `renderer`, `validator`) which describes specified behaviour of the cell.
*/
function _register(name, type) {
var editor = type.editor,
renderer = type.renderer,
validator = type.validator;
if (editor) {
(0, _editors.registerEditor)(name, editor);
}
if (renderer) {
(0, _renderers.registerRenderer)(name, renderer);
}
if (validator) {
(0, _validators.registerValidator)(name, validator);
}
register(name, type);
}
exports.registerCellType = _register;
exports.getCellType = _getItem;
exports.hasCellType = hasItem;
exports.getRegisteredCellTypeNames = getNames;
exports.getRegisteredCellTypes = getValues;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _templateObject = _taggedTemplateLiteral(['Deprecation warning: This method is going to be removed in the next release. \n If you want to select a cell using props, please use the `selectCell` method.'], ['Deprecation warning: This method is going to be removed in the next release.\\x20\n If you want to select a cell using props, please use the \\`selectCell\\` method.']);
exports.default = Core;
var _element = __webpack_require__(2);
var _setting = __webpack_require__(153);
var _function = __webpack_require__(35);
var _mixed = __webpack_require__(13);
var _browser = __webpack_require__(33);
var _dataMap = __webpack_require__(537);
var _dataMap2 = _interopRequireDefault(_dataMap);
var _editorManager = __webpack_require__(540);
var _editorManager2 = _interopRequireDefault(_editorManager);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _object = __webpack_require__(1);
var _array = __webpack_require__(0);
var _templateLiteralTag = __webpack_require__(34);
var _plugins = __webpack_require__(6);
var _renderers = __webpack_require__(15);
var _validators = __webpack_require__(36);
var _string = __webpack_require__(31);
var _number = __webpack_require__(4);
var _tableView = __webpack_require__(541);
var _tableView2 = _interopRequireDefault(_tableView);
var _dataSource = __webpack_require__(542);
var _dataSource2 = _interopRequireDefault(_dataSource);
var _data = __webpack_require__(81);
var _recordTranslator = __webpack_require__(53);
var _rootInstance = __webpack_require__(449);
var _src = __webpack_require__(8);
var _pluginHooks = __webpack_require__(14);
var _pluginHooks2 = _interopRequireDefault(_pluginHooks);
var _defaultSettings = __webpack_require__(450);
var _defaultSettings2 = _interopRequireDefault(_defaultSettings);
var _cellTypes = __webpack_require__(151);
var _i18n = __webpack_require__(451);
var _dictionariesManager = __webpack_require__(82);
var _utils = __webpack_require__(452);
var _keyStateObserver = __webpack_require__(453);
var _selection = __webpack_require__(546);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
function _toConsumableArray(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 activeGuid = null;
/**
* Handsontable constructor
*
* @core
* @constructor Core
* @description
*
* After Handsontable is constructed, you can modify the grid behavior using the available public methods.
*
* ---
* ## How to call methods
*
* These are 2 equal ways to call a Handsontable method:
*
* ```js
* // all following examples assume that you constructed Handsontable like this
* var ht = new Handsontable(document.getElementById('example1'), options);
*
* // now, to use setDataAtCell method, you can either:
* ht.setDataAtCell(0, 0, 'new value');
* ```
*
* Alternatively, you can call the method using jQuery wrapper (__obsolete__, requires initialization using our jQuery guide
* ```js
* $('#example1').handsontable('setDataAtCell', 0, 0, 'new value');
* ```
* ---
*/
function Core(rootElement, userSettings) {
var _this = this;
var rootInstanceSymbol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var priv,
datamap,
dataSource,
grid,
editorManager,
preventScrollingToCell = false,
instance = this,
GridSettings = function GridSettings() {},
eventManager = new _eventManager2.default(instance);
(0, _object.extend)(GridSettings.prototype, _defaultSettings2.default.prototype); // create grid settings as a copy of default settings
(0, _object.extend)(GridSettings.prototype, userSettings); // overwrite defaults with user settings
(0, _object.extend)(GridSettings.prototype, expandType(userSettings));
(0, _utils.applyLanguageSetting)(GridSettings.prototype, userSettings.language);
if ((0, _rootInstance.hasValidParameter)(rootInstanceSymbol)) {
(0, _rootInstance.registerAsRootInstance)(this);
}
(0, _keyStateObserver.startObserving)();
this.rootElement = rootElement;
this.isHotTableEnv = (0, _element.isChildOfWebComponentTable)(this.rootElement);
_eventManager2.default.isHotTableEnv = this.isHotTableEnv;
this.container = document.createElement('div');
this.renderCall = false;
rootElement.insertBefore(this.container, rootElement.firstChild);
if ('pro' !== '\x63\x65' && (0, _rootInstance.isRootInstance)(this)) {
(0, _mixed._injectProductInfo)(userSettings.licenseKey, rootElement);
}
this.guid = 'ht_' + (0, _string.randomString)(); // this is the namespace for global events
var recordTranslator = (0, _recordTranslator.getTranslator)(instance);
dataSource = new _dataSource2.default(instance);
if (!this.rootElement.id || this.rootElement.id.substring(0, 3) === 'ht_') {
this.rootElement.id = this.guid; // if root element does not have an id, assign a random id
}
priv = {
cellSettings: [],
columnSettings: [],
columnsSettingConflicts: ['data', 'width', 'language'],
settings: new GridSettings(), // current settings instance
selRange: null, // exposed by public method `getSelectedRange`
isPopulated: null,
scrollable: null,
firstRun: true
};
var selection = new _selection.Selection(priv.settings, {
countCols: function countCols() {
return instance.countCols();
},
countRows: function countRows() {
return instance.countRows();
},
propToCol: function propToCol(prop) {
return datamap.propToCol(prop);
},
isEditorOpened: function isEditorOpened() {
return instance.getActiveEditor() ? instance.getActiveEditor().isOpened() : false;
}
});
this.selection = selection;
this.selection.addLocalHook('beforeSetRangeStart', function (cellCoords) {
_this.runHooks('beforeSetRangeStart', cellCoords);
});
this.selection.addLocalHook('beforeSetRangeStartOnly', function (cellCoords) {
_this.runHooks('beforeSetRangeStartOnly', cellCoords);
});
this.selection.addLocalHook('beforeSetRangeEnd', function (cellCoords) {
_this.runHooks('beforeSetRangeEnd', cellCoords);
if (cellCoords.row < 0) {
cellCoords.row = _this.view.wt.wtTable.getFirstVisibleRow();
}
if (cellCoords.col < 0) {
cellCoords.col = _this.view.wt.wtTable.getFirstVisibleColumn();
}
});
this.selection.addLocalHook('afterSetRangeEnd', function (cellCoords) {
var preventScrolling = (0, _object.createObjectPropListener)(false);
var selectionRange = _this.selection.getSelectedRange();
var _selectionRange$curre = selectionRange.current(),
from = _selectionRange$curre.from,
to = _selectionRange$curre.to;
var selectionLayerLevel = selectionRange.size() - 1;
_this.runHooks('afterSelection', from.row, from.col, to.row, to.col, preventScrolling, selectionLayerLevel);
_this.runHooks('afterSelectionByProp', from.row, instance.colToProp(from.col), to.row, instance.colToProp(to.col), preventScrolling, selectionLayerLevel);
var isHeaderSelected = false;
var areCoordsPositive = true;
if (_this.selection.selectedHeader.cols || _this.selection.selectedHeader.rows) {
isHeaderSelected = true;
}
if (cellCoords.row < 0 || cellCoords.col < 0) {
areCoordsPositive = false;
}
var scrollToCell = true;
if (preventScrollingToCell) {
scrollToCell = false;
}
if (preventScrolling.isTouched()) {
scrollToCell = !preventScrolling.value;
}
if (scrollToCell !== false && !isHeaderSelected && areCoordsPositive) {
if (_this.selection.selectedRange.current().from && !_this.selection.isMultiple()) {
_this.view.scrollViewport(_this.selection.selectedRange.current().from);
} else {
_this.view.scrollViewport(cellCoords);
}
}
if (_this.selection.selectedHeader.rows && _this.selection.selectedHeader.cols) {
(0, _element.addClass)(_this.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
} else if (_this.selection.selectedHeader.rows) {
(0, _element.removeClass)(_this.rootElement, 'ht__selection--columns');
(0, _element.addClass)(_this.rootElement, 'ht__selection--rows');
} else if (_this.selection.selectedHeader.cols) {
(0, _element.removeClass)(_this.rootElement, 'ht__selection--rows');
(0, _element.addClass)(_this.rootElement, 'ht__selection--columns');
} else {
(0, _element.removeClass)(_this.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
}
_this._refreshBorders(null);
});
this.selection.addLocalHook('afterSelectionFinished', function (cellRanges) {
var selectionLayerLevel = cellRanges.length - 1;
var _cellRanges$selection = cellRanges[selectionLayerLevel],
from = _cellRanges$selection.from,
to = _cellRanges$selection.to;
_this.runHooks('afterSelectionEnd', from.row, from.col, to.row, to.col, selectionLayerLevel);
_this.runHooks('afterSelectionEndByProp', from.row, instance.colToProp(from.col), to.row, instance.colToProp(to.col), selectionLayerLevel);
});
this.selection.addLocalHook('afterIsMultipleSelection', function (isMultiple) {
var changedIsMultiple = _this.runHooks('afterIsMultipleSelection', isMultiple.value);
if (isMultiple.value) {
isMultiple.value = changedIsMultiple;
}
});
this.selection.addLocalHook('beforeModifyTransformStart', function (cellCoordsDelta) {
_this.runHooks('modifyTransformStart', cellCoordsDelta);
});
this.selection.addLocalHook('afterModifyTransformStart', function (coords, rowTransformDir, colTransformDir) {
_this.runHooks('afterModifyTransformStart', coords, rowTransformDir, colTransformDir);
});
this.selection.addLocalHook('beforeModifyTransformEnd', function (cellCoordsDelta) {
_this.runHooks('modifyTransformEnd', cellCoordsDelta);
});
this.selection.addLocalHook('afterModifyTransformEnd', function (coords, rowTransformDir, colTransformDir) {
_this.runHooks('afterModifyTransformEnd', coords, rowTransformDir, colTransformDir);
});
this.selection.addLocalHook('afterDeselect', function (coords, rowTransformDir, colTransformDir) {
editorManager.destroyEditor();
_this._refreshBorders();
(0, _element.removeClass)(_this.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
_this.runHooks('afterDeselect');
});
this.selection.addLocalHook('insertRowRequire', function (totalRows) {
_this.alter('insert_row', totalRows, 1, 'auto');
});
this.selection.addLocalHook('insertColRequire', function (totalCols) {
_this.alter('insert_col', totalCols, 1, 'auto');
});
grid = {
/**
* Inserts or removes rows and columns.
*
* @memberof Core#
* @function alter
* @private
* @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col".
* @param {Number|Array} index Row or column visual index which from the alter action will be triggered.
* Alter actions such as "remove_row" and "remove_col" support array indexes in the
* format `[[index, amount], [index, amount]...]` this can be used to remove
* non-consecutive columns or rows in one call.
* @param {Number} amount Ammount rows or columns to remove.
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
*/
alter: function alter(action, index, amount, source, keepEmptyRows) {
var delta;
amount = amount || 1;
function spliceWith(data, index, count, toInject) {
var valueFactory = function valueFactory() {
var result = void 0;
if (toInject === 'array') {
result = [];
} else if (toInject === 'object') {
result = {};
}
return result;
};
var spliceArgs = (0, _array.arrayMap)(new Array(count), function () {
return valueFactory();
});
spliceArgs.unshift(index, 0);
data.splice.apply(data, _toConsumableArray(spliceArgs));
}
var normalizeIndexesGroup = function normalizeIndexesGroup(indexes) {
if (indexes.length === 0) {
return [];
}
var sortedIndexes = [].concat(_toConsumableArray(indexes));
// Sort the indexes in ascending order.
sortedIndexes.sort(function (_ref, _ref2) {
var _ref4 = _slicedToArray(_ref, 1),
indexA = _ref4[0];
var _ref3 = _slicedToArray(_ref2, 1),
indexB = _ref3[0];
if (indexA === indexB) {
return 0;
}
return indexA > indexB ? 1 : -1;
});
// Normalize the {index, amount} groups into bigger groups.
var normalizedIndexes = (0, _array.arrayReduce)(sortedIndexes, function (acc, _ref5) {
var _ref6 = _slicedToArray(_ref5, 2),
index = _ref6[0],
amount = _ref6[1];
var previousItem = acc[acc.length - 1];
var _previousItem = _slicedToArray(previousItem, 2),
prevIndex = _previousItem[0],
prevAmount = _previousItem[1];
var prevLastIndex = prevIndex + prevAmount;
if (index <= prevLastIndex) {
var amountToAdd = Math.max(amount - (prevLastIndex - index), 0);
previousItem[1] += amountToAdd;
} else {
acc.push([index, amount]);
}
return acc;
}, [sortedIndexes[0]]);
return normalizedIndexes;
};
/* eslint-disable no-case-declarations */
switch (action) {
case 'insert_row':
var numberOfSourceRows = instance.countSourceRows();
if (instance.getSettings().maxRows === numberOfSourceRows) {
return;
}
index = (0, _mixed.isDefined)(index) ? index : numberOfSourceRows;
delta = datamap.createRow(index, amount, source);
spliceWith(priv.cellSettings, index, amount, 'array');
if (delta) {
if (selection.isSelected() && selection.selectedRange.current().from.row >= index) {
selection.selectedRange.current().from.row += delta;
selection.transformEnd(delta, 0); // will call render() internally
} else {
instance._refreshBorders(); // it will call render and prepare methods
}
}
break;
case 'insert_col':
delta = datamap.createCol(index, amount, source);
for (var row = 0, len = instance.countSourceRows(); row < len; row++) {
if (priv.cellSettings[row]) {
spliceWith(priv.cellSettings[row], index, amount);
}
}
if (delta) {
if (Array.isArray(instance.getSettings().colHeaders)) {
var spliceArray = [index, 0];
spliceArray.length += delta; // inserts empty (undefined) elements at the end of an array
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); // inserts empty (undefined) elements into the colHeader array
}
if (selection.isSelected() && selection.selectedRange.current().from.col >= index) {
selection.selectedRange.current().from.col += delta;
selection.transformEnd(0, delta); // will call render() internally
} else {
instance._refreshBorders(); // it will call render and prepare methods
}
}
break;
case 'remove_row':
var removeRow = function removeRow(indexes) {
var offset = 0;
(0, _array.arrayEach)(indexes, function (_ref7) {
var _ref8 = _slicedToArray(_ref7, 2),
index = _ref8[0],
amount = _ref8[1];
var calcIndex = (0, _mixed.isEmpty)(index) ? instance.countRows() - 1 : Math.max(index - offset, 0);
// If the 'index' is an integer decrease it by 'offset' otherwise pass it through to make the value
// compatible with datamap.removeCol method.
if (Number.isInteger(index)) {
index = Math.max(index - offset, 0);
}
// TODO: for datamap.removeRow index should be passed as it is (with undefined and null values). If not, the logic
// inside the datamap.removeRow breaks the removing functionality.
datamap.removeRow(index, amount, source);
priv.cellSettings.splice(calcIndex, amount);
var totalRows = instance.countRows();
var fixedRowsTop = instance.getSettings().fixedRowsTop;
if (fixedRowsTop >= calcIndex + 1) {
instance.getSettings().fixedRowsTop -= Math.min(amount, fixedRowsTop - calcIndex);
}
var fixedRowsBottom = instance.getSettings().fixedRowsBottom;
if (fixedRowsBottom && calcIndex >= totalRows - fixedRowsBottom) {
instance.getSettings().fixedRowsBottom -= Math.min(amount, fixedRowsBottom);
}
offset += amount;
});
};
if (Array.isArray(index)) {
removeRow(normalizeIndexesGroup(index));
} else {
removeRow([[index, amount]]);
}
grid.adjustRowsAndCols();
instance._refreshBorders(); // it will call render and prepare methods
break;
case 'remove_col':
var removeCol = function removeCol(indexes) {
var offset = 0;
(0, _array.arrayEach)(indexes, function (_ref9) {
var _ref10 = _slicedToArray(_ref9, 2),
index = _ref10[0],
amount = _ref10[1];
var calcIndex = (0, _mixed.isEmpty)(index) ? instance.countCols() - 1 : Math.max(index - offset, 0);
var visualColumnIndex = recordTranslator.toPhysicalColumn(calcIndex);
// If the 'index' is an integer decrease it by 'offset' otherwise pass it through to make the value
// compatible with datamap.removeCol method.
if (Number.isInteger(index)) {
index = Math.max(index - offset, 0);
}
// TODO: for datamap.removeCol index should be passed as it is (with undefined and null values). If not, the logic
// inside the datamap.removeCol breaks the removing functionality.
datamap.removeCol(index, amount, source);
for (var _row = 0, _len = instance.countSourceRows(); _row < _len; _row++) {
if (priv.cellSettings[_row]) {
// if row hasn't been rendered it wouldn't have cellSettings
priv.cellSettings[_row].splice(visualColumnIndex, amount);
}
}
var fixedColumnsLeft = instance.getSettings().fixedColumnsLeft;
if (fixedColumnsLeft >= calcIndex + 1) {
instance.getSettings().fixedColumnsLeft -= Math.min(amount, fixedColumnsLeft - calcIndex);
}
if (Array.isArray(instance.getSettings().colHeaders)) {
if (typeof visualColumnIndex === 'undefined') {
visualColumnIndex = -1;
}
instance.getSettings().colHeaders.splice(visualColumnIndex, amount);
}
offset += amount;
});
};
if (Array.isArray(index)) {
removeCol(normalizeIndexesGroup(index));
} else {
removeCol([[index, amount]]);
}
grid.adjustRowsAndCols();
instance._refreshBorders(); // it will call render and prepare methods
break;
default:
throw new Error('There is no such action "' + action + '"');
}
if (!keepEmptyRows) {
grid.adjustRowsAndCols(); // makes sure that we did not add rows that will be removed in next refresh
}
},
/**
* Makes sure there are empty rows at the bottom of the table
*/
adjustRowsAndCols: function adjustRowsAndCols() {
if (priv.settings.minRows) {
// should I add empty rows to data source to meet minRows?
var rows = instance.countRows();
if (rows < priv.settings.minRows) {
for (var r = 0, minRows = priv.settings.minRows; r < minRows - rows; r++) {
datamap.createRow(instance.countRows(), 1, 'auto');
}
}
}
if (priv.settings.minSpareRows) {
var emptyRows = instance.countEmptyRows(true);
// should I add empty rows to meet minSpareRows?
if (emptyRows < priv.settings.minSpareRows) {
for (; emptyRows < priv.settings.minSpareRows && instance.countSourceRows() < priv.settings.maxRows; emptyRows++) {
datamap.createRow(instance.countRows(), 1, 'auto');
}
}
}
{
var emptyCols = void 0;
// count currently empty cols
if (priv.settings.minCols || priv.settings.minSpareCols) {
emptyCols = instance.countEmptyCols(true);
}
// should I add empty cols to meet minCols?
if (priv.settings.minCols && !priv.settings.columns && instance.countCols() < priv.settings.minCols) {
for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, 'auto');
}
}
// should I add empty cols to meet minSpareCols?
if (priv.settings.minSpareCols && !priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, 'auto');
}
}
}
var rowCount = instance.countRows();
var colCount = instance.countCols();
if (rowCount === 0 || colCount === 0) {
selection.deselect();
}
if (selection.isSelected()) {
(0, _array.arrayEach)(selection.selectedRange, function (range) {
var selectionChanged = false;
var fromRow = range.from.row;
var fromCol = range.from.col;
var toRow = range.to.row;
var toCol = range.to.col;
// if selection is outside, move selection to last row
if (fromRow > rowCount - 1) {
fromRow = rowCount - 1;
selectionChanged = true;
if (toRow > fromRow) {
toRow = fromRow;
}
} else if (toRow > rowCount - 1) {
toRow = rowCount - 1;
selectionChanged = true;
if (fromRow > toRow) {
fromRow = toRow;
}
}
// if selection is outside, move selection to last row
if (fromCol > colCount - 1) {
fromCol = colCount - 1;
selectionChanged = true;
if (toCol > fromCol) {
toCol = fromCol;
}
} else if (toCol > colCount - 1) {
toCol = colCount - 1;
selectionChanged = true;
if (fromCol > toCol) {
fromCol = toCol;
}
}
if (selectionChanged) {
instance.selectCell(fromRow, fromCol, toRow, toCol);
}
});
}
if (instance.view) {
instance.view.wt.wtOverlays.adjustElementsSize();
}
},
/**
* Populate the data from the provided 2d array from the given cell coordinates.
*
* @private
* @param {Object} start Start selection position. Visual indexes.
* @param {Array} input 2d data array.
* @param {Object} [end] End selection position (only for drag-down mode). Visual indexes.
* @param {String} [source="populateFromArray"] Source information string.
* @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
* @param {String} direction (left|right|up|down) String specifying the direction.
* @param {Array} deltas The deltas array. A difference between values of adjacent cells.
* Useful **only** when the type of handled cells is `numeric`.
* @returns {Object|undefined} ending td in pasted area (only if any cell was changed).
*/
populateFromArray: function populateFromArray(start, input, end, source, method, direction, deltas) {
// TODO: either remove or implement the `direction` argument. Currently it's not working at all.
var r,
rlen,
c,
clen,
setData = [],
current = {};
rlen = input.length;
if (rlen === 0) {
return false;
}
var repeatCol,
repeatRow,
cmax,
rmax,
baseEnd = {
row: end === null ? null : end.row,
col: end === null ? null : end.col
};
/* eslint-disable no-case-declarations */
// insert data with specified pasteMode method
switch (method) {
case 'shift_down':
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
input = (0, _data.translateRowsToColumns)(input);
for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
if (c < clen) {
var _instance;
for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
input[c].push(input[c][r % rlen]);
}
input[c].unshift(start.col + c, start.row, 0);
(_instance = instance).spliceCol.apply(_instance, _toConsumableArray(input[c]));
} else {
var _instance2;
input[c % clen][0] = start.col + c;
(_instance2 = instance).spliceCol.apply(_instance2, _toConsumableArray(input[c % clen]));
}
}
break;
case 'shift_right':
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
if (r < rlen) {
var _instance3;
for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
input[r].push(input[r][c % clen]);
}
input[r].unshift(start.row + r, start.col, 0);
(_instance3 = instance).spliceRow.apply(_instance3, _toConsumableArray(input[r]));
} else {
var _instance4;
input[r % rlen][0] = start.row + r;
(_instance4 = instance).spliceRow.apply(_instance4, _toConsumableArray(input[r % rlen]));
}
}
break;
case 'overwrite':
default:
// overwrite and other not specified options
current.row = start.row;
current.col = start.col;
var selected = { // selected range
row: end && start ? end.row - start.row + 1 : 1,
col: end && start ? end.col - start.col + 1 : 1
};
var skippedRow = 0;
var skippedColumn = 0;
var pushData = true;
var cellMeta = void 0;
var getInputValue = function getInputValue(row) {
var col = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var rowValue = input[row % input.length];
if (col !== null) {
return rowValue[col % rowValue.length];
}
return rowValue;
};
var rowInputLength = input.length;
var rowSelectionLength = end ? end.row - start.row + 1 : 0;
if (end) {
rlen = rowSelectionLength;
} else {
rlen = Math.max(rowInputLength, rowSelectionLength);
}
for (r = 0; r < rlen; r++) {
if (end && current.row > end.row && rowSelectionLength > rowInputLength || !priv.settings.allowInsertRow && current.row > instance.countRows() - 1 || current.row >= priv.settings.maxRows) {
break;
}
var visualRow = r - skippedRow;
var colInputLength = getInputValue(visualRow).length;
var colSelectionLength = end ? end.col - start.col + 1 : 0;
if (end) {
clen = colSelectionLength;
} else {
clen = Math.max(colInputLength, colSelectionLength);
}
current.col = start.col;
cellMeta = instance.getCellMeta(current.row, current.col);
if ((source === 'CopyPaste.paste' || source === 'Autofill.autofill') && cellMeta.skipRowOnPaste) {
skippedRow++;
current.row++;
rlen++;
/* eslint-disable no-continue */
continue;
}
skippedColumn = 0;
for (c = 0; c < clen; c++) {
if (end && current.col > end.col && colSelectionLength > colInputLength || !priv.settings.allowInsertColumn && current.col > instance.countCols() - 1 || current.col >= priv.settings.maxCols) {
break;
}
cellMeta = instance.getCellMeta(current.row, current.col);
if ((source === 'CopyPaste.paste' || source === 'Autofill.fill') && cellMeta.skipColumnOnPaste) {
skippedColumn++;
current.col++;
clen++;
continue;
}
if (cellMeta.readOnly) {
current.col++;
/* eslint-disable no-continue */
continue;
}
var visualColumn = c - skippedColumn;
var value = getInputValue(visualRow, visualColumn);
var orgValue = instance.getDataAtCell(current.row, current.col);
var index = {
row: visualRow,
col: visualColumn
};
if (source === 'Autofill.fill') {
var result = instance.runHooks('beforeAutofillInsidePopulate', index, direction, input, deltas, {}, selected);
if (result) {
value = (0, _mixed.isUndefined)(result.value) ? value : result.value;
}
}
if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (orgValue === null || (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) !== 'object') {
pushData = false;
} else {
var orgValueSchema = (0, _object.duckSchema)(orgValue[0] || orgValue);
var valueSchema = (0, _object.duckSchema)(value[0] || value);
/* eslint-disable max-depth */
if ((0, _object.isObjectEqual)(orgValueSchema, valueSchema)) {
value = (0, _object.deepClone)(value);
} else {
pushData = false;
}
}
} else if (orgValue !== null && (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) === 'object') {
pushData = false;
}
if (pushData) {
setData.push([current.row, current.col, value]);
}
pushData = true;
current.col++;
}
current.row++;
}
instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
break;
}
}
};
/**
* Internal function to set `language` key of settings.
*
* @private
* @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'
* @fires Hooks#afterLanguageChange
*/
function setLanguage(languageCode) {
var normalizedLanguageCode = (0, _utils.normalizeLanguageCode)(languageCode);
if ((0, _dictionariesManager.hasLanguageDictionary)(normalizedLanguageCode)) {
instance.runHooks('beforeLanguageChange', normalizedLanguageCode);
GridSettings.prototype.language = normalizedLanguageCode;
instance.runHooks('afterLanguageChange', normalizedLanguageCode);
} else {
(0, _utils.warnUserAboutLanguageRegistration)(languageCode);
}
}
this.init = function () {
dataSource.setData(priv.settings.data);
instance.runHooks('beforeInit');
if ((0, _browser.isMobileBrowser)()) {
(0, _element.addClass)(instance.rootElement, 'mobile');
}
this.updateSettings(priv.settings, true);
this.view = new _tableView2.default(this);
editorManager = _editorManager2.default.getInstance(instance, priv, selection, datamap);
this.forceFullRender = true; // used when data was changed
instance.runHooks('init');
this.view.render();
if (_typeof(priv.firstRun) === 'object') {
instance.runHooks('afterChange', priv.firstRun[0], priv.firstRun[1]);
priv.firstRun = false;
}
instance.runHooks('afterInit');
};
function ValidatorsQueue() {
// moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
var resolved = false;
return {
validatorsInQueue: 0,
valid: true,
addValidatorToQueue: function addValidatorToQueue() {
this.validatorsInQueue++;
resolved = false;
},
removeValidatorFormQueue: function removeValidatorFormQueue() {
this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
this.checkIfQueueIsEmpty();
},
onQueueEmpty: function onQueueEmpty(valid) {},
checkIfQueueIsEmpty: function checkIfQueueIsEmpty() {
if (this.validatorsInQueue == 0 && resolved == false) {
resolved = true;
this.onQueueEmpty(this.valid);
}
}
};
}
/**
* Get parsed number from numeric string.
*
* @private
* @param {String} numericData Float (separated by a dot or a comma) or integer.
* @returns {Number} Number if we get data in parsable format, not changed value otherwise.
*/
function getParsedNumber(numericData) {
// Unifying "float like" string. Change from value with comma determiner to value with dot determiner,
// for example from `450,65` to `450.65`.
var unifiedNumericData = numericData.replace(',', '.');
if (isNaN(parseFloat(unifiedNumericData)) === false) {
return parseFloat(unifiedNumericData);
}
return numericData;
}
function validateChanges(changes, source, callback) {
var waitingForValidator = new ValidatorsQueue();
var isNumericData = function isNumericData(value) {
return value.length > 0 && /^-?[\d\s]*(\.|,)?\d*$/.test(value);
};
waitingForValidator.onQueueEmpty = resolve;
for (var i = changes.length - 1; i >= 0; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
} else {
var _changes$i = _slicedToArray(changes[i], 4),
row = _changes$i[0],
prop = _changes$i[1],
newValue = _changes$i[3];
var col = datamap.propToCol(prop);
var cellProperties = instance.getCellMeta(row, col);
if (cellProperties.type === 'numeric' && typeof newValue === 'string' && isNumericData(newValue)) {
changes[i][3] = getParsedNumber(newValue);
}
/* eslint-disable no-loop-func */
if (instance.getCellValidator(cellProperties)) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(changes[i][3], cellProperties, function (i, cellProperties) {
return function (result) {
if (typeof result !== 'boolean') {
throw new Error('Validation error: result is not boolean');
}
if (result === false && cellProperties.allowInvalid === false) {
changes.splice(i, 1); // cancel the change
cellProperties.valid = true; // we cancelled the change, so cell value is still valid
var cell = instance.getCell(cellProperties.visualRow, cellProperties.visualCol);
(0, _element.removeClass)(cell, instance.getSettings().invalidCellClassName);
--i;
}
waitingForValidator.removeValidatorFormQueue();
};
}(i, cellProperties), source);
}
}
}
waitingForValidator.checkIfQueueIsEmpty();
function resolve() {
var beforeChangeResult;
if (changes.length) {
beforeChangeResult = instance.runHooks('beforeChange', changes, source || 'edit');
if ((0, _function.isFunction)(beforeChangeResult)) {
console.warn('Your beforeChange callback returns a function. It\'s not supported since Handsontable 0.12.1 (and the returned function will not be executed).');
} else if (beforeChangeResult === false) {
changes.splice(0, changes.length); // invalidate all changes (remove everything from array)
}
}
callback(); // called when async validators are resolved and beforeChange was not async
}
}
/**
* Internal function to apply changes. Called after validateChanges
*
* @private
* @param {Array} changes Array in form of [row, prop, oldValue, newValue]
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
* @fires Hooks#beforeChangeRender
* @fires Hooks#afterChange
*/
function applyChanges(changes, source) {
var i = changes.length - 1;
if (i < 0) {
return;
}
for (; i >= 0; i--) {
var skipThisChange = false;
if (changes[i] === null) {
changes.splice(i, 1);
/* eslint-disable no-continue */
continue;
}
if (changes[i][2] == null && changes[i][3] == null) {
/* eslint-disable no-continue */
continue;
}
if (priv.settings.allowInsertRow) {
while (changes[i][0] > instance.countRows() - 1) {
var numberOfCreatedRows = datamap.createRow(void 0, void 0, source);
if (numberOfCreatedRows === 0) {
skipThisChange = true;
break;
}
}
}
if (skipThisChange) {
/* eslint-disable no-continue */
continue;
}
if (instance.dataType === 'array' && (!priv.settings.columns || priv.settings.columns.length === 0) && priv.settings.allowInsertColumn) {
while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
datamap.createCol(void 0, void 0, source);
}
}
datamap.set(changes[i][0], changes[i][1], changes[i][3]);
}
instance.forceFullRender = true; // used when data was changed
grid.adjustRowsAndCols();
instance.runHooks('beforeChangeRender', changes, source);
editorManager.lockEditor();
instance._refreshBorders(null);
editorManager.unlockEditor();
instance.view.wt.wtOverlays.adjustElementsSize();
instance.runHooks('afterChange', changes, source || 'edit');
var activeEditor = instance.getActiveEditor();
if (activeEditor && (0, _mixed.isDefined)(activeEditor.refreshValue)) {
activeEditor.refreshValue();
}
}
/**
* Validate a single cell.
*
* @param {String|Number} value
* @param cellProperties
* @param callback
* @param source
*/
this.validateCell = function (value, cellProperties, callback, source) {
var validator = instance.getCellValidator(cellProperties);
// the `canBeValidated = false` argument suggests, that the cell passes validation by default.
function done(valid) {
var canBeValidated = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
// Fixes GH#3903
if (!canBeValidated || cellProperties.hidden === true) {
callback(valid);
return;
}
var col = cellProperties.visualCol,
row = cellProperties.visualRow,
td = instance.getCell(row, col, true);
if (td && td.nodeName != 'TH') {
instance.view.wt.wtSettings.settings.cellRenderer(row, col, td);
}
callback(valid);
}
if ((0, _mixed.isRegExp)(validator)) {
validator = function (validator) {
return function (value, callback) {
callback(validator.test(value));
};
}(validator);
}
if ((0, _function.isFunction)(validator)) {
value = instance.runHooks('beforeValidate', value, cellProperties.visualRow, cellProperties.prop, source);
// To provide consistent behaviour, validation should be always asynchronous
instance._registerTimeout(setTimeout(function () {
validator.call(cellProperties, value, function (valid) {
valid = instance.runHooks('afterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
cellProperties.valid = valid;
done(valid);
instance.runHooks('postAfterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
});
}, 0));
} else {
// resolve callback even if validator function was not found
instance._registerTimeout(setTimeout(function () {
cellProperties.valid = true;
done(cellProperties.valid, false);
}, 0));
}
};
function setDataInputToArray(row, propOrCol, value) {
if ((typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
// is it an array of changes
return row;
}
return [[row, propOrCol, value]];
}
/**
* @description
* Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, col, value], ...]` as
* the only parameter. `col` is the index of a __visible__ column (note that if columns were reordered,
* the current visible order will be used). `source` is a flag for before/afterChange events. If you pass only array of
* changes then `source` could be set as second parameter.
*
* @memberof Core#
* @function setDataAtCell
* @param {Number|Array} row Visual row index or array of changes in format `[[row, col, value], ...]`.
* @param {Number} col Visual column index.
* @param {String} value New value.
* @param {String} [source] String that identifies how this change will be described in the changes array (useful in onAfterChange or onBeforeChange callback).
*/
this.setDataAtCell = function (row, col, value, source) {
var input = setDataInputToArray(row, col, value),
i,
ilen,
changes = [],
prop;
for (i = 0, ilen = input.length; i < ilen; i++) {
if (_typeof(input[i]) !== 'object') {
throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
}
if (typeof input[i][1] !== 'number') {
throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
}
prop = datamap.colToProp(input[i][1]);
changes.push([input[i][0], prop, dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
}
if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
source = col;
}
instance.runHooks('afterSetDataAtCell', changes, source);
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* @description
* Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, prop, value], ...]` as
* the only parameter. `prop` is the name of the object property (e.g. `first.name`). `source` is a flag for before/afterChange events.
* If you pass only array of changes then `source` could be set as second parameter.
*
* @memberof Core#
* @function setDataAtRowProp
* @param {Number|Array} row Visual row index or array of changes in format `[[row, prop, value], ...]`.
* @param {String} prop Property name or the source string.
* @param {String} value Value to be set.
* @param {String} [source] String that identifies how this change will be described in changes array (useful in onChange callback).
*/
this.setDataAtRowProp = function (row, prop, value, source) {
var input = setDataInputToArray(row, prop, value),
i,
ilen,
changes = [];
for (i = 0, ilen = input.length; i < ilen; i++) {
changes.push([input[i][0], input[i][1], dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
}
if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
source = prop;
}
instance.runHooks('afterSetDataAtRowProp', changes, source);
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Listen to the keyboard input on document body.
*
* @memberof Core#
* @function listen
* @since 0.11
* @param {Boolean} [modifyDocumentFocus=true] If `true`, currently focused element will be blured (which returns focus
* to the document.body). Otherwise the active element does not lose its focus.
*/
this.listen = function () {
var modifyDocumentFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (modifyDocumentFocus) {
var invalidActiveElement = !document.activeElement || document.activeElement && document.activeElement.nodeName === void 0;
if (document.activeElement && document.activeElement !== document.body && !invalidActiveElement) {
document.activeElement.blur();
} else if (invalidActiveElement) {
// IE
document.body.focus();
}
}
if (instance && !instance.isListening()) {
activeGuid = instance.guid;
instance.runHooks('afterListen');
}
};
/**
* Stop listening to keyboard input on the document body.
*
* @memberof Core#
* @function unlisten
* @since 0.11
*/
this.unlisten = function () {
if (this.isListening()) {
activeGuid = null;
instance.runHooks('afterUnlisten');
}
};
/**
* Returns `true` if the current Handsontable instance is listening to keyboard input on document body.
*
* @memberof Core#
* @function isListening
* @since 0.11
* @returns {Boolean} `true` if the instance is listening, `false` otherwise.
*/
this.isListening = function () {
return activeGuid === instance.guid;
};
/**
* Destroys the current editor, renders and selects the current cell.
*
* @memberof Core#
* @function destroyEditor
* @param {Boolean} [revertOriginal] If != `true`, edited data is saved. Otherwise the previous value is restored.
*/
this.destroyEditor = function (revertOriginal) {
instance._refreshBorders(revertOriginal);
};
/**
* Populate cells at position with 2D input array (e.g. `[[1, 2], [3, 4]]`).
* Use `endRow`, `endCol` when you want to cut input when a certain row is reached.
* Optional `source` parameter (default value "populateFromArray") is used to identify this call in the resulting events (beforeChange, afterChange).
* Optional `populateMethod` parameter (default value "overwrite", possible values "shift_down" and "shift_right")
* has the same effect as pasteMode option {@link Options#pasteMode}
*
* @memberof Core#
* @function populateFromArray
* @since 0.9.0
* @param {Number} row Start visual row index.
* @param {Number} col Start visual column index.
* @param {Array} input 2d array
* @param {Number} [endRow] End visual row index (use when you want to cut input when certain row is reached).
* @param {Number} [endCol] End visual column index (use when you want to cut input when certain column is reached).
* @param {String} [source="populateFromArray"] Source string.
* @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
* @param {String} direction Populate direction. (left|right|up|down)
* @param {Array} deltas Deltas array.
* @returns {Object|undefined} The ending TD element in pasted area (only if any cells were changed).
*/
this.populateFromArray = function (row, col, input, endRow, endCol, source, method, direction, deltas) {
var c;
if (!((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && _typeof(input[0]) === 'object')) {
throw new Error('populateFromArray parameter `input` must be an array of arrays'); // API changed in 0.9-beta2, let's check if you use it correctly
}
c = typeof endRow === 'number' ? new _src.CellCoords(endRow, endCol) : null;
return grid.populateFromArray(new _src.CellCoords(row, col), input, c, source, method, direction, deltas);
};
/**
* Adds/removes data from the column. This function is modelled after Array.splice.
* Parameter `col` is the index of the column in which do you want to do splice.
* Parameter `index` is the row index at which to start changing the array.
* If negative, will begin that many elements from the end. Parameter `amount`, is the number of the old array elements to remove.
* If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
* If you don't specify any elements, spliceCol simply removes elements from the array.
* {@link DataMap#spliceCol}
*
* @memberof Core#
* @function spliceCol
* @since 0.9-beta2
* @param {Number} col Index of the column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
* @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
*/
this.spliceCol = function (col, index, amount /* , elements... */) {
var _datamap;
return (_datamap = datamap).spliceCol.apply(_datamap, arguments);
};
/**
* Adds/removes data from the row. This function works is modelled after Array.splice.
* Parameter `row` is the index of row in which do you want to do splice.
* Parameter `index` is the column index at which to start changing the array.
* If negative, will begin that many elements from the end. Parameter `amount`, is the number of old array elements to remove.
* If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
* If you don't specify any elements, spliceCol simply removes elements from the array.
* {@link DataMap#spliceRow}
*
* @memberof Core#
* @function spliceRow
* @since 0.11
* @param {Number} row Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
* @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
*/
this.spliceRow = function (row, index, amount /* , elements... */) {
var _datamap2;
return (_datamap2 = datamap).spliceRow.apply(_datamap2, arguments);
};
/**
* Returns indexes of the currently selected cells as an array of arrays `[[startRow, startCol, endRow, endCol], ...]`.
*
* Start row and start col are the coordinates of the active cell (where the selection was started).
*
* The version 0.36.0 adds a non-consecutive selection feature. Since this version, the method returns an array of arrays.
* Additionally to collect the coordinates of the currently selected area (as it was previously done by the method)
* you need to use `getSelectedLast` method.
*
* @memberof Core#
* @function getSelected
* @returns {Array[]|undefined} An array of arrays of the selection's coordinates.
*/
this.getSelected = function () {
// https://github.com/handsontable/handsontable/issues/44 //cjl
if (selection.isSelected()) {
return (0, _array.arrayMap)(selection.getSelectedRange(), function (_ref11) {
var from = _ref11.from,
to = _ref11.to;
return [from.row, from.col, to.row, to.col];
});
}
};
/**
* Returns the last coordinates applied to the table as a an array `[startRow, startCol, endRow, endCol]`.
*
* @since 0.36.0
* @memberof Core#
* @function getSelectedLast
* @returns {Array|undefined} An array of the selection's coordinates.
*/
this.getSelectedLast = function () {
var selected = this.getSelected();
var result = void 0;
if (selected && selected.length > 0) {
result = selected[selected.length - 1];
}
return result;
};
/**
* Returns the current selection as an array of CellRange objects.
*
* The version 0.36.0 adds a non-consecutive selection feature. Since this version, the method returns an array of arrays.
* Additionally to collect the coordinates of the currently selected area (as it was previously done by the method)
* you need to use `getSelectedRangeLast` method.
*
* @memberof Core#
* @function getSelectedRange
* @since 0.11
* @returns {CellRange[]|undefined} Selected range object or undefined` if there is no selection.
*/
this.getSelectedRange = function () {
// https://github.com/handsontable/handsontable/issues/44 //cjl
if (selection.isSelected()) {
return Array.from(selection.getSelectedRange());
}
};
/**
* Returns the last coordinates applied to the table as a CellRange object.
*
* @memberof Core#
* @function getSelectedRangeLast
* @since 0.36.0
* @returns {CellRange|undefined} Selected range object or undefined` if there is no selection.
*/
this.getSelectedRangeLast = function () {
var selectedRange = this.getSelectedRange();
var result = void 0;
if (selectedRange && selectedRange.length > 0) {
result = selectedRange[selectedRange.length - 1];
}
return result;
};
/**
* Erases content from cells that have been selected in the table.
*
* @memberof Core#
* @function emptySelectedCells
* @since 0.36.0
*/
this.emptySelectedCells = function () {
var _this2 = this;
if (!selection.isSelected()) {
return;
}
var changes = [];
(0, _array.arrayEach)(selection.getSelectedRange(), function (cellRange) {
var topLeft = cellRange.getTopLeftCorner();
var bottomRight = cellRange.getBottomRightCorner();
(0, _number.rangeEach)(topLeft.row, bottomRight.row, function (row) {
(0, _number.rangeEach)(topLeft.col, bottomRight.col, function (column) {
if (!_this2.getCellMeta(row, column).readOnly) {
changes.push([row, column, '']);
}
});
});
});
if (changes.length > 0) {
this.setDataAtCell(changes);
}
};
/**
* Rerender the table.
*
* @memberof Core#
* @function render
*/
this.render = function () {
if (instance.view) {
instance.renderCall = true;
instance.forceFullRender = true; // used when data was changed
editorManager.lockEditor();
instance._refreshBorders(null);
editorManager.unlockEditor();
}
};
/**
* Reset all cells in the grid to contain data from the data array.
*
* @memberof Core#
* @function loadData
* @param {Array} data Array of arrays or array of objects containing data.
* @fires Hooks#afterLoadData
* @fires Hooks#afterChange
*/
this.loadData = function (data) {
if (Array.isArray(priv.settings.dataSchema)) {
instance.dataType = 'array';
} else if ((0, _function.isFunction)(priv.settings.dataSchema)) {
instance.dataType = 'function';
} else {
instance.dataType = 'object';
}
if (datamap) {
datamap.destroy();
}
datamap = new _dataMap2.default(instance, priv, GridSettings);
if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object' && data !== null) {
if (!(data.push && data.splice)) {
// check if data is array. Must use duck-type check so Backbone Collections also pass it
// when data is not an array, attempt to make a single-row array of it
data = [data];
}
} else if (data === null) {
data = [];
var row;
var r = 0;
var rlen = 0;
var dataSchema = datamap.getSchema();
for (r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
if ((instance.dataType === 'object' || instance.dataType === 'function') && priv.settings.dataSchema) {
row = (0, _object.deepClone)(dataSchema);
data.push(row);
} else if (instance.dataType === 'array') {
row = (0, _object.deepClone)(dataSchema[0]);
data.push(row);
} else {
row = [];
for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
row.push(null);
}
data.push(row);
}
}
} else {
throw new Error('loadData only accepts array of objects or array of arrays (' + (typeof data === 'undefined' ? 'undefined' : _typeof(data)) + ' given)');
}
priv.isPopulated = false;
GridSettings.prototype.data = data;
if (Array.isArray(data[0])) {
instance.dataType = 'array';
}
datamap.dataSource = data;
dataSource.data = data;
dataSource.dataType = instance.dataType;
dataSource.colToProp = datamap.colToProp.bind(datamap);
dataSource.propToCol = datamap.propToCol.bind(datamap);
clearCellSettingCache();
grid.adjustRowsAndCols();
instance.runHooks('afterLoadData', priv.firstRun);
if (priv.firstRun) {
priv.firstRun = [null, 'loadData'];
} else {
instance.runHooks('afterChange', null, 'loadData');
instance.render();
}
priv.isPopulated = true;
function clearCellSettingCache() {
priv.cellSettings.length = 0;
}
};
/**
* Returns the current data object (the same one that was passed by `data` configuration option or `loadData` method,
* unless the `modifyRow` hook was used to trim some of the rows. If that's the case - use the {@link Core#getSourceData} method.).
* Optionally you can provide cell range by defining `row`, `col`, `row2`, `col2` to get only a fragment of grid data.
*
* Note: getData functionality changed with the release of version 0.20. If you're looking for the previous functionality,
* you should use the {@link Core#getSourceData} method.
*
* @memberof Core#
* @function getData
* @param {Number} [r] From visual row index.
* @param {Number} [c] From visual column index.
* @param {Number} [r2] To visual row index.
* @param {Number} [c2] To visual column index.
* @returns {Array} Array with the data.
*/
this.getData = function (r, c, r2, c2) {
if ((0, _mixed.isUndefined)(r)) {
return datamap.getAll();
}
return datamap.getRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2), datamap.DESTINATION_RENDERER);
};
/**
* Returns a string value of the selected range. Each column is separated by tab, each row is separated by a new line character.
* {@link DataMap#getCopyableText}
*
* @memberof Core#
* @function getCopyableText
* @since 0.11
* @param {Number} startRow From visual row index.
* @param {Number} startCol From visual column index.
* @param {Number} endRow To visual row index.
* @param {Number} endCol To visual column index.
* @returns {String}
*/
this.getCopyableText = function (startRow, startCol, endRow, endCol) {
return datamap.getCopyableText(new _src.CellCoords(startRow, startCol), new _src.CellCoords(endRow, endCol));
};
/**
* Returns the data's copyable value at specified row and column index ({@link DataMap#getCopyable}).
*
* @memberof Core#
* @function getCopyableData
* @since 0.19.0
* @param {Number} row Visual row index.
* @param {Number} column Visual column index.
* @returns {String}
*/
this.getCopyableData = function (row, column) {
return datamap.getCopyable(row, datamap.colToProp(column));
};
/**
* Returns schema provided by constructor settings. If it doesn't exist then it returns the schema based on the data
* structure in the first row.
*
* @memberof Core#
* @function getSchema
* @since 0.13.2
* @returns {Object} Schema object.
*/
this.getSchema = function () {
return datamap.getSchema();
};
/**
* Use it if you need to change configuration after initialization. The `settings` parameter is an object containing the new
* settings, declared the same way as in the initial settings object.
* Note, that although the `updateSettings` method doesn't overwrite the previously declared settings, it might reset
* the settings made post-initialization. (for example - ignore changes made using the columnResize feature).
*
* @memberof Core#
* @function updateSettings
* @param {Object} settings New settings object.
* @param {Boolean} init Calls this method in the initialization mode. Internal use only.
* Used by API could be cause of the unexpected behaviour of the Handsontable.
* @example
* ```js
* hot.updateSettings({
* contextMenu: true,
* colHeaders: true,
* fixedRowsTop: 2
* });
* ```
* @fires Hooks#afterCellMetaReset
* @fires Hooks#afterUpdateSettings
*/
this.updateSettings = function (settings, init) {
var columnsAsFunc = false;
var i = void 0;
var j = void 0;
var clen = void 0;
if ((0, _mixed.isDefined)(settings.rows)) {
throw new Error('"rows" setting is no longer supported. do you mean startRows, minRows or maxRows?');
}
if ((0, _mixed.isDefined)(settings.cols)) {
throw new Error('"cols" setting is no longer supported. do you mean startCols, minCols or maxCols?');
}
for (i in settings) {
if (i === 'data') {
/* eslint-disable-next-line no-continue */
continue; // loadData will be triggered later
} else if (i === 'language') {
setLanguage(settings.language);
/* eslint-disable-next-line no-continue */
continue;
} else if (_pluginHooks2.default.getSingleton().getRegistered().indexOf(i) > -1) {
if ((0, _function.isFunction)(settings[i]) || Array.isArray(settings[i])) {
settings[i].initialHook = true;
instance.addHook(i, settings[i]);
}
} else if (!init && (0, _object.hasOwnProperty)(settings, i)) {
// Update settings
GridSettings.prototype[i] = settings[i];
}
}
// Load data or create data map
if (settings.data === void 0 && priv.settings.data === void 0) {
instance.loadData(null); // data source created just now
} else if (settings.data !== void 0) {
instance.loadData(settings.data); // data source given as option
} else if (settings.columns !== void 0) {
datamap.createMap();
}
clen = instance.countCols();
var columnSetting = settings.columns || GridSettings.prototype.columns;
// Init columns constructors configuration
if (columnSetting && (0, _function.isFunction)(columnSetting)) {
clen = instance.countSourceCols();
columnsAsFunc = true;
}
// Clear cellSettings cache
if (settings.cell !== void 0 || settings.cells !== void 0 || settings.columns !== void 0) {
priv.cellSettings.length = 0;
}
if (clen > 0) {
var proto = void 0;
var column = void 0;
for (i = 0, j = 0; i < clen; i++) {
if (columnsAsFunc && !columnSetting(i)) {
/* eslint-disable no-continue */
continue;
}
priv.columnSettings[j] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);
// shortcut for prototype
proto = priv.columnSettings[j].prototype;
// Use settings provided by user
if (columnSetting) {
if (columnsAsFunc) {
column = columnSetting(i);
} else {
column = columnSetting[j];
}
if (column) {
(0, _object.extend)(proto, column);
(0, _object.extend)(proto, expandType(column));
}
}
j++;
}
}
if ((0, _mixed.isDefined)(settings.cell)) {
for (var key in settings.cell) {
if ((0, _object.hasOwnProperty)(settings.cell, key)) {
var cell = settings.cell[key];
instance.setCellMetaObject(cell.row, cell.col, cell);
}
}
}
instance.runHooks('afterCellMetaReset');
if ((0, _mixed.isDefined)(settings.className)) {
if (GridSettings.prototype.className) {
(0, _element.removeClass)(instance.rootElement, GridSettings.prototype.className);
}
if (settings.className) {
(0, _element.addClass)(instance.rootElement, settings.className);
}
}
var currentHeight = instance.rootElement.style.height;
if (currentHeight !== '') {
currentHeight = parseInt(instance.rootElement.style.height, 10);
}
var height = settings.height;
if ((0, _function.isFunction)(height)) {
height = height();
}
if (init) {
var initialStyle = instance.rootElement.getAttribute('style');
if (initialStyle) {
instance.rootElement.setAttribute('data-initialstyle', instance.rootElement.getAttribute('style'));
}
}
if (height === null) {
var _initialStyle = instance.rootElement.getAttribute('data-initialstyle');
if (_initialStyle && (_initialStyle.indexOf('height') > -1 || _initialStyle.indexOf('overflow') > -1)) {
instance.rootElement.setAttribute('style', _initialStyle);
} else {
instance.rootElement.style.height = '';
instance.rootElement.style.overflow = '';
}
} else if (height !== void 0) {
instance.rootElement.style.height = height + 'px';
instance.rootElement.style.overflow = 'hidden';
}
if (typeof settings.width !== 'undefined') {
var width = settings.width;
if ((0, _function.isFunction)(width)) {
width = width();
}
instance.rootElement.style.width = width + 'px';
}
if (!init) {
datamap.clearLengthCache(); // force clear cache length on updateSettings() #3416
if (instance.view) {
instance.view.wt.wtViewport.resetHasOversizedColumnHeadersMarked();
}
instance.runHooks('afterUpdateSettings', settings);
}
grid.adjustRowsAndCols();
if (instance.view && !priv.firstRun) {
instance.forceFullRender = true; // used when data was changed
editorManager.lockEditor();
instance._refreshBorders(null);
editorManager.unlockEditor();
}
if (!init && instance.view && (currentHeight === '' || height === '' || height === void 0) && currentHeight !== height) {
instance.view.wt.wtOverlays.updateMainScrollableElements();
}
};
/**
* Get value from the selected cell.
*
* @memberof Core#
* @function getValue
* @since 0.11
* @returns {*} Value of selected cell.
*/
this.getValue = function () {
var sel = instance.getSelectedLast();
if (GridSettings.prototype.getValue) {
if ((0, _function.isFunction)(GridSettings.prototype.getValue)) {
return GridSettings.prototype.getValue.call(instance);
} else if (sel) {
return instance.getData()[sel[0][0]][GridSettings.prototype.getValue];
}
} else if (sel) {
return instance.getDataAtCell(sel[0], sel[1]);
}
};
function expandType(obj) {
if (!(0, _object.hasOwnProperty)(obj, 'type')) {
// ignore obj.prototype.type
return;
}
var type,
expandedType = {};
if (_typeof(obj.type) === 'object') {
type = obj.type;
} else if (typeof obj.type === 'string') {
type = (0, _cellTypes.getCellType)(obj.type);
}
for (var i in type) {
if ((0, _object.hasOwnProperty)(type, i) && !(0, _object.hasOwnProperty)(obj, i)) {
expandedType[i] = type[i];
}
}
return expandedType;
}
/**
* Returns the object settings.
*
* @memberof Core#
* @function getSettings
* @returns {Object} Object containing the current grid settings.
*/
this.getSettings = function () {
return priv.settings;
};
/**
* Clears the data from the grid (the table settings remain intact).
*
* @memberof Core#
* @function clear
* @since 0.11
*/
this.clear = function () {
selection.selectAll();
this.emptySelectedCells();
};
/**
* @memberof Core#
* @function alter
* @param {String} action See grid.alter for possible values: `"insert_row"`, `"insert_col"`, `"remove_row"`, `"remove_col"`
* @param {Number} index Visual index of the row/column before which the new row/column will be inserted/removed.
* @param {Number} [amount = 1] Amound of rows/columns to be inserted/removed.
* @param {String} [source] Source indicator.
* @param {Boolean} [keepEmptyRows] Flag for preventing deletion of empty rows.
* @description
*
* Allows altering the table structure by either inserting/removing rows or inserting/removing columns:
*
* Insert new row(s) above the row with a given `index`. If index is `null` or `undefined`, the new row will be
* added after the last row.
* ```js
* var hot = new Handsontable(document.getElementById('example'));
* hot.alter('insert_row', 10);
* ```
*
* Insert new column(s) before the column with a given `index`. If index is `null` or `undefined`, the new column
* will be added after the last column.
* ```js
* var hot = new Handsontable(document.getElementById('example'));
* hot.alter('insert_col', 10);
* ```
*
* Remove the row(s) at the given `index`.
* ```js
* var hot = new Handsontable(document.getElementById('example'));
* hot.alter('remove_row', 10);
* ```
*
* Remove the column(s) at the given `index`.
* ```js
* var hot = new Handsontable(document.getElementById('example'));
* hot.alter('remove_col', 10);
* ```
*/
this.alter = function (action, index, amount, source, keepEmptyRows) {
grid.alter(action, index, amount, source, keepEmptyRows);
};
/**
* Returns a TD element for the given `row` and `col` arguments, if it is rendered on screen.
* Returns `null` if the TD is not rendered on screen (probably because that part of the table is not visible).
*
* @memberof Core#
* @function getCell
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {Boolean} topmost If set to true, it returns the TD element from the topmost overlay. For example,
* if the wanted cell is in the range of fixed rows, it will return a TD element from the `top` overlay.
* @returns {Element} The cell's TD element.
*/
this.getCell = function (row, col, topmost) {
return instance.view.getCellAtCoords(new _src.CellCoords(row, col), topmost);
};
/**
* Returns the coordinates of the cell, provided as a HTML Element.
*
* @memberof Core#
* @function getCoords
* @param {Element} elem The HTML Element representing the cell.
* @returns {CellCoords} Visual coordinates object.
*/
this.getCoords = function (elem) {
return this.view.wt.wtTable.getCoords.call(this.view.wt.wtTable, elem);
};
/**
* Returns the property name that corresponds with the given column index. {@link DataMap#colToProp}
* If the data source is an array of arrays, it returns the columns index.
*
* @memberof Core#
* @function colToProp
* @param {Number} col Visual column index.
* @returns {String|Number} Column property or physical column index.
*/
this.colToProp = function (col) {
return datamap.colToProp(col);
};
/**
* Returns column index that corresponds with the given property. {@link DataMap#propToCol}
*
* @memberof Core#
* @function propToCol
* @param {String|Number} prop Property name or physical column index.
* @returns {Number} Visual column index.
*/
this.propToCol = function (prop) {
return datamap.propToCol(prop);
};
/**
* Translate physical row index into visual.
*
* @since 0.29.0
* @memberof Core#
* @function toVisualRow
* @param {Number} row Physical row index.
* @returns {Number} Returns visual row index.
*/
this.toVisualRow = function (row) {
return recordTranslator.toVisualRow(row);
};
/**
* Translate physical column index into visual.
*
* @since 0.29.0
* @memberof Core#
* @function toVisualColumn
* @param {Number} column Physical column index.
* @returns {Number} Returns visual column index.
*/
this.toVisualColumn = function (column) {
return recordTranslator.toVisualColumn(column);
};
/**
* Translate visual row index into physical.
* If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
* to retrieve valid physical row index you can use this method.
*
* @since 0.29.0
* @memberof Core#
* @function toPhysicalRow
* @param {Number} row Visual row index.
* @returns {Number} Returns physical row index.
*/
this.toPhysicalRow = function (row) {
return recordTranslator.toPhysicalRow(row);
};
/**
* Translate visual column index into physical.
* If displayed columns order is different than the order of columns stored in memory (i.e. manual column move is applied)
* to retrieve valid physical column index you can use this method.
*
* @since 0.29.0
* @memberof Core#
* @function toPhysicalColumn
* @param {Number} column Visual column index.
* @returns {Number} Returns physical column index.
*/
this.toPhysicalColumn = function (column) {
return recordTranslator.toPhysicalColumn(column);
};
/**
* @description
* Returns the cell value at `row`, `col`. `row` and `col` are the __visible__ indexes (note, that if columns were reordered or sorted,
* the currently visible order will be used).
*
* @memberof Core#
* @function getDataAtCell
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @returns {String|Boolean|null} Data at cell.
*/
this.getDataAtCell = function (row, col) {
return datamap.get(row, datamap.colToProp(col));
};
/**
* Return value at `row`, `prop`. (Uses {@link DataMap#get})
*
* @memberof Core#
* @function getDataAtRowProp
* @param {Number} row Visual row index.
* @param {String} prop Property name.
* @returns {*} Cell value.
*/
this.getDataAtRowProp = function (row, prop) {
return datamap.get(row, prop);
};
/**
* @description
* Returns array of column values from the data source. `col` is the __visible__ index of the column.
* Note, that if columns were reordered or sorted, the currently visible order will be used.
*
* @memberof Core#
* @function getDataAtCol
* @since 0.9-beta2
* @param {Number} col Visual column index.
* @returns {Array} Array of cell values.
*/
this.getDataAtCol = function (col) {
var out = [];
return out.concat.apply(out, _toConsumableArray(datamap.getRange(new _src.CellCoords(0, col), new _src.CellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER)));
};
/**
* Given the object property name (e.g. `'first.name'`), returns an array of column's values from the data source.
* You can also provide a column index as the first argument.
*
* @memberof Core#
* @function getDataAtProp
* @since 0.9-beta2
* @param {String|Number} prop Property name / physical column index.
* @returns {Array} Array of cell values.
*/
// TODO: Getting data from `datamap` should work on visual indexes.
this.getDataAtProp = function (prop) {
var out = [],
range;
range = datamap.getRange(new _src.CellCoords(0, datamap.propToCol(prop)), new _src.CellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER);
return out.concat.apply(out, _toConsumableArray(range));
};
/**
* Returns the source data object (the same that was passed by `data` configuration option or `loadData` method).
* Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
*
* @memberof Core#
* @function getSourceData
* @since 0.20.0
* @param {Number} [r] From physical row index.
* @param {Number} [c] From physical column index (or visual index, if data type is an array of objects).
* @param {Number} [r2] To physical row index.
* @param {Number} [c2] To physical column index (or visual index, if data type is an array of objects).
* @returns {Array} Array of grid data.
*/
this.getSourceData = function (r, c, r2, c2) {
var data = void 0;
if (r === void 0) {
data = dataSource.getData();
} else {
data = dataSource.getByRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2));
}
return data;
};
/**
* Returns the source data object as an arrays of arrays format even when source data was provided in another format.
* Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
*
* @memberof Core#
* @function getSourceDataArray
* @since 0.28.0
* @param {Number} [r] From physical row index.
* @param {Number} [c] From physical column index (or visual index, if data type is an array of objects).
* @param {Number} [r2] To physical row index.
* @param {Number} [c2] To physical column index (or visual index, if data type is an array of objects).
* @returns {Array} An array of arrays.
*/
this.getSourceDataArray = function (r, c, r2, c2) {
var data = void 0;
if (r === void 0) {
data = dataSource.getData(true);
} else {
data = dataSource.getByRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2), true);
}
return data;
};
/**
* Returns an array of column values from the data source. `col` is the index of the row in the data source.
*
* @memberof Core#
* @function getSourceDataAtCol
* @since 0.11.0-beta3
* @param {Number} column Visual column index.
* @returns {Array} Array of the column's cell values.
*/
// TODO: Getting data from `sourceData` should work always on physical indexes.
this.getSourceDataAtCol = function (column) {
return dataSource.getAtColumn(column);
};
/**
* Returns a single row of the data (array or object, depending on what you have). `row` is the index of the row in the data source.
*
* @memberof Core#
* @function getSourceDataAtRow
* @since 0.11.0-beta3
* @param {Number} row Physical row index.
* @returns {Array|Object} Single row of data.
*/
this.getSourceDataAtRow = function (row) {
return dataSource.getAtRow(row);
};
/**
* Returns a single value from the data source.
*
* @memberof Core#
* @function getSourceDataAtCell
* @param {Number} row Physical row index.
* @param {Number} column Visual column index.
* @returns {*} Cell data.
* @since 0.20.0
*/
// TODO: Getting data from `sourceData` should work always on physical indexes.
this.getSourceDataAtCell = function (row, column) {
return dataSource.getAtCell(row, column);
};
/**
* @description
* Returns a single row of the data. The `row` argument is the __visible__ index of the row.
*
* @memberof Core#
* @function getDataAtRow
* @param {Number} row Visual row index.
* @returns {Array} Array of row's cell data.
* @since 0.9-beta2
*/
this.getDataAtRow = function (row) {
var data = datamap.getRange(new _src.CellCoords(row, 0), new _src.CellCoords(row, this.countCols() - 1), datamap.DESTINATION_RENDERER);
return data[0] || [];
};
/**
* @description
* Returns a data type defined in the Handsontable settings under the `type` key ([Options#type](http://docs.handsontable.com/Options.html#type)).
* If there are cells with different types in the selected range, it returns `'mixed'`.
*
* @since 0.18.1
* @memberof Core#
* @function getDataType
* @param {Number} rowFrom From visual row index.
* @param {Number} columnFrom From visual column index.
* @param {Number} rowTo To visual row index.
* @param {Number} columnTo To visual column index.
* @returns {String} Cell type (e.q: `'mixed'`, `'text'`, `'numeric'`, `'autocomplete'`).
*/
this.getDataType = function (rowFrom, columnFrom, rowTo, columnTo) {
var _this3 = this;
var previousType = null;
var currentType = null;
if (rowFrom === void 0) {
rowFrom = 0;
rowTo = this.countRows();
columnFrom = 0;
columnTo = this.countCols();
}
if (rowTo === void 0) {
rowTo = rowFrom;
}
if (columnTo === void 0) {
columnTo = columnFrom;
}
var type = 'mixed';
(0, _number.rangeEach)(Math.min(rowFrom, rowTo), Math.max(rowFrom, rowTo), function (row) {
var isTypeEqual = true;
(0, _number.rangeEach)(Math.min(columnFrom, columnTo), Math.max(columnFrom, columnTo), function (column) {
var cellType = _this3.getCellMeta(row, column);
currentType = cellType.type;
if (previousType) {
isTypeEqual = previousType === currentType;
} else {
previousType = currentType;
}
return isTypeEqual;
});
type = isTypeEqual ? currentType : 'mixed';
return isTypeEqual;
});
return type;
};
/**
* Remove a property defined by the `key` argument from the cell meta object for the provided `row` and `col` coordinates.
*
* @memberof Core#
* @function removeCellMeta
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String} key Property name.
* @fires Hooks#beforeRemoveCellMeta
* @fires Hooks#afterRemoveCellMeta
*/
this.removeCellMeta = function (row, col, key) {
var _recordTranslator$toP = recordTranslator.toPhysical(row, col),
_recordTranslator$toP2 = _slicedToArray(_recordTranslator$toP, 2),
physicalRow = _recordTranslator$toP2[0],
physicalColumn = _recordTranslator$toP2[1];
var cachedValue = priv.cellSettings[physicalRow][physicalColumn][key];
var hookResult = instance.runHooks('beforeRemoveCellMeta', row, col, key, cachedValue);
if (hookResult !== false) {
delete priv.cellSettings[physicalRow][physicalColumn][key];
instance.runHooks('afterRemoveCellMeta', row, col, key, cachedValue);
}
cachedValue = null;
};
/**
* Remove one or more rows from the cell meta object.
*
* @since 0.30.0
* @param {Number} index An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
* @param {Number} deleteAmount The number of items to be removed. If set to 0, no items will be removed.
* @param {Array} items The new items to be added to the array.
*/
this.spliceCellsMeta = function (index, deleteAmount) {
var _priv$cellSettings;
for (var _len2 = arguments.length, items = Array(_len2 > 2 ? _len2 - 2 : 0), _key = 2; _key < _len2; _key++) {
items[_key - 2] = arguments[_key];
}
(_priv$cellSettings = priv.cellSettings).splice.apply(_priv$cellSettings, [index, deleteAmount].concat(items));
};
/**
* Set cell meta data object defined by `prop` to the corresponding params `row` and `col`.
*
* @memberof Core#
* @function setCellMetaObject
* @since 0.11
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {Object} prop Meta object.
*/
this.setCellMetaObject = function (row, col, prop) {
if ((typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object') {
for (var key in prop) {
if ((0, _object.hasOwnProperty)(prop, key)) {
var value = prop[key];
this.setCellMeta(row, col, key, value);
}
}
}
};
/**
* Sets a property defined by the `key` object to the meta object of a cell corresponding to params `row` and `col`.
*
* @memberof Core#
* @function setCellMeta
* @since 0.11
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @param {String} key Property name.
* @param {String} val Property value.
* @fires Hooks#afterSetCellMeta
*/
this.setCellMeta = function (row, col, key, val) {
var _recordTranslator$toP3 = recordTranslator.toPhysical(row, col),
_recordTranslator$toP4 = _slicedToArray(_recordTranslator$toP3, 2),
physicalRow = _recordTranslator$toP4[0],
physicalColumn = _recordTranslator$toP4[1];
if (!priv.columnSettings[physicalColumn]) {
priv.columnSettings[physicalColumn] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[physicalRow]) {
priv.cellSettings[physicalRow] = [];
}
if (!priv.cellSettings[physicalRow][physicalColumn]) {
priv.cellSettings[physicalRow][physicalColumn] = new priv.columnSettings[physicalColumn]();
}
priv.cellSettings[physicalRow][physicalColumn][key] = val;
instance.runHooks('afterSetCellMeta', row, col, key, val);
};
/**
* Get all the cells meta settings at least once generated in the table (in order of cell initialization).
*
* @since 0.19.0
* @returns {Array} Returns Array of ColumnSettings object.
*/
this.getCellsMeta = function () {
return (0, _array.arrayFlatten)(priv.cellSettings);
};
/**
* Returns the cell properties object for the given `row` and `col` coordinates.
*
* @memberof Core#
* @function getCellMeta
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @returns {Object} The cell properties object.
* @fires Hooks#beforeGetCellMeta
* @fires Hooks#afterGetCellMeta
*/
this.getCellMeta = function (row, col) {
var prop = datamap.colToProp(col);
var cellProperties = void 0;
var _recordTranslator$toP5 = recordTranslator.toPhysical(row, col),
_recordTranslator$toP6 = _slicedToArray(_recordTranslator$toP5, 2),
physicalRow = _recordTranslator$toP6[0],
physicalColumn = _recordTranslator$toP6[1];
// Workaround for #11. Connected also with #3849. It should be fixed within #4497.
if (physicalRow === null) {
physicalRow = row;
}
if (!priv.columnSettings[physicalColumn]) {
priv.columnSettings[physicalColumn] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[physicalRow]) {
priv.cellSettings[physicalRow] = [];
}
if (!priv.cellSettings[physicalRow][physicalColumn]) {
priv.cellSettings[physicalRow][physicalColumn] = new priv.columnSettings[physicalColumn]();
}
cellProperties = priv.cellSettings[physicalRow][physicalColumn]; // retrieve cellProperties from cache
cellProperties.row = physicalRow;
cellProperties.col = physicalColumn;
cellProperties.visualRow = row;
cellProperties.visualCol = col;
cellProperties.prop = prop;
cellProperties.instance = instance;
instance.runHooks('beforeGetCellMeta', row, col, cellProperties);
(0, _object.extend)(cellProperties, expandType(cellProperties)); // for `type` added in beforeGetCellMeta
if (cellProperties.cells) {
var settings = cellProperties.cells.call(cellProperties, physicalRow, physicalColumn, prop);
if (settings) {
(0, _object.extend)(cellProperties, settings);
(0, _object.extend)(cellProperties, expandType(settings)); // for `type` added in cells
}
}
instance.runHooks('afterGetCellMeta', row, col, cellProperties);
return cellProperties;
};
/**
* Returns a row off the cell meta array.
*
* @memberof Core#
* @function getCellMetaAtRow
* @since 0.30.0
* @param {Number} row Physical index of the row to return cell meta for.
* @returns {Array}
*/
this.getCellMetaAtRow = function (row) {
return priv.cellSettings[row];
};
/**
* Checks if the data format and config allows user to modify the column structure.
* @returns {boolean}
*/
this.isColumnModificationAllowed = function () {
return !(instance.dataType === 'object' || instance.getSettings().columns);
};
var rendererLookup = (0, _data.cellMethodLookupFactory)('renderer');
/**
* Returns the cell renderer function by given `row` and `col` arguments.
*
* @memberof Core#
* @function getCellRenderer
* @since 0.11
* @param {Number|Object} row Visual row index or cell meta object.
* @param {Number} [col] Visual column index.
* @returns {Function} The renderer function.
*/
this.getCellRenderer = function (row, col) {
return (0, _renderers.getRenderer)(rendererLookup.call(this, row, col));
};
/**
* Returns the cell editor by the provided `row` and `col` arguments.
*
* @memberof Core#
* @function getCellEditor
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @returns {Object} The Editor object.
*/
this.getCellEditor = (0, _data.cellMethodLookupFactory)('editor');
var validatorLookup = (0, _data.cellMethodLookupFactory)('validator');
/**
* Returns the cell validator by `row` and `col`, provided a validator is defined. If not - it doesn't return anything.
*
* @memberof Core#
* @function getCellValidator
* @param {Number} row Visual row index.
* @param {Number} col Visual column index.
* @returns {Function|RegExp|undefined} The validator function.
*/
this.getCellValidator = function (row, col) {
var validator = validatorLookup.call(this, row, col);
if (typeof validator === 'string') {
validator = (0, _validators.getValidator)(validator);
}
return validator;
};
/**
* Validates all cells using their validator functions and calls callback when finished.
*
* If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
*
* @memberof Core#
* @function validateCells
* @param {Function} [callback] The callback function.
*/
this.validateCells = function (callback) {
this._validateCells(callback);
};
/**
* Validates rows using their validator functions and calls callback when finished.
*
* If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
*
* @memberof Core#
* @function validateRows
* @param {Array} [rows] Array of validation target visual row indexes.
* @param {Function} [callback] The callback function.
*/
this.validateRows = function (rows, callback) {
if (!Array.isArray(rows)) {
throw new Error('validateRows parameter `rows` must be an array');
}
this._validateCells(callback, rows);
};
/**
* Validates columns using their validator functions and calls callback when finished.
*
* If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
*
* @memberof Core#
* @function validateColumns
* @param {Array} [columns] Array of validation target visual columns indexes.
* @param {Function} [callback] The callback function.
*/
this.validateColumns = function (columns, callback) {
if (!Array.isArray(columns)) {
throw new Error('validateColumns parameter `columns` must be an array');
}
this._validateCells(callback, undefined, columns);
};
/**
* Validates all cells using their validator functions and calls callback when finished.
*
* If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
*
* Private use intended.
*
* @private
* @memberof Core#
* @function _validateCells
* @param {Function} [callback] The callback function.
* @param {Array} [rows] Optional. Array of validation target visual row indexes.
* @param {Array} [columns] Optional. Array of validation target visual column indexes.
*/
this._validateCells = function (callback, rows, columns) {
var waitingForValidator = new ValidatorsQueue();
if (callback) {
waitingForValidator.onQueueEmpty = callback;
}
var i = instance.countRows() - 1;
while (i >= 0) {
if (rows !== undefined && rows.indexOf(i) === -1) {
i--;
continue;
}
var j = instance.countCols() - 1;
while (j >= 0) {
if (columns !== undefined && columns.indexOf(j) === -1) {
j--;
continue;
}
waitingForValidator.addValidatorToQueue();
instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function (result) {
if (typeof result !== 'boolean') {
throw new Error('Validation error: result is not boolean');
}
if (result === false) {
waitingForValidator.valid = false;
}
waitingForValidator.removeValidatorFormQueue();
}, 'validateCells');
j--;
}
i--;
}
waitingForValidator.checkIfQueueIsEmpty();
};
/**
* Returns an array of row headers' values (if they are enabled). If param `row` was given, it returns the header of the given row as a string.
*
* @memberof Core#
* @function getRowHeader
* @param {Number} [row] Visual row index.
* @fires Hooks#modifyRowHeader
* @returns {Array|String} Array of header values / single header value.
*/
this.getRowHeader = function (row) {
var rowHeader = priv.settings.rowHeaders;
if (row !== void 0) {
row = instance.runHooks('modifyRowHeader', row);
}
if (row === void 0) {
rowHeader = [];
(0, _number.rangeEach)(instance.countRows() - 1, function (i) {
rowHeader.push(instance.getRowHeader(i));
});
} else if (Array.isArray(rowHeader) && rowHeader[row] !== void 0) {
rowHeader = rowHeader[row];
} else if ((0, _function.isFunction)(rowHeader)) {
rowHeader = rowHeader(row);
} else if (rowHeader && typeof rowHeader !== 'string' && typeof rowHeader !== 'number') {
rowHeader = row + 1;
}
return rowHeader;
};
/**
* Returns information about if this table is configured to display row headers.
*
* @memberof Core#
* @function hasRowHeaders
* @returns {Boolean} `true` if the instance has the row headers enabled, `false` otherwise.
* @since 0.11
*/
this.hasRowHeaders = function () {
return !!priv.settings.rowHeaders;
};
/**
* Returns information about if this table is configured to display column headers.
*
* @memberof Core#
* @function hasColHeaders
* @since 0.11
* @returns {Boolean} `True` if the instance has the column headers enabled, `false` otherwise.
*/
this.hasColHeaders = function () {
if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) {
// Polymer has empty value = null
return !!priv.settings.colHeaders;
}
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
if (instance.getColHeader(i)) {
return true;
}
}
return false;
};
/**
* Returns an array of column headers (in string format, if they are enabled). If param `col` is given, it returns the header at the given column as a string.
*
* @memberof Core#
* @function getColHeader
* @param {Number} [col] Visual column index.
* @fires Hooks#modifyColHeader
* @returns {Array|String} The column header(s).
*/
this.getColHeader = function (col) {
var columnsAsFunc = priv.settings.columns && (0, _function.isFunction)(priv.settings.columns);
var result = priv.settings.colHeaders;
col = instance.runHooks('modifyColHeader', col);
if (col === void 0) {
var out = [];
var ilen = columnsAsFunc ? instance.countSourceCols() : instance.countCols();
for (var i = 0; i < ilen; i++) {
out.push(instance.getColHeader(i));
}
result = out;
} else {
var translateVisualIndexToColumns = function translateVisualIndexToColumns(col) {
var arr = [];
var columnsLen = instance.countSourceCols();
var index = 0;
for (; index < columnsLen; index++) {
if ((0, _function.isFunction)(instance.getSettings().columns) && instance.getSettings().columns(index)) {
arr.push(index);
}
}
return arr[col];
};
var baseCol = col;
col = instance.runHooks('modifyCol', col);
var prop = translateVisualIndexToColumns(col);
if (priv.settings.columns && (0, _function.isFunction)(priv.settings.columns) && priv.settings.columns(prop) && priv.settings.columns(prop).title) {
result = priv.settings.columns(prop).title;
} else if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
result = priv.settings.columns[col].title;
} else if (Array.isArray(priv.settings.colHeaders) && priv.settings.colHeaders[col] !== void 0) {
result = priv.settings.colHeaders[col];
} else if ((0, _function.isFunction)(priv.settings.colHeaders)) {
result = priv.settings.colHeaders(col);
} else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
result = (0, _data.spreadsheetColumnLabel)(baseCol); // see #1458
}
}
return result;
};
/**
* Return column width from settings (no guessing). Private use intended.
*
* @private
* @memberof Core#
* @function _getColWidthFromSettings
* @param {Number} col Visual col index.
* @returns {Number}
*/
this._getColWidthFromSettings = function (col) {
var cellProperties = instance.getCellMeta(0, col);
var width = cellProperties.width;
if (width === void 0 || width === priv.settings.width) {
width = cellProperties.colWidths;
}
if (width !== void 0 && width !== null) {
switch (typeof width === 'undefined' ? 'undefined' : _typeof(width)) {
case 'object':
// array
width = width[col];
break;
case 'function':
width = width(col);
break;
default:
break;
}
if (typeof width === 'string') {
width = parseInt(width, 10);
}
}
return width;
};
/**
* Returns the width of the requested column.
*
* @memberof Core#
* @function getColWidth
* @since 0.11
* @param {Number} col Visual column index.
* @returns {Number} Column width.
* @fires Hooks#modifyColWidth
*/
this.getColWidth = function (col) {
var width = instance._getColWidthFromSettings(col);
width = instance.runHooks('modifyColWidth', width, col);
if (width === void 0) {
width = _src.ViewportColumnsCalculator.DEFAULT_WIDTH;
}
return width;
};
/**
* Return row height from settings (no guessing). Private use intended.
*
* @private
* @memberof Core#
* @function _getRowHeightFromSettings
* @param {Number} row Visual row index.
* @returns {Number}
*/
this._getRowHeightFromSettings = function (row) {
// let cellProperties = instance.getCellMeta(row, 0);
// let height = cellProperties.height;
//
// if (height === void 0 || height === priv.settings.height) {
// height = cellProperties.rowHeights;
// }
var height = priv.settings.rowHeights;
if (height !== void 0 && height !== null) {
switch (typeof height === 'undefined' ? 'undefined' : _typeof(height)) {
case 'object':
// array
height = height[row];
break;
case 'function':
height = height(row);
break;
default:
break;
}
if (typeof height === 'string') {
height = parseInt(height, 10);
}
}
return height;
};
/**
* Returns the row height.
*
* @memberof Core#
* @function getRowHeight
* @since 0.11
* @param {Number} row Visual row index.
* @returns {Number} The given row's height.
* @fires Hooks#modifyRowHeight
*/
this.getRowHeight = function (row) {
var height = instance._getRowHeightFromSettings(row);
height = instance.runHooks('modifyRowHeight', height, row);
return height;
};
/**
* Returns the total number of rows in the data source.
*
* @memberof Core#
* @function countSourceRows
* @since 0.20.0
* @returns {Number} Total number in rows in data source.
*/
this.countSourceRows = function () {
var sourceLength = instance.runHooks('modifySourceLength');
return sourceLength || (instance.getSourceData() ? instance.getSourceData().length : 0);
};
/**
* Returns the total number of columns in the data source.
*
* @memberof Core#
* @function countSourceCols
* @since 0.26.1
* @returns {Number} Total number in columns in data source.
*/
this.countSourceCols = function () {
var len = 0;
var obj = instance.getSourceData() && instance.getSourceData()[0] ? instance.getSourceData()[0] : [];
if ((0, _object.isObject)(obj)) {
len = (0, _object.deepObjectSize)(obj);
} else {
len = obj.length || 0;
}
return len;
};
/**
* Returns the total number of rows in the grid.
*
* @memberof Core#
* @function countRows
* @returns {Number} Total number in rows the grid.
*/
this.countRows = function () {
return datamap.getLength();
};
/**
* Returns the total number of columns in the grid.
*
* @memberof Core#
* @function countCols
* @returns {Number} Total number of columns.
*/
this.countCols = function () {
var maxCols = this.getSettings().maxCols;
var dataHasLength = false;
var dataLen = 0;
if (instance.dataType === 'array') {
dataHasLength = priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length;
}
if (dataHasLength) {
dataLen = priv.settings.data[0].length;
}
if (priv.settings.columns) {
var columnsIsFunction = (0, _function.isFunction)(priv.settings.columns);
if (columnsIsFunction) {
if (instance.dataType === 'array') {
var columnLen = 0;
for (var i = 0; i < dataLen; i++) {
if (priv.settings.columns(i)) {
columnLen++;
}
}
dataLen = columnLen;
} else if (instance.dataType === 'object' || instance.dataType === 'function') {
dataLen = datamap.colToPropCache.length;
}
} else {
dataLen = priv.settings.columns.length;
}
} else if (instance.dataType === 'object' || instance.dataType === 'function') {
dataLen = datamap.colToPropCache.length;
}
return Math.min(maxCols, dataLen);
};
/**
* Returns an visual index of the first rendered row.
*
* @memberof Core#
* @function rowOffset
* @returns {Number} Visual index of first rendered row.
*/
this.rowOffset = function () {
return instance.view.wt.wtTable.getFirstRenderedRow();
};
/**
* Returns the visual index of the first rendered column.
*
* @memberof Core#
* @function colOffset
* @returns {Number} Visual index of the first visible column.
*/
this.colOffset = function () {
return instance.view.wt.wtTable.getFirstRenderedColumn();
};
/**
* Returns the number of rendered rows (including rows partially or fully rendered outside viewport).
*
* @memberof Core#
* @function countRenderedRows
* @returns {Number} Returns -1 if table is not visible.
*/
this.countRenderedRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedRowsCount() : -1;
};
/**
* Returns the number of visible rows (rendered rows that fully fit inside viewport).
*
* @memberof Core#
* @function countVisibleRows
* @returns {Number} Number of visible rows or -1.
*/
this.countVisibleRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleRowsCount() : -1;
};
/**
* Returns the number of rendered columns (including columns partially or fully rendered outside viewport).
*
* @memberof Core#
* @function countRenderedCols
* @returns {Number} Returns -1 if table is not visible.
*/
this.countRenderedCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedColumnsCount() : -1;
};
/**
* Returns the number of visible columns. Returns -1 if table is not visible
*
* @memberof Core#
* @function countVisibleCols
* @return {Number} Number of visible columns or -1.
*/
this.countVisibleCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleColumnsCount() : -1;
};
/**
* Returns the number of empty rows. If the optional ending parameter is `true`, returns the
* number of empty rows at the bottom of the table.
*
* @memberof Core#
* @function countEmptyRows
* @param {Boolean} [ending] If `true`, will only count empty rows at the end of the data source.
* @returns {Number} Count empty rows
* @fires Hooks#modifyRow
*/
this.countEmptyRows = function (ending) {
var i = instance.countRows() - 1,
empty = 0,
row;
while (i >= 0) {
row = instance.runHooks('modifyRow', i);
if (instance.isEmptyRow(row)) {
empty++;
} else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Returns the number of empty columns. If the optional ending parameter is `true`, returns the number of empty
* columns at right hand edge of the table.
*
* @memberof Core#
* @function countEmptyCols
* @param {Boolean} [ending] If `true`, will only count empty columns at the end of the data source row.
* @returns {Number} Count empty cols
*/
this.countEmptyCols = function (ending) {
if (instance.countRows() < 1) {
return 0;
}
var i = instance.countCols() - 1,
empty = 0;
while (i >= 0) {
if (instance.isEmptyCol(i)) {
empty++;
} else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Check if all cells in the row declared by the `row` argument are empty.
*
* @memberof Core#
* @function isEmptyRow
* @param {Number} row Row index.
* @returns {Boolean} `true` if the row at the given `row` is empty, `false` otherwise.
*/
this.isEmptyRow = function (row) {
return priv.settings.isEmptyRow.call(instance, row);
};
/**
* Check if all cells in the the column declared by the `col` argument are empty.
*
* @memberof Core#
* @function isEmptyCol
* @param {Number} col Column index.
* @returns {Boolean} `true` if the column at the given `col` is empty, `false` otherwise.
*/
this.isEmptyCol = function (col) {
return priv.settings.isEmptyCol.call(instance, col);
};
/**
* Select cell specified by `row` and `col` values or a range of cells finishing at `endRow`, `endCol`. If the table
* was configured to support data column properties that properties can be used to making a selection.
*
* By default, viewport will be scrolled to the selection. After the `selectCell` method had finished, the instance
* will be listening to keyboard input on the document.
*
* @example
* ```js
* // select a single cell
* hot.selectCell(2, 4);
* // select a single cell using column property
* hot.selectCell(2, 'address');
* // select a range of cells
* hot.selectCell(2, 4, 3, 5);
* // select a range of cells using column properties
* hot.selectCell(2, 'address', 3, 'phone_number');
* // select a range of cells without scrolling to them
* hot.selectCell(2, 'address', 3, 'phone_number', false);
* ```
*
* @memberof Core#
* @function selectCell
* @param {Number} row Visual row index.
* @param {Number|String} column Visual column index or column property.
* @param {Number} [endRow] Visual end row index (if selecting a range).
* @param {Number|String} [endColumn] Visual end column index or column property (if selecting a range).
* @param {Boolean} [scrollToCell=true] If `true`, the viewport will be scrolled to the selection.
* @param {Boolean} [changeListener=true] If `false`, Handsontable will not change keyboard events listener to himself.
* @returns {Boolean} `true` if selection was successful, `false` otherwise.
*/
this.selectCell = function (row, column, endRow, endColumn) {
var scrollToCell = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var changeListener = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
if ((0, _mixed.isUndefined)(row) || (0, _mixed.isUndefined)(column)) {
return false;
}
return this.selectCells([[row, column, endRow, endColumn]], scrollToCell, changeListener);
};
/**
* Make multiple, non-contiguous selection specified by `row` and `column` values or a range of cells
* finishing at `endRow`, `endColumn`. The method supports two input formats which are the same as that
* produces by `getSelected` and `getSelectedRange` methods.
*
* By default, viewport will be scrolled to selection. After the `selectCells` method had finished, the instance
* will be listening to keyboard input on the document.
*
* @example
* ```js
* // using an array of arrays
* hot.selectCells([[1, 1, 2, 2], [3, 3], [6, 2, 0, 2]]);
* // using an array of arrays with defined columns as props
* hot.selectCells([[1, 'id', 2, 'first_name'], [3, 'full_name'], [6, 'last_name', 0, 'first_name']]);
* // or using an array of CellRange objects (produced by `.getSelectedRange()` method)
* const selected = hot.getSelectedRange();
*
* selected[0].from.row = 0;
* selected[0].from.col = 0;
*
* hot.selectCells(selected);
* ```
*
* @memberof Core#
* @since 0.38.0
* @function selectCells
* @param {Array[]|CellRange[]} coords Visual coords passed as an array of array (`[[rowStart, columnStart, rowEnd, columnEnd], ...]`)
* the same format as `getSelected` method returns or as an CellRange objects
* which is the same format what `getSelectedRange` method returns.
* @param {Boolean} [scrollToCell=true] If `true`, the viewport will be scrolled to the selection.
* @param {Boolean} [changeListener=true] If `false`, Handsontable will not change keyboard events listener to himself.
* @returns {Boolean} `true` if selection was successful, `false` otherwise.
*/
this.selectCells = function () {
var coords = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [[]];
var scrollToCell = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var changeListener = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (scrollToCell === false) {
preventScrollingToCell = true;
}
var wasSelected = selection.selectCells(coords);
if (wasSelected && changeListener) {
instance.listen();
}
preventScrollingToCell = false;
return wasSelected;
};
/**
* Select the cell specified by the `row` and `prop` arguments, or a range finishing at `endRow`, `endProp`.
* By default, viewport will be scrolled to selection.
*
* @deprecated
* @memberof Core#
* @function selectCellByProp
* @param {Number} row Visual row index.
* @param {String} prop Property name.
* @param {Number} [endRow] visual end row index (if selecting a range).
* @param {String} [endProp] End property name (if selecting a range).
* @param {Boolean} [scrollToCell=true] If `true`, viewport will be scrolled to the selection.
* @param {Boolean} [changeListener=true] If `false`, Handsontable will not change keyboard events listener to himself.
* @returns {Boolean} `true` if selection was successful, `false` otherwise.
*/
this.selectCellByProp = function (row, prop, endRow, endProp) {
var scrollToCell = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var changeListener = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
console.warn((0, _templateLiteralTag.toSingleLine)(_templateObject));
return this.selectCells([[row, prop, endRow, endProp]], scrollToCell, changeListener);
};
/**
* Select column specified by `startColumn` visual index, column property or a range of columns finishing at `endColumn`.
*
* @example
* ```js
* // select column using visual index
* hot.selectColumns(1);
* // select column using column property
* hot.selectColumns('id');
* // select range of columns using visual indexes
* hot.selectColumns(1, 4);
* // select range of columns using column properties
* hot.selectColumns('id', 'last_name');
* ```
*
* @memberof Core#
* @since 0.38.0
* @function selectColumns
* @param {Number} startColumn The visual column index from which the selection starts.
* @param {Number} [endColumn=startColumn] The visual column index to which the selection finishes. If `endColumn`
* is not defined the column defined by `startColumn` will be selected.
* @returns {Boolean} `true` if selection was successful, `false` otherwise.
*/
this.selectColumns = function (startColumn) {
var endColumn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : startColumn;
return selection.selectColumns(startColumn, endColumn);
};
/**
* Select row specified by `startRow` visual index or a range of rows finishing at `endRow`.
*
* @example
* ```js
* select row using visual index
* hot.selectRows(1);
* select range of rows using visual indexes
* hot.selectRows(1, 4);
* ```
*
* @memberof Core#
* @since 0.38.0
* @function selectRows
* @param {Number} startRow The visual row index from which the selection starts.
* @param {Number} [endRow=startRow] The visual row index to which the selection finishes. If `endRow`
* is not defined the row defined by `startRow` will be selected.
* @returns {Boolean} `true` if selection was successful, `false` otherwise.
*/
this.selectRows = function (startRow) {
var endRow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : startRow;
return selection.selectRows(startRow, endRow);
};
/**
* Deselects the current cell selection on grid.
*
* @memberof Core#
* @function deselectCell
*/
this.deselectCell = function () {
selection.deselect();
};
/**
* Scroll viewport to coords specified by the `row` and `column` arguments.
*
* @since 0.24.3
* @memberof Core#
* @function scrollViewportTo
* @param {Number} [row] Visual row index.
* @param {Number} [column] Visual column index.
* @param {Boolean} [snapToBottom = false] If `true`, viewport is scrolled to show the cell on the bottom of the table.
* @param {Boolean} [snapToRight = false] If `true`, viewport is scrolled to show the cell on the right side of the table.
* @returns {Boolean} `true` if scroll was successful, `false` otherwise.
*/
this.scrollViewportTo = function (row, column) {
var snapToBottom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var snapToRight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (row !== void 0 && (row < 0 || row >= instance.countRows())) {
return false;
}
if (column !== void 0 && (column < 0 || column >= instance.countCols())) {
return false;
}
var result = false;
if (row !== void 0 && column !== void 0) {
instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);
instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);
result = true;
}
if (typeof row === 'number' && typeof column !== 'number') {
instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);
result = true;
}
if (typeof column === 'number' && typeof row !== 'number') {
instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);
result = true;
}
return result;
};
/**
* Removes grid from the DOM.
*
* @memberof Core#
* @function destroy
* @fires Hooks#afterDestroy
*/
this.destroy = function () {
instance._clearTimeouts();
if (instance.view) {
// in case HT is destroyed before initialization has finished
instance.view.destroy();
}
if (dataSource) {
dataSource.destroy();
}
dataSource = null;
(0, _keyStateObserver.stopObserving)();
if ('pro' !== '\x63\x65' && (0, _rootInstance.isRootInstance)(instance)) {
var licenseInfo = document.querySelector('#hot-display-license-info');
if (licenseInfo) {
licenseInfo.parentNode.removeChild(licenseInfo);
}
}
(0, _element.empty)(instance.rootElement);
eventManager.destroy();
if (editorManager) {
editorManager.destroy();
}
instance.runHooks('afterDestroy');
_pluginHooks2.default.getSingleton().destroy(instance);
for (var i in instance) {
if ((0, _object.hasOwnProperty)(instance, i)) {
// replace instance methods with post mortem
if ((0, _function.isFunction)(instance[i])) {
instance[i] = postMortem;
} else if (i !== 'guid') {
// replace instance properties with null (restores memory)
// it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
instance[i] = null;
}
}
}
// replace private properties with null (restores memory)
// it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
if (datamap) {
datamap.destroy();
}
datamap = null;
priv = null;
grid = null;
selection = null;
editorManager = null;
instance = null;
GridSettings = null;
};
/**
* Replacement for all methods after Handsotnable was destroyed.
*
* @private
*/
function postMortem() {
throw new Error('This method cannot be called because this Handsontable instance has been destroyed');
}
/**
* Returns the active editor object.
*
* @memberof Core#
* @function getActiveEditor
* @returns {Object} The active editor object.
*/
this.getActiveEditor = function () {
return editorManager.getActiveEditor();
};
/**
* Returns plugin instance using the plugin name provided.
*
* @memberof Core#
* @function getPlugin
* @param {String} pluginName The plugin name.
* @returns {*} The plugin instance.
* @since 0.15.0
*/
this.getPlugin = function (pluginName) {
return (0, _plugins.getPlugin)(this, pluginName);
};
/**
* Returns the Handsontable instance.
*
* @memberof Core#
* @function getInstance
* @returns {Handsontable} The Handsontable instance.
*/
this.getInstance = function () {
return instance;
};
/**
* Adds listener to the specified hook name (only for this Handsontable instance).
*
* @memberof Core#
* @function addHook
* @see Hooks#add
* @param {String} key Hook name.
* @param {Function|Array} callback Function or array of Functions.
*
* @example
* ```js
* hot.addHook('beforeInit', myCallback);
* ```
*/
this.addHook = function (key, callback) {
_pluginHooks2.default.getSingleton().add(key, callback, instance);
};
/**
* Check if for a specified hook name there are added listeners (only for this Handsontable instance).
*
* @memberof Core#
* @function hasHook
* @see Hooks#has
* @param {String} key Hook name
* @return {Boolean}
*
* @example
* ```js
* var hasBeforeInitListeners = hot.hasHook('beforeInit');
* ```
*/
this.hasHook = function (key) {
return _pluginHooks2.default.getSingleton().has(key, instance);
};
/**
* Adds listener to specified hook name (only for this Handsontable instance).
* After the listener is triggered, it will be automatically removed.
*
* @memberof Core#
* @function addHookOnce
* @see Hooks#once
* @param {String} key Hook name.
* @param {Function|Array} callback Function or array of Functions.
*
* @example
* ```js
* hot.addHookOnce('beforeInit', myCallback);
* ```
*/
this.addHookOnce = function (key, callback) {
_pluginHooks2.default.getSingleton().once(key, callback, instance);
};
/**
* Removes the hook listener previously registered with {@link Core#addHook}.
*
* @memberof Core#
* @function removeHook
* @see Hooks#remove
* @param {String} key Hook name.
* @param {Function} callback Function which have been registered via {@link Core#addHook}.
*
* @example
* ```js
* hot.removeHook('beforeInit', myCallback);
* ```
*/
this.removeHook = function (key, callback) {
_pluginHooks2.default.getSingleton().remove(key, callback, instance);
};
/**
* Run the callbacks for the hook provided in the `key` argument using the parameters given in the other arguments.
*
* @memberof Core#
* @function runHooks
* @see Hooks#run
* @param {String} key Hook name.
* @param {*} [p1] Argument passed to the callback.
* @param {*} [p2] Argument passed to the callback.
* @param {*} [p3] Argument passed to the callback.
* @param {*} [p4] Argument passed to the callback.
* @param {*} [p5] Argument passed to the callback.
* @param {*} [p6] Argument passed to the callback.
* @returns {*}
*
* @example
* ```js
* hot.runHooks('beforeInit');
* ```
*/
this.runHooks = function (key, p1, p2, p3, p4, p5, p6) {
return _pluginHooks2.default.getSingleton().run(instance, key, p1, p2, p3, p4, p5, p6);
};
/**
* Get phrase for specified dictionary key.
*
* @memberof Core#
* @function getTranslatedPhrase
* @since 0.35.0
* @param {String} dictionaryKey Constant which is dictionary key.
* @param {*} extraArguments Arguments which will be handled by formatters.
*
* @returns {String}
*/
this.getTranslatedPhrase = function (dictionaryKey, extraArguments) {
return (0, _i18n.getTranslatedPhrase)(priv.settings.language, dictionaryKey, extraArguments);
};
this.timeouts = [];
/**
* Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called.
*
* @param {*} handle
* @private
*/
this._registerTimeout = function (handle) {
this.timeouts.push(handle);
};
/**
* Clears all known timeouts.
*
* @private
*/
this._clearTimeouts = function () {
for (var i = 0, ilen = this.timeouts.length; i < ilen; i++) {
clearTimeout(this.timeouts[i]);
}
};
/**
* Refresh selection borders. This is temporary method relic after selection rewrite.
*
* @private
* @param {Boolean} revertOriginal
*/
this._refreshBorders = function (revertOriginal) {
editorManager.destroyEditor(revertOriginal);
instance.view.render();
if (selection.isSelected()) {
editorManager.prepareEditor();
}
};
_pluginHooks2.default.getSingleton().run(instance, 'construct');
};
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.columnFactory = columnFactory;
var _object = __webpack_require__(1);
/* eslint-disable import/prefer-default-export */
/**
* Factory for columns constructors.
*
* @param {Object} GridSettings
* @param {Array} conflictList
* @return {Object} ColumnSettings
*/
function columnFactory(GridSettings, conflictList) {
function ColumnSettings() {};
(0, _object.inherit)(ColumnSettings, GridSettings);
// Clear conflict settings
for (var i = 0, len = conflictList.length; i < len; i++) {
ColumnSettings.prototype[conflictList[i]] = void 0;
}
return ColumnSettings;
}
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SELECTION_TYPES = exports.SELECTION_TYPE_OBJECT = exports.SELECTION_TYPE_ARRAY = exports.SELECTION_TYPE_EMPTY = exports.SELECTION_TYPE_UNRECOGNIZED = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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; };
exports.detectSelectionType = detectSelectionType;
exports.normalizeSelectionFactory = normalizeSelectionFactory;
exports.transformSelectionToColumnDistance = transformSelectionToColumnDistance;
exports.transformSelectionToRowDistance = transformSelectionToRowDistance;
exports.isValidCoord = isValidCoord;
var _src = __webpack_require__(8);
var _array = __webpack_require__(0);
var _mixed = __webpack_require__(13);
var SELECTION_TYPE_UNRECOGNIZED = exports.SELECTION_TYPE_UNRECOGNIZED = 0;
var SELECTION_TYPE_EMPTY = exports.SELECTION_TYPE_EMPTY = 1;
var SELECTION_TYPE_ARRAY = exports.SELECTION_TYPE_ARRAY = 2;
var SELECTION_TYPE_OBJECT = exports.SELECTION_TYPE_OBJECT = 3;
var SELECTION_TYPES = exports.SELECTION_TYPES = [SELECTION_TYPE_OBJECT, SELECTION_TYPE_ARRAY];
var ARRAY_TYPE_PATTERN = [['number'], ['number', 'string'], ['number', 'undefined'], ['number', 'string', 'undefined']];
var rootCall = Symbol('root');
var childCall = Symbol('child');
/**
* Detect selection schema structure.
*
* @param {*} selectionRanges The selected range or and array of selected ranges. This type of data is produced by
* `hot.getSelected()`, `hot.getSelectedLast()`, `hot.getSelectedRange()`
* and `hot.getSelectedRangeLast()` methods.
* @returns {Number} Returns a number that specifies the type of detected selection schema. If selection schema type
* is unrecognized than it returns `0`.
*/
function detectSelectionType(selectionRanges) {
var _callSymbol = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : rootCall;
if (_callSymbol !== rootCall && _callSymbol !== childCall) {
throw new Error('The second argument is used internally only and cannot be overwritten.');
}
var isArray = Array.isArray(selectionRanges);
var isRootCall = _callSymbol === rootCall;
var result = SELECTION_TYPE_UNRECOGNIZED;
if (isArray) {
var firstItem = selectionRanges[0];
if (selectionRanges.length === 0) {
result = SELECTION_TYPE_EMPTY;
} else if (isRootCall && firstItem instanceof _src.CellRange) {
result = SELECTION_TYPE_OBJECT;
} else if (isRootCall && Array.isArray(firstItem)) {
result = detectSelectionType(firstItem, childCall);
} else if (selectionRanges.length >= 2 && selectionRanges.length <= 4) {
var isArrayType = !selectionRanges.some(function (value, index) {
return !ARRAY_TYPE_PATTERN[index].includes(typeof value === 'undefined' ? 'undefined' : _typeof(value));
});
if (isArrayType) {
result = SELECTION_TYPE_ARRAY;
}
}
}
return result;
}
/**
* Factory function designed for normalization data schema from different data structures of the selection ranges.
*
* @param {String} type Selection type which will be processed.
* @param {Object} [options]
* @param {Boolean} [options.keepDirection=false] If `true`, the coordinates which contain the direction of the
* selected cells won't be changed. Otherwise, the selection will be
* normalized to values starting from top-left to bottom-right.
* @param {Function} [options.propToCol] Pass the converting function (usually `datamap.propToCol`) if the column
* defined as props should be normalized to the numeric values.
* @returns {Number[]} Returns normalized data about selected range as an array (`[rowStart, columnStart, rowEnd, columnEnd]`).
*/
function normalizeSelectionFactory(type) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$keepDirection = _ref.keepDirection,
keepDirection = _ref$keepDirection === undefined ? false : _ref$keepDirection,
propToCol = _ref.propToCol;
if (!SELECTION_TYPES.includes(type)) {
throw new Error('Unsupported selection ranges schema type was provided.');
}
return function (selection) {
var isObjectType = type === SELECTION_TYPE_OBJECT;
var rowStart = isObjectType ? selection.from.row : selection[0];
var columnStart = isObjectType ? selection.from.col : selection[1];
var rowEnd = isObjectType ? selection.to.row : selection[2];
var columnEnd = isObjectType ? selection.to.col : selection[3];
if (typeof propToCol === 'function') {
if (typeof columnStart === 'string') {
columnStart = propToCol(columnStart);
}
if (typeof columnEnd === 'string') {
columnEnd = propToCol(columnEnd);
}
}
if ((0, _mixed.isUndefined)(rowEnd)) {
rowEnd = rowStart;
}
if ((0, _mixed.isUndefined)(columnEnd)) {
columnEnd = columnStart;
}
if (!keepDirection) {
var origRowStart = rowStart;
var origColumnStart = columnStart;
var origRowEnd = rowEnd;
var origColumnEnd = columnEnd;
rowStart = Math.min(origRowStart, origRowEnd);
columnStart = Math.min(origColumnStart, origColumnEnd);
rowEnd = Math.max(origRowStart, origRowEnd);
columnEnd = Math.max(origColumnStart, origColumnEnd);
}
return [rowStart, columnStart, rowEnd, columnEnd];
};
}
/**
* Function transform selection ranges (produced by `hot.getSelected()` and `hot.getSelectedRange()`) to normalized
* data structure. It merges repeated ranges into consecutive coordinates. The returned structure
* contains an array of arrays. The single item contains at index 0 visual column index from the selection was
* started and at index 1 distance as a count of selected columns.
*
* @param {Array[]|CellRange[]} selectionRanges Selection ranges produced by Handsontable.
* @return {Array[]} Returns an array of arrays with ranges defines in that schema:
* `[[visualColumnStart, distance], [visualColumnStart, distance], ...]`.
* The column distances are always created starting from the left (zero index) to the
* right (the latest column index).
*/
function transformSelectionToColumnDistance(selectionRanges) {
var selectionType = detectSelectionType(selectionRanges);
if (selectionType === SELECTION_TYPE_UNRECOGNIZED || selectionType === SELECTION_TYPE_EMPTY) {
return [];
}
var selectionSchemaNormalizer = normalizeSelectionFactory(selectionType);
var unorderedIndexes = new Set();
// Iterate through all ranges and collect all column indexes which are not saved yet.
(0, _array.arrayEach)(selectionRanges, function (selection) {
var _selectionSchemaNorma = selectionSchemaNormalizer(selection),
_selectionSchemaNorma2 = _slicedToArray(_selectionSchemaNorma, 4),
columnStart = _selectionSchemaNorma2[1],
columnEnd = _selectionSchemaNorma2[3];
var amount = columnEnd - columnStart + 1;
(0, _array.arrayEach)(Array.from(new Array(amount), function (_, i) {
return columnStart + i;
}), function (index) {
if (!unorderedIndexes.has(index)) {
unorderedIndexes.add(index);
}
});
});
// Sort indexes in ascending order to easily detecting non-consecutive columns.
var orderedIndexes = Array.from(unorderedIndexes).sort(function (a, b) {
return a - b;
});
var normalizedColumnRanges = (0, _array.arrayReduce)(orderedIndexes, function (acc, visualColumnIndex, index, array) {
if (index !== 0 && visualColumnIndex === array[index - 1] + 1) {
acc[acc.length - 1][1]++;
} else {
acc.push([visualColumnIndex, 1]);
}
return acc;
}, []);
return normalizedColumnRanges;
}
/**
* Function transform selection ranges (produced by `hot.getSelected()` and `hot.getSelectedRange()`) to normalized
* data structure. It merges repeated ranges into consecutive coordinates. The returned structure
* contains an array of arrays. The single item contains at index 0 visual column index from the selection was
* started and at index 1 distance as a count of selected columns.
*
* @param {Array[]|CellRange[]} selectionRanges Selection ranges produced by Handsontable.
* @return {Array[]} Returns an array of arrays with ranges defines in that schema:
* `[[visualColumnStart, distance], [visualColumnStart, distance], ...]`.
* The column distances are always created starting from the left (zero index) to the
* right (the latest column index).
*/
function transformSelectionToRowDistance(selectionRanges) {
var selectionType = detectSelectionType(selectionRanges);
if (selectionType === SELECTION_TYPE_UNRECOGNIZED || selectionType === SELECTION_TYPE_EMPTY) {
return [];
}
var selectionSchemaNormalizer = normalizeSelectionFactory(selectionType);
var unorderedIndexes = new Set();
// Iterate through all ranges and collect all column indexes which are not saved yet.
(0, _array.arrayEach)(selectionRanges, function (selection) {
var _selectionSchemaNorma3 = selectionSchemaNormalizer(selection),
_selectionSchemaNorma4 = _slicedToArray(_selectionSchemaNorma3, 3),
rowStart = _selectionSchemaNorma4[0],
rowEnd = _selectionSchemaNorma4[2];
var amount = rowEnd - rowStart + 1;
(0, _array.arrayEach)(Array.from(new Array(amount), function (_, i) {
return rowStart + i;
}), function (index) {
if (!unorderedIndexes.has(index)) {
unorderedIndexes.add(index);
}
});
});
// Sort indexes in ascending order to easily detecting non-consecutive columns.
var orderedIndexes = Array.from(unorderedIndexes).sort(function (a, b) {
return a - b;
});
var normalizedRowRanges = (0, _array.arrayReduce)(orderedIndexes, function (acc, rowIndex, index, array) {
if (index !== 0 && rowIndex === array[index - 1] + 1) {
acc[acc.length - 1][1]++;
} else {
acc.push([rowIndex, 1]);
}
return acc;
}, []);
return normalizedRowRanges;
}
/**
* Check if passed value can be treated as valid cell coordinate. The second argument is
* used to check if the value doesn't exceed the defined max table rows/columns count.
*
* @param {*} coord
* @param {Number} maxTableItemsCount The value that declares the maximum coordinate that is still validatable.
* @return {Boolean}
*/
function isValidCoord(coord) {
var maxTableItemsCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
return typeof coord === 'number' && coord >= 0 && coord < maxTableItemsCount;
};
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _array = __webpack_require__(0);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class GhostTable
* @util
*/
var GhostTable = function () {
function GhostTable(hotInstance) {
_classCallCheck(this, GhostTable);
/**
* Handsontable instance.
*
* @type {Core}
*/
this.hot = hotInstance;
/**
* Container element where every table will be injected.
*
* @type {HTMLElement|null}
*/
this.container = null;
/**
* Flag which determine is table was injected to DOM.
*
* @type {Boolean}
*/
this.injected = false;
/**
* Added rows collection.
*
* @type {Array}
*/
this.rows = [];
/**
* Added columns collection.
*
* @type {Array}
*/
this.columns = [];
/**
* Samples prepared for calculations.
*
* @type {Map}
* @default {null}
*/
this.samples = null;
/**
* Ghost table settings.
*
* @type {Object}
* @default {Object}
*/
this.settings = {
useHeaders: true
};
}
/**
* Add row.
*
* @param {Number} row Row index.
* @param {Map} samples Samples Map object.
*/
_createClass(GhostTable, [{
key: 'addRow',
value: function addRow(row, samples) {
if (this.columns.length) {
throw new Error('Doesn\'t support multi-dimensional table');
}
if (!this.rows.length) {
this.container = this.createContainer(this.hot.rootElement.className);
}
var rowObject = { row: row };
this.rows.push(rowObject);
this.samples = samples;
this.table = this.createTable(this.hot.table.className);
this.table.colGroup.appendChild(this.createColGroupsCol());
this.table.tr.appendChild(this.createRow(row));
this.container.container.appendChild(this.table.fragment);
rowObject.table = this.table.table;
}
/**
* Add a row consisting of the column headers.
*/
}, {
key: 'addColumnHeadersRow',
value: function addColumnHeadersRow(samples) {
if (this.hot.getColHeader(0) != null) {
var rowObject = { row: -1 };
this.rows.push(rowObject);
this.container = this.createContainer(this.hot.rootElement.className);
this.samples = samples;
this.table = this.createTable(this.hot.table.className);
this.table.colGroup.appendChild(this.createColGroupsCol());
this.table.tHead.appendChild(this.createColumnHeadersRow());
this.container.container.appendChild(this.table.fragment);
rowObject.table = this.table.table;
}
}
/**
* Add column.
*
* @param {Number} column Column index.
* @param {Map} samples Samples Map object.
*/
}, {
key: 'addColumn',
value: function addColumn(column, samples) {
if (this.rows.length) {
throw new Error('Doesn\'t support multi-dimensional table');
}
if (!this.columns.length) {
this.container = this.createContainer(this.hot.rootElement.className);
}
var columnObject = { col: column };
this.columns.push(columnObject);
this.samples = samples;
this.table = this.createTable(this.hot.table.className);
if (this.getSetting('useHeaders') && this.hot.getColHeader(column) !== null) {
this.hot.view.appendColHeader(column, this.table.th);
}
this.table.tBody.appendChild(this.createCol(column));
this.container.container.appendChild(this.table.fragment);
columnObject.table = this.table.table;
}
/**
* Get calculated heights.
*
* @param {Function} callback Callback which will be fired for each calculated row.
*/
}, {
key: 'getHeights',
value: function getHeights(callback) {
if (!this.injected) {
this.injectTable();
}
(0, _array.arrayEach)(this.rows, function (row) {
// -1 <- reduce border-top from table
callback(row.row, (0, _element.outerHeight)(row.table) - 1);
});
}
/**
* Get calculated widths.
*
* @param {Function} callback Callback which will be fired for each calculated column.
*/
}, {
key: 'getWidths',
value: function getWidths(callback) {
if (!this.injected) {
this.injectTable();
}
(0, _array.arrayEach)(this.columns, function (column) {
callback(column.col, (0, _element.outerWidth)(column.table));
});
}
/**
* Set the Ghost Table settings to the provided object.
*
* @param {Object} settings New Ghost Table Settings
*/
}, {
key: 'setSettings',
value: function setSettings(settings) {
this.settings = settings;
}
/**
* Set a single setting of the Ghost Table.
*
* @param {String} name Setting name.
* @param {*} value Setting value.
*/
}, {
key: 'setSetting',
value: function setSetting(name, value) {
if (!this.settings) {
this.settings = {};
}
this.settings[name] = value;
}
/**
* Get the Ghost Table settings.
*
* @returns {Object|null}
*/
}, {
key: 'getSettings',
value: function getSettings() {
return this.settings;
}
/**
* Get a single Ghost Table setting.
*
* @param {String} name
* @returns {Boolean|null}
*/
}, {
key: 'getSetting',
value: function getSetting(name) {
if (this.settings) {
return this.settings[name];
}
return null;
}
/**
* Create colgroup col elements.
*
* @returns {DocumentFragment}
*/
}, {
key: 'createColGroupsCol',
value: function createColGroupsCol() {
var _this = this;
var d = document;
var fragment = d.createDocumentFragment();
if (this.hot.hasRowHeaders()) {
fragment.appendChild(this.createColElement(-1));
}
this.samples.forEach(function (sample) {
(0, _array.arrayEach)(sample.strings, function (string) {
fragment.appendChild(_this.createColElement(string.col));
});
});
return fragment;
}
/**
* Create table row element.
*
* @param {Number} row Row index.
* @returns {DocumentFragment} Returns created table row elements.
*/
}, {
key: 'createRow',
value: function createRow(row) {
var _this2 = this;
var d = document;
var fragment = d.createDocumentFragment();
var th = d.createElement('th');
if (this.hot.hasRowHeaders()) {
this.hot.view.appendRowHeader(row, th);
fragment.appendChild(th);
}
this.samples.forEach(function (sample) {
(0, _array.arrayEach)(sample.strings, function (string) {
var column = string.col;
var cellProperties = _this2.hot.getCellMeta(row, column);
cellProperties.col = column;
cellProperties.row = row;
var renderer = _this2.hot.getCellRenderer(cellProperties);
var td = d.createElement('td');
renderer(_this2.hot, td, row, column, _this2.hot.colToProp(column), string.value, cellProperties);
fragment.appendChild(td);
});
});
return fragment;
}
}, {
key: 'createColumnHeadersRow',
value: function createColumnHeadersRow() {
var _this3 = this;
var d = document;
var fragment = d.createDocumentFragment();
if (this.hot.hasRowHeaders()) {
var th = d.createElement('th');
this.hot.view.appendColHeader(-1, th);
fragment.appendChild(th);
}
this.samples.forEach(function (sample) {
(0, _array.arrayEach)(sample.strings, function (string) {
var column = string.col;
var th = d.createElement('th');
_this3.hot.view.appendColHeader(column, th);
fragment.appendChild(th);
});
});
return fragment;
}
/**
* Create table column elements.
*
* @param {Number} column Column index.
* @returns {DocumentFragment} Returns created column table column elements.
*/
}, {
key: 'createCol',
value: function createCol(column) {
var _this4 = this;
var d = document;
var fragment = d.createDocumentFragment();
this.samples.forEach(function (sample) {
(0, _array.arrayEach)(sample.strings, function (string) {
var row = string.row;
var cellProperties = _this4.hot.getCellMeta(row, column);
cellProperties.col = column;
cellProperties.row = row;
var renderer = _this4.hot.getCellRenderer(cellProperties);
var td = d.createElement('td');
var tr = d.createElement('tr');
renderer(_this4.hot, td, row, column, _this4.hot.colToProp(column), string.value, cellProperties);
tr.appendChild(td);
fragment.appendChild(tr);
});
});
return fragment;
}
/**
* Remove table from document and reset internal state.
*/
}, {
key: 'clean',
value: function clean() {
this.rows.length = 0;
this.rows[-1] = void 0;
this.columns.length = 0;
if (this.samples) {
this.samples.clear();
}
this.samples = null;
this.removeTable();
}
/**
* Inject generated table into document.
*
* @param {HTMLElement} [parent=null]
*/
}, {
key: 'injectTable',
value: function injectTable() {
var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
if (!this.injected) {
(parent || this.hot.rootElement).appendChild(this.container.fragment);
this.injected = true;
}
}
/**
* Remove table from document.
*/
}, {
key: 'removeTable',
value: function removeTable() {
if (this.injected && this.container.container.parentNode) {
this.container.container.parentNode.removeChild(this.container.container);
this.container = null;
this.injected = false;
}
}
/**
* Create col element.
*
* @param {Number} column Column index.
* @returns {HTMLElement}
*/
}, {
key: 'createColElement',
value: function createColElement(column) {
var d = document;
var col = d.createElement('col');
col.style.width = this.hot.view.wt.wtTable.getStretchedColumnWidth(column) + 'px';
return col;
}
/**
* Create table element.
*
* @param {String} className
* @returns {Object}
*/
}, {
key: 'createTable',
value: function createTable() {
var className = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var d = document;
var fragment = d.createDocumentFragment();
var table = d.createElement('table');
var tHead = d.createElement('thead');
var tBody = d.createElement('tbody');
var colGroup = d.createElement('colgroup');
var tr = d.createElement('tr');
var th = d.createElement('th');
if (this.isVertical()) {
table.appendChild(colGroup);
}
if (this.isHorizontal()) {
tr.appendChild(th);
tHead.appendChild(tr);
table.style.tableLayout = 'auto';
table.style.width = 'auto';
}
table.appendChild(tHead);
if (this.isVertical()) {
tBody.appendChild(tr);
}
table.appendChild(tBody);
(0, _element.addClass)(table, className);
fragment.appendChild(table);
return { fragment: fragment, table: table, tHead: tHead, tBody: tBody, colGroup: colGroup, tr: tr, th: th };
}
/**
* Create container for tables.
*
* @param {String} className
* @returns {Object}
*/
}, {
key: 'createContainer',
value: function createContainer() {
var className = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var d = document;
var fragment = d.createDocumentFragment();
var container = d.createElement('div');
className = 'htGhostTable htAutoSize ' + className.trim();
(0, _element.addClass)(container, className);
fragment.appendChild(container);
return { fragment: fragment, container: container };
}
/**
* Checks if table is raised vertically (checking rows).
*
* @returns {Boolean}
*/
}, {
key: 'isVertical',
value: function isVertical() {
return !!(this.rows.length && !this.columns.length);
}
/**
* Checks if table is raised horizontally (checking columns).
*
* @returns {Boolean}
*/
}, {
key: 'isHorizontal',
value: function isHorizontal() {
return !!(this.columns.length && !this.rows.length);
}
}]);
return GhostTable;
}();
exports.default = GhostTable;
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = separatorItem;
var KEY = exports.KEY = '---------';
function separatorItem() {
return {
name: KEY
};
}
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _core = __webpack_require__(152);
var _core2 = _interopRequireDefault(_core);
var _element = __webpack_require__(2);
var _array = __webpack_require__(0);
var _cursor = __webpack_require__(582);
var _cursor2 = _interopRequireDefault(_cursor);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _object = __webpack_require__(1);
var _mixed = __webpack_require__(13);
var _function = __webpack_require__(35);
var _utils = __webpack_require__(24);
var _unicode = __webpack_require__(18);
var _localHooks = __webpack_require__(21);
var _localHooks2 = _interopRequireDefault(_localHooks);
var _predefinedItems = __webpack_require__(44);
var _event = __webpack_require__(11);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Menu
* @plugin ContextMenu
*/
var Menu = function () {
function Menu(hotInstance, options) {
_classCallCheck(this, Menu);
this.hot = hotInstance;
this.options = options || {
parent: null,
name: null,
className: '',
keepInViewport: true,
standalone: false
};
this.eventManager = new _eventManager2.default(this);
this.container = this.createContainer(this.options.name);
this.hotMenu = null;
this.hotSubMenus = {};
this.parentMenu = this.options.parent || null;
this.menuItems = null;
this.origOutsideClickDeselects = null;
this.keyEvent = false;
this.offset = {
above: 0,
below: 0,
left: 0,
right: 0
};
this._afterScrollCallback = null;
this.registerEvents();
}
/**
* Register event listeners.
*
* @private
*/
_createClass(Menu, [{
key: 'registerEvents',
value: function registerEvents() {
var _this = this;
this.eventManager.addEventListener(document.documentElement, 'mousedown', function (event) {
return _this.onDocumentMouseDown(event);
});
}
/**
* Set array of objects which defines menu items.
*
* @param {Array} menuItems Menu items to display.
*/
}, {
key: 'setMenuItems',
value: function setMenuItems(menuItems) {
this.menuItems = menuItems;
}
/**
* Set offset menu position for specified area (`above`, `below`, `left` or `right`).
*
* @param {String} area Specified area name (`above`, `below`, `left` or `right`).
* @param {Number} offset Offset value.
*/
}, {
key: 'setOffset',
value: function setOffset(area) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
this.offset[area] = offset;
}
/**
* Check if menu is using as sub-menu.
*
* @returns {Boolean}
*/
}, {
key: 'isSubMenu',
value: function isSubMenu() {
return this.parentMenu !== null;
}
/**
* Open menu.
*/
}, {
key: 'open',
value: function open() {
var _this2 = this;
this.container.removeAttribute('style');
this.container.style.display = 'block';
var delayedOpenSubMenu = (0, _function.debounce)(function (row) {
return _this2.openSubMenu(row);
}, 300);
var filteredItems = (0, _array.arrayFilter)(this.menuItems, function (item) {
return (0, _utils.isItemHidden)(item, _this2.hot);
});
filteredItems = (0, _utils.filterSeparators)(filteredItems, _predefinedItems.SEPARATOR);
var settings = {
data: filteredItems,
colHeaders: false,
colWidths: [215],
autoRowSize: false,
readOnly: true,
copyPaste: false,
columns: [{
data: 'name',
renderer: function renderer(hot, TD, row, col, prop, value) {
return _this2.menuItemRenderer(hot, TD, row, col, prop, value);
}
}],
renderAllRows: true,
fragmentSelection: 'cell',
disableVisualSelection: 'area',
beforeKeyDown: function beforeKeyDown(event) {
return _this2.onBeforeKeyDown(event);
},
afterOnCellMouseOver: function afterOnCellMouseOver(event, coords, TD) {
if (_this2.isAllSubMenusClosed()) {
delayedOpenSubMenu(coords.row);
} else {
_this2.openSubMenu(coords.row);
}
},
rowHeights: function rowHeights(row) {
return filteredItems[row].name === _predefinedItems.SEPARATOR ? 1 : 23;
}
};
this.origOutsideClickDeselects = this.hot.getSettings().outsideClickDeselects;
this.hot.getSettings().outsideClickDeselects = false;
this.hotMenu = new _core2.default(this.container, settings);
this.hotMenu.addHook('afterInit', function () {
return _this2.onAfterInit();
});
this.hotMenu.addHook('afterSelection', function () {
return _this2.onAfterSelection.apply(_this2, arguments);
});
this.hotMenu.init();
this.hotMenu.listen();
this.blockMainTableCallbacks();
this.runLocalHooks('afterOpen');
}
/**
* Close menu.
*
* @param {Boolean} [closeParent=false] if `true` try to close parent menu if exists.
*/
}, {
key: 'close',
value: function close() {
var closeParent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!this.isOpened()) {
return;
}
if (closeParent && this.parentMenu) {
this.parentMenu.close();
} else {
this.closeAllSubMenus();
this.container.style.display = 'none';
this.releaseMainTableCallbacks();
this.hotMenu.destroy();
this.hotMenu = null;
this.hot.getSettings().outsideClickDeselects = this.origOutsideClickDeselects;
this.runLocalHooks('afterClose');
if (this.parentMenu) {
this.parentMenu.hotMenu.listen();
}
}
}
/**
* Open sub menu at the provided row index.
*
* @param {Number} row Row index.
* @returns {Menu|Boolean} Returns created menu or `false` if no one menu was created.
*/
}, {
key: 'openSubMenu',
value: function openSubMenu(row) {
if (!this.hotMenu) {
return false;
}
var cell = this.hotMenu.getCell(row, 0);
this.closeAllSubMenus();
if (!cell || !(0, _utils.hasSubMenu)(cell)) {
return false;
}
var dataItem = this.hotMenu.getSourceDataAtRow(row);
var subMenu = new Menu(this.hot, {
parent: this,
name: dataItem.name,
className: this.options.className,
keepInViewport: true
});
subMenu.setMenuItems(dataItem.submenu.items);
subMenu.open();
subMenu.setPosition(cell.getBoundingClientRect());
this.hotSubMenus[dataItem.key] = subMenu;
return subMenu;
}
/**
* Close sub menu at row index.
*
* @param {Number} row Row index.
*/
}, {
key: 'closeSubMenu',
value: function closeSubMenu(row) {
var dataItem = this.hotMenu.getSourceDataAtRow(row);
var menus = this.hotSubMenus[dataItem.key];
if (menus) {
menus.destroy();
delete this.hotSubMenus[dataItem.key];
}
}
/**
* Close all opened sub menus.
*/
}, {
key: 'closeAllSubMenus',
value: function closeAllSubMenus() {
var _this3 = this;
(0, _array.arrayEach)(this.hotMenu.getData(), function (value, row) {
return _this3.closeSubMenu(row);
});
}
/**
* Checks if all created and opened sub menus are closed.
*
* @returns {Boolean}
*/
}, {
key: 'isAllSubMenusClosed',
value: function isAllSubMenusClosed() {
return Object.keys(this.hotSubMenus).length === 0;
}
/**
* Destroy instance.
*/
}, {
key: 'destroy',
value: function destroy() {
this.clearLocalHooks();
this.close();
this.parentMenu = null;
this.eventManager.destroy();
}
/**
* Checks if menu was opened.
*
* @returns {Boolean} Returns `true` if menu was opened.
*/
}, {
key: 'isOpened',
value: function isOpened() {
return this.hotMenu !== null;
}
/**
* Execute menu command.
*
* @param {Event} [event]
*/
}, {
key: 'executeCommand',
value: function executeCommand(event) {
if (!this.isOpened() || !this.hotMenu.getSelectedLast()) {
return;
}
var selectedItem = this.hotMenu.getSourceDataAtRow(this.hotMenu.getSelectedLast()[0]);
this.runLocalHooks('select', selectedItem, event);
if (selectedItem.isCommand === false || selectedItem.name === _predefinedItems.SEPARATOR) {
return;
}
var selRanges = this.hot.getSelectedRange();
var normalizedSelection = selRanges ? (0, _utils.normalizeSelection)(selRanges) : [];
var autoClose = true;
// Don't close context menu if item is disabled or it has submenu
if (selectedItem.disabled === true || typeof selectedItem.disabled === 'function' && selectedItem.disabled.call(this.hot) === true || selectedItem.submenu) {
autoClose = false;
}
this.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);
if (this.isSubMenu()) {
this.parentMenu.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);
}
if (autoClose) {
this.close(true);
}
}
/**
* Set menu position based on dom event or based on literal object.
*
* @param {Event|Object} coords Event or literal Object with coordinates.
*/
}, {
key: 'setPosition',
value: function setPosition(coords) {
var cursor = new _cursor2.default(coords);
if (this.options.keepInViewport) {
if (cursor.fitsBelow(this.container)) {
this.setPositionBelowCursor(cursor);
} else if (cursor.fitsAbove(this.container)) {
this.setPositionAboveCursor(cursor);
} else {
this.setPositionBelowCursor(cursor);
}
if (cursor.fitsOnRight(this.container)) {
this.setPositionOnRightOfCursor(cursor);
} else {
this.setPositionOnLeftOfCursor(cursor);
}
} else {
this.setPositionBelowCursor(cursor);
this.setPositionOnRightOfCursor(cursor);
}
}
/**
* Set menu position above cursor object.
*
* @param {Cursor} cursor `Cursor` object.
*/
}, {
key: 'setPositionAboveCursor',
value: function setPositionAboveCursor(cursor) {
var top = this.offset.above + cursor.top - this.container.offsetHeight;
if (this.isSubMenu()) {
top = cursor.top + cursor.cellHeight - this.container.offsetHeight + 3;
}
this.container.style.top = top + 'px';
}
/**
* Set menu position below cursor object.
*
* @param {Cursor} cursor `Cursor` object.
*/
}, {
key: 'setPositionBelowCursor',
value: function setPositionBelowCursor(cursor) {
var top = this.offset.below + cursor.top;
if (this.isSubMenu()) {
top = cursor.top - 1;
}
this.container.style.top = top + 'px';
}
/**
* Set menu position on the right of cursor object.
*
* @param {Cursor} cursor `Cursor` object.
*/
}, {
key: 'setPositionOnRightOfCursor',
value: function setPositionOnRightOfCursor(cursor) {
var left = void 0;
if (this.isSubMenu()) {
left = 1 + cursor.left + cursor.cellWidth;
} else {
left = this.offset.right + 1 + cursor.left;
}
this.container.style.left = left + 'px';
}
/**
* Set menu position on the left of cursor object.
*
* @param {Cursor} cursor `Cursor` object.
*/
}, {
key: 'setPositionOnLeftOfCursor',
value: function setPositionOnLeftOfCursor(cursor) {
var left = this.offset.left + cursor.left - this.container.offsetWidth + (0, _element.getScrollbarWidth)() + 4;
this.container.style.left = left + 'px';
}
/**
* Select first cell in opened menu.
*/
}, {
key: 'selectFirstCell',
value: function selectFirstCell() {
var cell = this.hotMenu.getCell(0, 0);
if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
this.selectNextCell(0, 0);
} else {
this.hotMenu.selectCell(0, 0);
}
}
/**
* Select last cell in opened menu.
*/
}, {
key: 'selectLastCell',
value: function selectLastCell() {
var lastRow = this.hotMenu.countRows() - 1;
var cell = this.hotMenu.getCell(lastRow, 0);
if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
this.selectPrevCell(lastRow, 0);
} else {
this.hotMenu.selectCell(lastRow, 0);
}
}
/**
* Select next cell in opened menu.
*
* @param {Number} row Row index.
* @param {Number} col Column index.
*/
}, {
key: 'selectNextCell',
value: function selectNextCell(row, col) {
var nextRow = row + 1;
var cell = nextRow < this.hotMenu.countRows() ? this.hotMenu.getCell(nextRow, col) : null;
if (!cell) {
return;
}
if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
this.selectNextCell(nextRow, col);
} else {
this.hotMenu.selectCell(nextRow, col);
}
}
/**
* Select previous cell in opened menu.
*
* @param {Number} row Row index.
* @param {Number} col Column index.
*/
}, {
key: 'selectPrevCell',
value: function selectPrevCell(row, col) {
var prevRow = row - 1;
var cell = prevRow >= 0 ? this.hotMenu.getCell(prevRow, col) : null;
if (!cell) {
return;
}
if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
this.selectPrevCell(prevRow, col);
} else {
this.hotMenu.selectCell(prevRow, col);
}
}
/**
* Menu item renderer.
*
* @private
*/
}, {
key: 'menuItemRenderer',
value: function menuItemRenderer(hot, TD, row, col, prop, value) {
var _this4 = this;
var item = hot.getSourceDataAtRow(row);
var wrapper = document.createElement('div');
var isSubMenu = function isSubMenu(item) {
return (0, _object.hasOwnProperty)(item, 'submenu');
};
var itemIsSeparator = function itemIsSeparator(item) {
return new RegExp(_predefinedItems.SEPARATOR, 'i').test(item.name);
};
var itemIsDisabled = function itemIsDisabled(item) {
return item.disabled === true || typeof item.disabled == 'function' && item.disabled.call(_this4.hot) === true;
};
var itemIsSelectionDisabled = function itemIsSelectionDisabled(item) {
return item.disableSelection;
};
if (typeof value === 'function') {
value = value.call(this.hot);
}
(0, _element.empty)(TD);
(0, _element.addClass)(wrapper, 'htItemWrapper');
TD.appendChild(wrapper);
if (itemIsSeparator(item)) {
(0, _element.addClass)(TD, 'htSeparator');
} else if (typeof item.renderer === 'function') {
(0, _element.addClass)(TD, 'htCustomMenuRenderer');
TD.appendChild(item.renderer(hot, wrapper, row, col, prop, value));
} else {
(0, _element.fastInnerHTML)(wrapper, value);
}
if (itemIsDisabled(item)) {
(0, _element.addClass)(TD, 'htDisabled');
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.deselectCell();
});
} else if (itemIsSelectionDisabled(item)) {
(0, _element.addClass)(TD, 'htSelectionDisabled');
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.deselectCell();
});
} else if (isSubMenu(item)) {
(0, _element.addClass)(TD, 'htSubmenu');
if (itemIsSelectionDisabled(item)) {
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.deselectCell();
});
} else {
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.selectCell(row, col, void 0, void 0, false, false);
});
}
} else {
(0, _element.removeClass)(TD, 'htSubmenu');
(0, _element.removeClass)(TD, 'htDisabled');
if (itemIsSelectionDisabled(item)) {
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.deselectCell();
});
} else {
this.eventManager.addEventListener(TD, 'mouseenter', function () {
return hot.selectCell(row, col, void 0, void 0, false, false);
});
}
}
}
/**
* Create container/wrapper for handsontable.
*
* @private
* @param {String} [name] Class name.
* @returns {HTMLElement}
*/
}, {
key: 'createContainer',
value: function createContainer() {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var container = void 0;
if (name) {
if ((0, _function.isFunction)(name)) {
name = name.call(this.hot);
if (name === null || (0, _mixed.isUndefined)(name)) {
name = '';
} else {
name = name.toString();
}
}
name = name.replace(/[^A-z0-9]/g, '_');
name = this.options.className + 'Sub_' + name;
container = document.querySelector('.' + this.options.className + '.' + name);
} else {
container = document.querySelector('.' + this.options.className);
}
if (!container) {
container = document.createElement('div');
(0, _element.addClass)(container, 'htMenu ' + this.options.className);
if (name) {
(0, _element.addClass)(container, name);
}
document.getElementsByTagName('body')[0].appendChild(container);
}
return container;
}
/**
* @private
*/
}, {
key: 'blockMainTableCallbacks',
value: function blockMainTableCallbacks() {
this._afterScrollCallback = function () {};
this.hot.addHook('afterScrollVertically', this._afterScrollCallback);
this.hot.addHook('afterScrollHorizontally', this._afterScrollCallback);
}
/**
* @private
*/
}, {
key: 'releaseMainTableCallbacks',
value: function releaseMainTableCallbacks() {
if (this._afterScrollCallback) {
this.hot.removeHook('afterScrollVertically', this._afterScrollCallback);
this.hot.removeHook('afterScrollHorizontally', this._afterScrollCallback);
this._afterScrollCallback = null;
}
}
/**
* On before key down listener.
*
* @private
* @param {Event} event
*/
}, {
key: 'onBeforeKeyDown',
value: function onBeforeKeyDown(event) {
var selection = this.hotMenu.getSelectedLast();
var stopEvent = false;
this.keyEvent = true;
switch (event.keyCode) {
case _unicode.KEY_CODES.ESCAPE:
this.close();
stopEvent = true;
break;
case _unicode.KEY_CODES.ENTER:
if (selection) {
if (this.hotMenu.getSourceDataAtRow(selection[0]).submenu) {
stopEvent = true;
} else {
this.executeCommand(event);
this.close(true);
}
}
break;
case _unicode.KEY_CODES.ARROW_DOWN:
if (selection) {
this.selectNextCell(selection[0], selection[1]);
} else {
this.selectFirstCell();
}
stopEvent = true;
break;
case _unicode.KEY_CODES.ARROW_UP:
if (selection) {
this.selectPrevCell(selection[0], selection[1]);
} else {
this.selectLastCell();
}
stopEvent = true;
break;
case _unicode.KEY_CODES.ARROW_RIGHT:
if (selection) {
var menu = this.openSubMenu(selection[0]);
if (menu) {
menu.selectFirstCell();
}
}
stopEvent = true;
break;
case _unicode.KEY_CODES.ARROW_LEFT:
if (selection && this.isSubMenu()) {
this.close();
if (this.parentMenu) {
this.parentMenu.hotMenu.listen();
}
stopEvent = true;
}
break;
default:
break;
}
if (stopEvent) {
event.preventDefault();
(0, _event.stopImmediatePropagation)(event);
}
this.keyEvent = false;
}
/**
* On after init listener.
*
* @private
*/
}, {
key: 'onAfterInit',
value: function onAfterInit() {
var data = this.hotMenu.getSettings().data;
var hiderStyle = this.hotMenu.view.wt.wtTable.hider.style;
var holderStyle = this.hotMenu.view.wt.wtTable.holder.style;
var currentHiderWidth = parseInt(hiderStyle.width, 10);
var realHeight = (0, _array.arrayReduce)(data, function (accumulator, value) {
return accumulator + (value.name === _predefinedItems.SEPARATOR ? 1 : 26);
}, 0);
holderStyle.width = currentHiderWidth + 22 + 'px';
holderStyle.height = realHeight + 4 + 'px';
hiderStyle.height = holderStyle.height;
}
/**
* On after selection listener.
*
* @param {Number} r Selection start row index.
* @param {Number} c Selection start column index.
* @param {Number} r2 Selection end row index.
* @param {Number} c2 Selection end column index.
* @param {Object} preventScrolling Object with `value` property where its value change will be observed.
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified.
*/
}, {
key: 'onAfterSelection',
value: function onAfterSelection(r, c, r2, c2, preventScrolling) {
if (this.keyEvent === false) {
preventScrolling.value = true;
}
}
/**
* Document mouse down listener.
*
* @private
* @param {Event} event
*/
}, {
key: 'onDocumentMouseDown',
value: function onDocumentMouseDown(event) {
if (!this.isOpened()) {
return;
}
if (this.container && (0, _element.isChildOf)(event.target, this.container)) {
this.executeCommand(event);
}
// Close menu when clicked element is not belongs to menu itself
if (this.options.standalone && this.hotMenu && !(0, _element.isChildOf)(event.target, this.hotMenu.rootElement)) {
this.close(true);
// Automatically close menu when clicked element is not belongs to menu or submenu (not necessarily to itself)
} else if ((this.isAllSubMenusClosed() || this.isSubMenu()) && !(0, _element.isChildOf)(event.target, '.htMenu') && (0, _element.isChildOf)(event.target, document)) {
this.close(true);
}
}
}]);
return Menu;
}();
(0, _object.mixin)(Menu, _localHooks2.default);
exports.default = Menu;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _templateObject = _taggedTemplateLiteral(['The merged cell declared with {row: ', ', col: ', ', rowspan: \n ', ', colspan: ', '} contains negative values, which is not supported. It \n will not be added to the collection.'], ['The merged cell declared with {row: ', ', col: ', ', rowspan: \n ', ', colspan: ', '} contains negative values, which is not supported. It \n will not be added to the collection.']),
_templateObject2 = _taggedTemplateLiteral(['The merged cell declared at [', ', ', '] is positioned (or positioned partially) \n outside of the table range. It was not added to the table, please fix your setup.'], ['The merged cell declared at [', ', ', '] is positioned (or positioned partially) \n outside of the table range. It was not added to the table, please fix your setup.']),
_templateObject3 = _taggedTemplateLiteral(['The merged cell declared at [', ', ', '] has both "rowspan" \n and "colspan" declared as "1", which makes it a single cell. It cannot be added to the collection.'], ['The merged cell declared at [', ', ', '] has both "rowspan" \n and "colspan" declared as "1", which makes it a single cell. It cannot be added to the collection.']),
_templateObject4 = _taggedTemplateLiteral(['The merged cell declared at [', ', ', '] has "rowspan" or "colspan" declared as \n "0", which is not supported. It cannot be added to the collection.'], ['The merged cell declared at [', ', ', '] has "rowspan" or "colspan" declared as \n "0", which is not supported. It cannot be added to the collection.']);
var _index = __webpack_require__(8);
var _templateLiteralTag = __webpack_require__(34);
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* The `MergedCellCoords` class represents a single merged cell.
*
* @class MergedCellCoords
* @plugin MergeCells
*/
var MergedCellCoords = function () {
function MergedCellCoords(row, column, rowspan, colspan) {
_classCallCheck(this, MergedCellCoords);
/**
* The index of the topmost merged cell row.
*
* @type {Number}
*/
this.row = row;
/**
* The index of the leftmost column.
*
* @type {Number}
*/
this.col = column;
/**
* The `rowspan` value of the merged cell.
*
* @type {Number}
*/
this.rowspan = rowspan;
/**
* The `colspan` value of the merged cell.
*
* @type {Number}
*/
this.colspan = colspan;
/**
* `true` only if the merged cell is bound to be removed.
*
* @type {Boolean}
*/
this.removed = false;
}
/**
* Get a warning message for when the declared merged cell data contains negative values.
*
* @param {Object} newMergedCell Object containg information about the merged cells that was about to be added.
* @return {String}
*/
_createClass(MergedCellCoords, [{
key: 'normalize',
/**
* Sanitize (prevent from going outside the boundaries) the merged cell.
*
* @param hotInstance
*/
value: function normalize(hotInstance) {
var totalRows = hotInstance.countRows();
var totalColumns = hotInstance.countCols();
if (this.row < 0) {
this.row = 0;
} else if (this.row > totalRows - 1) {
this.row = totalRows - 1;
}
if (this.col < 0) {
this.col = 0;
} else if (this.col > totalColumns - 1) {
this.col = totalColumns - 1;
}
if (this.row + this.rowspan > totalRows - 1) {
this.rowspan = totalRows - this.row;
}
if (this.col + this.colspan > totalColumns - 1) {
this.colspan = totalColumns - this.col;
}
}
/**
* Returns `true` if the provided coordinates are inside the merged cell.
*
* @param {Number} row The row index.
* @param {Number} column The column index.
* @return {Boolean}
*/
}, {
key: 'includes',
value: function includes(row, column) {
return this.row <= row && this.col <= column && this.row + this.rowspan - 1 >= row && this.col + this.colspan - 1 >= column;
}
/**
* Returns `true` if the provided `column` property is within the column span of the merged cell.
*
* @param {Number} column The column index.
* @return {Boolean}
*/
}, {
key: 'includesHorizontally',
value: function includesHorizontally(column) {
return this.col <= column && this.col + this.colspan - 1 >= column;
}
/**
* Returns `true` if the provided `row` property is within the row span of the merged cell.
*
* @param {Number} row Row index.
* @return {Boolean}
*/
}, {
key: 'includesVertically',
value: function includesVertically(row) {
return this.row <= row && this.row + this.rowspan - 1 >= row;
}
/**
* Shift (and possibly resize, if needed) the merged cell.
*
* @param {Array} shiftVector 2-element array containing the information on the shifting in the `x` and `y` axis.
* @param {Number} indexOfChange Index of the preceding change.
* @returns {Boolean} Returns `false` if the whole merged cell was removed.
*/
}, {
key: 'shift',
value: function shift(shiftVector, indexOfChange) {
var shiftValue = shiftVector[0] || shiftVector[1];
var shiftedIndex = indexOfChange + Math.abs(shiftVector[0] || shiftVector[1]) - 1;
var span = shiftVector[0] ? 'colspan' : 'rowspan';
var index = shiftVector[0] ? 'col' : 'row';
var changeStart = Math.min(indexOfChange, shiftedIndex);
var changeEnd = Math.max(indexOfChange, shiftedIndex);
var mergeStart = this[index];
var mergeEnd = this[index] + this[span] - 1;
if (mergeStart >= indexOfChange) {
this[index] += shiftValue;
}
// adding rows/columns
if (shiftValue > 0) {
if (indexOfChange <= mergeEnd && indexOfChange > mergeStart) {
this[span] += shiftValue;
}
// removing rows/columns
} else if (shiftValue < 0) {
// removing the whole merge
if (changeStart <= mergeStart && changeEnd >= mergeEnd) {
this.removed = true;
return false;
// removing the merge partially, including the beginning
} else if (mergeStart >= changeStart && mergeStart <= changeEnd) {
var removedOffset = changeEnd - mergeStart + 1;
var preRemovedOffset = Math.abs(shiftValue) - removedOffset;
this[index] -= preRemovedOffset;
this[span] -= removedOffset;
// removing the middle part of the merge
} else if (mergeStart <= changeStart && mergeEnd >= changeEnd) {
this[span] += shiftValue;
// removing the end part of the merge
} else if (mergeStart <= changeStart && mergeEnd >= changeStart && mergeEnd < changeEnd) {
var removedPart = mergeEnd - changeStart + 1;
this[span] -= removedPart;
}
}
return true;
}
/**
* Check if the second provided merged cell is "farther" in the provided direction.
*
* @param {MergedCellCoords} mergedCell The merged cell to check.
* @param {String} direction Drag direction.
* @return {Boolean|null} `true` if the second provided merged cell is "farther".
*/
}, {
key: 'isFarther',
value: function isFarther(mergedCell, direction) {
if (!mergedCell) {
return true;
}
if (direction === 'down') {
return mergedCell.row + mergedCell.rowspan - 1 < this.row + this.rowspan - 1;
} else if (direction === 'up') {
return mergedCell.row > this.row;
} else if (direction === 'right') {
return mergedCell.col + mergedCell.colspan - 1 < this.col + this.colspan - 1;
} else if (direction === 'left') {
return mergedCell.col > this.col;
}
return null;
}
/**
* Get the bottom row index of the merged cell.
*
* @returns {Number}
*/
}, {
key: 'getLastRow',
value: function getLastRow() {
return this.row + this.rowspan - 1;
}
/**
* Get the rightmost column index of the merged cell.
*
* @returns {Number}
*/
}, {
key: 'getLastColumn',
value: function getLastColumn() {
return this.col + this.colspan - 1;
}
/**
* Get the range coordinates of the merged cell.
*
* @return {CellRange}
*/
}, {
key: 'getRange',
value: function getRange() {
return new _index.CellRange(new _index.CellCoords(this.row, this.col), new _index.CellCoords(this.row, this.col), new _index.CellCoords(this.getLastRow(), this.getLastColumn()));
}
}], [{
key: 'NEGATIVE_VALUES_WARNING',
value: function NEGATIVE_VALUES_WARNING(newMergedCell) {
return (0, _templateLiteralTag.toSingleLine)(_templateObject, newMergedCell.row, newMergedCell.col, newMergedCell.rowspan, newMergedCell.colspan);
}
/**
* Get a warning message for when the declared merged cell data contains values exceeding the table limits.
*
* @param {Object} newMergedCell Object containg information about the merged cells that was about to be added.
* @return {String}
*/
}, {
key: 'IS_OUT_OF_BOUNDS_WARNING',
value: function IS_OUT_OF_BOUNDS_WARNING(newMergedCell) {
return (0, _templateLiteralTag.toSingleLine)(_templateObject2, newMergedCell.row, newMergedCell.col);
}
/**
* Get a warning message for when the declared merged cell data represents a single cell.
*
* @param {Object} newMergedCell Object containg information about the merged cells that was about to be added.
* @return {String}
*/
}, {
key: 'IS_SINGLE_CELL',
value: function IS_SINGLE_CELL(newMergedCell) {
return (0, _templateLiteralTag.toSingleLine)(_templateObject3, newMergedCell.row, newMergedCell.col);
}
/**
* Get a warning message for when the declared merged cell data contains "colspan" or "rowspan", that equals 0.
*
* @param {Object} newMergedCell Object containg information about the merged cells that was about to be added.
* @return {String}
*/
}, {
key: 'ZERO_SPAN_WARNING',
value: function ZERO_SPAN_WARNING(newMergedCell) {
return (0, _templateLiteralTag.toSingleLine)(_templateObject4, newMergedCell.row, newMergedCell.col);
}
/**
* Check whether the values provided for a merged cell contain any negative values.
*
* @param {Object} mergedCellInfo Object containing the `row`, `col`, `rowspan` and `colspan` properties.
* @return {Boolean}
*/
}, {
key: 'containsNegativeValues',
value: function containsNegativeValues(mergedCellInfo) {
return mergedCellInfo.row < 0 || mergedCellInfo.col < 0 || mergedCellInfo.rowspan < 0 || mergedCellInfo.colspan < 0;
}
/**
* Check whether the provided merged cell information object represents a single cell.
*
* @private
* @param {Object} mergedCellInfo An object with `row`, `col`, `rowspan` and `colspan` properties.
* @return {Boolean}
*/
}, {
key: 'isSingleCell',
value: function isSingleCell(mergedCellInfo) {
return mergedCellInfo.colspan === 1 && mergedCellInfo.rowspan === 1;
}
/**
* Check whether the provided merged cell information object contains a rowspan or colspan of 0.
*
* @private
* @param {Object} mergedCellInfo An object with `row`, `col`, `rowspan` and `colspan` properties.
* @return {Boolean}
*/
}, {
key: 'containsZeroSpan',
value: function containsZeroSpan(mergedCellInfo) {
return mergedCellInfo.colspan === 0 || mergedCellInfo.rowspan === 0;
}
/**
* Check whether the provided merged cell object is to be declared out of bounds of the table.
*
* @param {Object} mergeCell Object containing the `row`, `col`, `rowspan` and `colspan` properties.
* @param {Number} rowCount Number of rows in the table.
* @param {Number} columnCount Number of rows in the table.
* @return {Boolean}
*/
}, {
key: 'isOutOfBounds',
value: function isOutOfBounds(mergeCell, rowCount, columnCount) {
return mergeCell.row < 0 || mergeCell.col < 0 || mergeCell.row >= rowCount || mergeCell.row + mergeCell.rowspan - 1 >= rowCount || mergeCell.col >= columnCount || mergeCell.col + mergeCell.colspan - 1 >= columnCount;
}
}]);
return MergedCellCoords;
}();
exports.default = MergedCellCoords;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.TYPES = exports.TYPE_DATE = exports.TYPE_TEXT = exports.TYPE_NUMERIC = exports.OPERATION_OR_THEN_VARIABLE = exports.OPERATION_OR = exports.OPERATION_AND = exports.CONDITION_FALSE = exports.CONDITION_TRUE = exports.CONDITION_BY_VALUE = exports.CONDITION_YESTERDAY = exports.CONDITION_TODAY = exports.CONDITION_TOMORROW = exports.CONDITION_DATE_AFTER = exports.CONDITION_DATE_BEFORE = exports.CONDITION_NOT_CONTAINS = exports.CONDITION_CONTAINS = exports.CONDITION_ENDS_WITH = exports.CONDITION_BEGINS_WITH = exports.CONDITION_NOT_BETWEEN = exports.CONDITION_BETWEEN = exports.CONDITION_LESS_THAN_OR_EQUAL = exports.CONDITION_LESS_THAN = exports.CONDITION_GREATER_THAN_OR_EQUAL = exports.CONDITION_GREATER_THAN = exports.CONDITION_NOT_EQUAL = exports.CONDITION_EQUAL = exports.CONDITION_NOT_EMPTY = exports.CONDITION_EMPTY = exports.CONDITION_NONE = undefined;
var _TYPES;
exports.default = getOptionsList;
var _object = __webpack_require__(1);
var _array = __webpack_require__(0);
var _predefinedItems = __webpack_require__(44);
var _conditionRegisterer = __webpack_require__(10);
var _none = __webpack_require__(641);
var _empty = __webpack_require__(462);
var _notEmpty = __webpack_require__(642);
var _equal = __webpack_require__(463);
var _notEqual = __webpack_require__(643);
var _greaterThan = __webpack_require__(644);
var _greaterThanOrEqual = __webpack_require__(645);
var _lessThan = __webpack_require__(646);
var _lessThanOrEqual = __webpack_require__(647);
var _between = __webpack_require__(464);
var _notBetween = __webpack_require__(648);
var _beginsWith = __webpack_require__(649);
var _endsWith = __webpack_require__(650);
var _contains = __webpack_require__(467);
var _notContains = __webpack_require__(651);
var _before = __webpack_require__(466);
var _after = __webpack_require__(465);
var _tomorrow = __webpack_require__(652);
var _today = __webpack_require__(653);
var _yesterday = __webpack_require__(654);
var _byValue = __webpack_require__(655);
var _true = __webpack_require__(656);
var _false = __webpack_require__(657);
var _conjunction = __webpack_require__(160);
var _disjunction = __webpack_require__(468);
var _disjunctionAndVariable = __webpack_require__(469);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
exports.CONDITION_NONE = _none.CONDITION_NAME;
exports.CONDITION_EMPTY = _empty.CONDITION_NAME;
exports.CONDITION_NOT_EMPTY = _notEmpty.CONDITION_NAME;
exports.CONDITION_EQUAL = _equal.CONDITION_NAME;
exports.CONDITION_NOT_EQUAL = _notEqual.CONDITION_NAME;
exports.CONDITION_GREATER_THAN = _greaterThan.CONDITION_NAME;
exports.CONDITION_GREATER_THAN_OR_EQUAL = _greaterThanOrEqual.CONDITION_NAME;
exports.CONDITION_LESS_THAN = _lessThan.CONDITION_NAME;
exports.CONDITION_LESS_THAN_OR_EQUAL = _lessThanOrEqual.CONDITION_NAME;
exports.CONDITION_BETWEEN = _between.CONDITION_NAME;
exports.CONDITION_NOT_BETWEEN = _notBetween.CONDITION_NAME;
exports.CONDITION_BEGINS_WITH = _beginsWith.CONDITION_NAME;
exports.CONDITION_ENDS_WITH = _endsWith.CONDITION_NAME;
exports.CONDITION_CONTAINS = _contains.CONDITION_NAME;
exports.CONDITION_NOT_CONTAINS = _notContains.CONDITION_NAME;
exports.CONDITION_DATE_BEFORE = _before.CONDITION_NAME;
exports.CONDITION_DATE_AFTER = _after.CONDITION_NAME;
exports.CONDITION_TOMORROW = _tomorrow.CONDITION_NAME;
exports.CONDITION_TODAY = _today.CONDITION_NAME;
exports.CONDITION_YESTERDAY = _yesterday.CONDITION_NAME;
exports.CONDITION_BY_VALUE = _byValue.CONDITION_NAME;
exports.CONDITION_TRUE = _true.CONDITION_NAME;
exports.CONDITION_FALSE = _false.CONDITION_NAME;
exports.OPERATION_AND = _conjunction.OPERATION_ID;
exports.OPERATION_OR = _disjunction.OPERATION_ID;
exports.OPERATION_OR_THEN_VARIABLE = _disjunctionAndVariable.OPERATION_ID;
var TYPE_NUMERIC = exports.TYPE_NUMERIC = 'numeric';
var TYPE_TEXT = exports.TYPE_TEXT = 'text';
var TYPE_DATE = exports.TYPE_DATE = 'date';
/**
* Default types and order for filter conditions.
*
* @type {Object}
*/
var TYPES = exports.TYPES = (_TYPES = {}, _defineProperty(_TYPES, TYPE_NUMERIC, [_none.CONDITION_NAME, _predefinedItems.SEPARATOR, _empty.CONDITION_NAME, _notEmpty.CONDITION_NAME, _predefinedItems.SEPARATOR, _equal.CONDITION_NAME, _notEqual.CONDITION_NAME, _predefinedItems.SEPARATOR, _greaterThan.CONDITION_NAME, _greaterThanOrEqual.CONDITION_NAME, _lessThan.CONDITION_NAME, _lessThanOrEqual.CONDITION_NAME, _between.CONDITION_NAME, _notBetween.CONDITION_NAME]), _defineProperty(_TYPES, TYPE_TEXT, [_none.CONDITION_NAME, _predefinedItems.SEPARATOR, _empty.CONDITION_NAME, _notEmpty.CONDITION_NAME, _predefinedItems.SEPARATOR, _equal.CONDITION_NAME, _notEqual.CONDITION_NAME, _predefinedItems.SEPARATOR, _beginsWith.CONDITION_NAME, _endsWith.CONDITION_NAME, _predefinedItems.SEPARATOR, _contains.CONDITION_NAME, _notContains.CONDITION_NAME]), _defineProperty(_TYPES, TYPE_DATE, [_none.CONDITION_NAME, _predefinedItems.SEPARATOR, _empty.CONDITION_NAME, _notEmpty.CONDITION_NAME, _predefinedItems.SEPARATOR, _equal.CONDITION_NAME, _notEqual.CONDITION_NAME, _predefinedItems.SEPARATOR, _before.CONDITION_NAME, _after.CONDITION_NAME, _between.CONDITION_NAME, _predefinedItems.SEPARATOR, _tomorrow.CONDITION_NAME, _today.CONDITION_NAME, _yesterday.CONDITION_NAME]), _TYPES);
/**
* Get options list for conditional filter by data type (e.q: `'text'`, `'numeric'`, `'date'`).
*
* @returns {Object}
*/
function getOptionsList(type) {
var items = [];
if (!TYPES[type]) {
type = TYPE_TEXT;
}
(0, _array.arrayEach)(TYPES[type], function (type) {
var option = void 0;
if (type === _predefinedItems.SEPARATOR) {
option = { name: _predefinedItems.SEPARATOR };
} else {
option = (0, _object.clone)((0, _conditionRegisterer.getConditionDescriptor)(type));
}
items.push(option);
});
return items;
}
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.SHORT_NAME_FOR_COMPONENT = exports.OPERATION_ID = undefined;
exports.operationResult = operationResult;
var _constants = __webpack_require__(3);
var C = _interopRequireWildcard(_constants);
var _logicalOperationRegisterer = __webpack_require__(64);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var OPERATION_ID = exports.OPERATION_ID = 'conjunction';
var SHORT_NAME_FOR_COMPONENT = exports.SHORT_NAME_FOR_COMPONENT = C.FILTERS_LABELS_CONJUNCTION;
// p AND q AND w AND x AND... === TRUE?
function operationResult(conditions, value) {
return conditions.every(function (condition) {
return condition.func(value);
});
}
(0, _logicalOperationRegisterer.registerOperation)(OPERATION_ID, SHORT_NAME_FOR_COMPONENT, operationResult);
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
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 _element = __webpack_require__(2);
var _object = __webpack_require__(1);
var _constants = __webpack_require__(3);
var C = _interopRequireWildcard(_constants);
var _base = __webpack_require__(65);
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var privatePool = new WeakMap();
/**
* @class InputUI
* @util
*/
var InputUI = function (_BaseUI) {
_inherits(InputUI, _BaseUI);
_createClass(InputUI, null, [{
key: 'DEFAULTS',
get: function get() {
return (0, _object.clone)({
placeholder: '',
type: 'text',
tagName: 'input'
});
}
}]);
function InputUI(hotInstance, options) {
_classCallCheck(this, InputUI);
var _this = _possibleConstructorReturn(this, (InputUI.__proto__ || Object.getPrototypeOf(InputUI)).call(this, hotInstance, (0, _object.extend)(InputUI.DEFAULTS, options)));
privatePool.set(_this, {});
_this.registerHooks();
return _this;
}
/**
* Register all necessary hooks.
*/
_createClass(InputUI, [{
key: 'registerHooks',
value: function registerHooks() {
var _this2 = this;
this.addLocalHook('click', function (event) {
return _this2.onClick(event);
});
this.addLocalHook('keyup', function (event) {
return _this2.onKeyup(event);
});
}
/**
* Build DOM structure.
*/
}, {
key: 'build',
value: function build() {
_get(InputUI.prototype.__proto__ || Object.getPrototypeOf(InputUI.prototype), 'build', this).call(this);
var priv = privatePool.get(this);
var icon = document.createElement('div');
priv.input = this._element.firstChild;
(0, _element.addClass)(this._element, 'htUIInput');
(0, _element.addClass)(icon, 'htUIInputIcon');
this._element.appendChild(icon);
this.update();
}
/**
* Update element.
*/
}, {
key: 'update',
value: function update() {
if (!this.isBuilt()) {
return;
}
var input = privatePool.get(this).input;
input.type = this.options.type;
input.placeholder = this.hot.getTranslatedPhrase(this.options.placeholder);
if (typeof this.options.value === 'string' && this.options.value.startsWith(C.FILTERS_NAMESPACE)) {
input.value = this.hot.getTranslatedPhrase(this.options.value);
} else {
input.value = this.options.value;
}
}
/**
* Focus element.
*/
}, {
key: 'focus',
value: function focus() {
if (this.isBuilt()) {
privatePool.get(this).input.focus();
}
}
/**
* OnClick listener.
*
* @param {Event} event
*/
}, {
key: 'onClick',
value: function onClick(event) {}
/**
* OnKeyup listener.
*
* @param {Event} event
*/
}, {
key: 'onKeyup',
value: function onKeyup(event) {
this.options.value = event.target.value;
}
}]);
return InputUI;
}(_base2.default);
exports.default = InputUI;
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Base class for the Nested Rows' UI sub-classes.
*
* @class
* @util
* @private
*/
var BaseUI = function BaseUI(pluginInstance, hotInstance) {
_classCallCheck(this, BaseUI);
/**
* Instance of Handsontable.
*
* @type {Core}
*/
this.hot = hotInstance;
/**
* Reference to the main plugin instance.
*/
this.plugin = pluginInstance;
};
exports.default = BaseUI;
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var dP = __webpack_require__(22).f;
var create = __webpack_require__(87);
var redefineAll = __webpack_require__(70);
var ctx = __webpack_require__(40);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(73);
var $iterDefine = __webpack_require__(172);
var step = __webpack_require__(174);
var setSpecies = __webpack_require__(175);
var DESCRIPTORS = __webpack_require__(25);
var fastKey = __webpack_require__(42).fastKey;
var validate = __webpack_require__(51);
var SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function (that, key) {
// fast case
var index = fastKey(key);
var 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) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
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);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear() {
for (var that = validate(this, NAME), 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 = validate(this, NAME);
var entry = getEntry(that, key);
if (entry) {
var next = entry.n;
var 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 */) {
validate(this, NAME);
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var 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(validate(this, NAME), key);
}
});
if (DESCRIPTORS) dP(C.prototype, 'size', {
get: function () {
return validate(this, NAME)[SIZE];
}
});
return C;
},
def: function (that, key, value) {
var entry = getEntry(that, key);
var 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
$iterDefine(C, NAME, function (iterated, kind) {
this._t = validate(iterated, NAME); // target
this._k = kind; // kind
this._l = undefined; // previous
}, function () {
var that = this;
var kind = that._k;
var 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
setSpecies(NAME);
}
};
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(25) && !__webpack_require__(26)(function () {
return Object.defineProperty(__webpack_require__(85)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(32);
var toIObject = __webpack_require__(27);
var arrayIndexOf = __webpack_require__(166)(false);
var IE_PROTO = __webpack_require__(89)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(27);
var toLength = __webpack_require__(28);
var toAbsoluteIndex = __webpack_require__(69);
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__(17).document;
module.exports = document && document.documentElement;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(20);
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(57);
var ITERATOR = __webpack_require__(16)('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(171);
var ITERATOR = __webpack_require__(16)('iterator');
var Iterators = __webpack_require__(57);
module.exports = __webpack_require__(50).getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(49);
var TAG = __webpack_require__(16)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(74);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(38);
var hide = __webpack_require__(39);
var has = __webpack_require__(32);
var Iterators = __webpack_require__(57);
var $iterCreate = __webpack_require__(478);
var setToStringTag = __webpack_require__(58);
var getPrototypeOf = __webpack_require__(173);
var ITERATOR = __webpack_require__(16)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = (!BUGGY && $native) || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(32);
var toObject = __webpack_require__(41);
var IE_PROTO = __webpack_require__(89)('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 174 */
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(17);
var dP = __webpack_require__(22);
var DESCRIPTORS = __webpack_require__(25);
var SPECIES = __webpack_require__(16)('species');
module.exports = function (KEY) {
var C = global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(12);
var anObject = __webpack_require__(20);
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = __webpack_require__(40)(Function.call, __webpack_require__(76).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(49);
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(46);
var gOPS = __webpack_require__(78);
var pIE = __webpack_require__(59);
var toObject = __webpack_require__(41);
var IObject = __webpack_require__(88);
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(26)(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var redefineAll = __webpack_require__(70);
var getWeak = __webpack_require__(42).getWeak;
var anObject = __webpack_require__(20);
var isObject = __webpack_require__(12);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(73);
var createArrayMethod = __webpack_require__(77);
var $has = __webpack_require__(32);
var validate = __webpack_require__(51);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (that) {
return that._l || (that._l = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.a = [];
};
var findUncaughtFrozen = function (store, key) {
return arrayFind(store.a, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.a.push([key, value]);
},
'delete': function (key) {
var index = arrayFindIndex(this.a, function (it) {
return it[0] === key;
});
if (~index) this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function (key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function (that, key, value) {
var data = getWeak(anObject(key), true);
if (data === true) uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__(71);
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(16);
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(27);
var gOPN = __webpack_require__(99).f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toInteger = __webpack_require__(68);
var defined = __webpack_require__(47);
module.exports = function repeat(count) {
var str = String(defined(this));
var res = '';
var n = toInteger(count);
if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
return res;
};
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(12);
var cof = __webpack_require__(49);
var MATCH = __webpack_require__(16)('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(12);
var floor = Math.floor;
module.exports = function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(46);
var toIObject = __webpack_require__(27);
var isEnum = __webpack_require__(59).f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) if (isEnum.call(O, key = keys[i++])) {
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(28);
var repeat = __webpack_require__(183);
var defined = __webpack_require__(47);
module.exports = function (that, maxLength, fillString, left) {
var S = String(defined(that));
var stringLength = S.length;
var fillStr = fillString === undefined ? ' ' : String(fillString);
var intMaxLength = toLength(maxLength);
if (intMaxLength <= stringLength || fillStr == '') return S;
var fillLen = intMaxLength - stringLength;
var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(17);
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var privatePool = new WeakMap();
/**
* Calculates indexes of columns to render OR columns that are visible.
* To redo the calculation, you need to create a new calculator.
*
* @class ViewportColumnsCalculator
*/
var ViewportColumnsCalculator = function () {
_createClass(ViewportColumnsCalculator, null, [{
key: 'DEFAULT_WIDTH',
/**
* Default column width
*
* @type {Number}
*/
get: function get() {
return 50;
}
/**
* @param {Number} viewportWidth Width of the viewport
* @param {Number} scrollOffset Current horizontal scroll position of the viewport
* @param {Number} totalColumns Total number of rows
* @param {Function} columnWidthFn Function that returns the width of the column at a given index (in px)
* @param {Function} overrideFn Function that changes calculated this.startRow, this.endRow (used by MergeCells plugin)
* @param {Boolean} onlyFullyVisible if `true`, only startRow and endRow will be indexes of rows that are fully in viewport
* @param {Boolean} stretchH
* @param {Function} [stretchingColumnWidthFn] Function that returns the new width of the stretched column.
*/
}]);
function ViewportColumnsCalculator(viewportWidth, scrollOffset, totalColumns, columnWidthFn, overrideFn, onlyFullyVisible, stretchH) {
var stretchingColumnWidthFn = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : function (width) {
return width;
};
_classCallCheck(this, ViewportColumnsCalculator);
privatePool.set(this, {
viewportWidth: viewportWidth,
scrollOffset: scrollOffset,
totalColumns: totalColumns,
columnWidthFn: columnWidthFn,
overrideFn: overrideFn,
onlyFullyVisible: onlyFullyVisible,
stretchingColumnWidthFn: stretchingColumnWidthFn
});
/**
* Number of rendered/visible columns
*
* @type {Number}
*/
this.count = 0;
/**
* Index of the first rendered/visible column (can be overwritten using overrideFn)
*
* @type {Number|null}
*/
this.startColumn = null;
/**
* Index of the last rendered/visible column (can be overwritten using overrideFn)
*
* @type {null}
*/
this.endColumn = null;
/**
* Position of the first rendered/visible column (in px)
*
* @type {Number|null}
*/
this.startPosition = null;
this.stretchAllRatio = 0;
this.stretchLastWidth = 0;
this.stretch = stretchH;
this.totalTargetWidth = 0;
this.needVerifyLastColumnWidth = true;
this.stretchAllColumnsWidth = [];
this.calculate();
}
/**
* Calculates viewport
*/
_createClass(ViewportColumnsCalculator, [{
key: 'calculate',
value: function calculate() {
var sum = 0;
var needReverse = true;
var startPositions = [];
var columnWidth = void 0;
var priv = privatePool.get(this);
var onlyFullyVisible = priv.onlyFullyVisible;
var overrideFn = priv.overrideFn;
var scrollOffset = priv.scrollOffset;
var totalColumns = priv.totalColumns;
var viewportWidth = priv.viewportWidth;
for (var i = 0; i < totalColumns; i++) {
columnWidth = this._getColumnWidth(i);
if (sum <= scrollOffset && !onlyFullyVisible) {
this.startColumn = i;
}
// +1 pixel for row header width compensation for horizontal scroll > 0
var compensatedViewportWidth = scrollOffset > 0 ? viewportWidth + 1 : viewportWidth;
if (sum >= scrollOffset && sum + columnWidth <= scrollOffset + compensatedViewportWidth) {
if (this.startColumn == null) {
this.startColumn = i;
}
this.endColumn = i;
}
startPositions.push(sum);
sum += columnWidth;
if (!onlyFullyVisible) {
this.endColumn = i;
}
if (sum >= scrollOffset + viewportWidth) {
needReverse = false;
break;
}
}
if (this.endColumn === totalColumns - 1 && needReverse) {
this.startColumn = this.endColumn;
while (this.startColumn > 0) {
var viewportSum = startPositions[this.endColumn] + columnWidth - startPositions[this.startColumn - 1];
if (viewportSum <= viewportWidth || !onlyFullyVisible) {
this.startColumn--;
}
if (viewportSum > viewportWidth) {
break;
}
}
}
if (this.startColumn !== null && overrideFn) {
overrideFn(this);
}
this.startPosition = startPositions[this.startColumn];
if (this.startPosition == void 0) {
this.startPosition = null;
}
if (this.startColumn !== null) {
this.count = this.endColumn - this.startColumn + 1;
}
}
/**
* Recalculate columns stretching.
*
* @param {Number} totalWidth
*/
}, {
key: 'refreshStretching',
value: function refreshStretching(totalWidth) {
if (this.stretch === 'none') {
return;
}
this.totalTargetWidth = totalWidth;
var priv = privatePool.get(this);
var totalColumns = priv.totalColumns;
var sumAll = 0;
for (var i = 0; i < totalColumns; i++) {
var columnWidth = this._getColumnWidth(i);
var permanentColumnWidth = priv.stretchingColumnWidthFn(void 0, i);
if (typeof permanentColumnWidth === 'number') {
totalWidth -= permanentColumnWidth;
} else {
sumAll += columnWidth;
}
}
var remainingSize = totalWidth - sumAll;
if (this.stretch === 'all' && remainingSize > 0) {
this.stretchAllRatio = totalWidth / sumAll;
this.stretchAllColumnsWidth = [];
this.needVerifyLastColumnWidth = true;
} else if (this.stretch === 'last' && totalWidth !== Infinity) {
var _columnWidth = this._getColumnWidth(totalColumns - 1);
var lastColumnWidth = remainingSize + _columnWidth;
this.stretchLastWidth = lastColumnWidth >= 0 ? lastColumnWidth : _columnWidth;
}
}
/**
* Get stretched column width based on stretchH (all or last) setting passed in handsontable instance.
*
* @param {Number} column
* @param {Number} baseWidth
* @returns {Number|null}
*/
}, {
key: 'getStretchedColumnWidth',
value: function getStretchedColumnWidth(column, baseWidth) {
var result = null;
if (this.stretch === 'all' && this.stretchAllRatio !== 0) {
result = this._getStretchedAllColumnWidth(column, baseWidth);
} else if (this.stretch === 'last' && this.stretchLastWidth !== 0) {
result = this._getStretchedLastColumnWidth(column);
}
return result;
}
/**
* @param {Number} column
* @param {Number} baseWidth
* @returns {Number}
* @private
*/
}, {
key: '_getStretchedAllColumnWidth',
value: function _getStretchedAllColumnWidth(column, baseWidth) {
var sumRatioWidth = 0;
var priv = privatePool.get(this);
var totalColumns = priv.totalColumns;
if (!this.stretchAllColumnsWidth[column]) {
var stretchedWidth = Math.round(baseWidth * this.stretchAllRatio);
var newStretchedWidth = priv.stretchingColumnWidthFn(stretchedWidth, column);
if (newStretchedWidth === void 0) {
this.stretchAllColumnsWidth[column] = stretchedWidth;
} else {
this.stretchAllColumnsWidth[column] = isNaN(newStretchedWidth) ? this._getColumnWidth(column) : newStretchedWidth;
}
}
if (this.stretchAllColumnsWidth.length === totalColumns && this.needVerifyLastColumnWidth) {
this.needVerifyLastColumnWidth = false;
for (var i = 0; i < this.stretchAllColumnsWidth.length; i++) {
sumRatioWidth += this.stretchAllColumnsWidth[i];
}
if (sumRatioWidth !== this.totalTargetWidth) {
this.stretchAllColumnsWidth[this.stretchAllColumnsWidth.length - 1] += this.totalTargetWidth - sumRatioWidth;
}
}
return this.stretchAllColumnsWidth[column];
}
/**
* @param {Number} column
* @returns {Number|null}
* @private
*/
}, {
key: '_getStretchedLastColumnWidth',
value: function _getStretchedLastColumnWidth(column) {
var priv = privatePool.get(this);
var totalColumns = priv.totalColumns;
if (column === totalColumns - 1) {
return this.stretchLastWidth;
}
return null;
}
/**
* @param {Number} column Column index.
* @returns {Number}
* @private
*/
}, {
key: '_getColumnWidth',
value: function _getColumnWidth(column) {
var width = privatePool.get(this).columnWidthFn(column);
if (width === void 0) {
width = ViewportColumnsCalculator.DEFAULT_WIDTH;
}
return width;
}
}]);
return ViewportColumnsCalculator;
}();
exports.default = ViewportColumnsCalculator;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var privatePool = new WeakMap();
/**
* Calculates indexes of rows to render OR rows that are visible.
* To redo the calculation, you need to create a new calculator.
*
* @class ViewportRowsCalculator
*/
var ViewportRowsCalculator = function () {
_createClass(ViewportRowsCalculator, null, [{
key: "DEFAULT_HEIGHT",
/**
* Default row height
*
* @type {Number}
*/
get: function get() {
return 23;
}
/**
* @param {Number} viewportHeight Height of the viewport
* @param {Number} scrollOffset Current vertical scroll position of the viewport
* @param {Number} totalRows Total number of rows
* @param {Function} rowHeightFn Function that returns the height of the row at a given index (in px)
* @param {Function} overrideFn Function that changes calculated this.startRow, this.endRow (used by MergeCells plugin)
* @param {Boolean} onlyFullyVisible if `true`, only startRow and endRow will be indexes of rows that are fully in viewport
* @param {Number} horizontalScrollbarHeight
*/
}]);
function ViewportRowsCalculator(viewportHeight, scrollOffset, totalRows, rowHeightFn, overrideFn, onlyFullyVisible, horizontalScrollbarHeight) {
_classCallCheck(this, ViewportRowsCalculator);
privatePool.set(this, {
viewportHeight: viewportHeight,
scrollOffset: scrollOffset,
totalRows: totalRows,
rowHeightFn: rowHeightFn,
overrideFn: overrideFn,
onlyFullyVisible: onlyFullyVisible,
horizontalScrollbarHeight: horizontalScrollbarHeight
});
/**
* Number of rendered/visible rows
*
* @type {Number}
*/
this.count = 0;
/**
* Index of the first rendered/visible row (can be overwritten using overrideFn)
*
* @type {Number|null}
*/
this.startRow = null;
/**
* Index of the last rendered/visible row (can be overwritten using overrideFn)
*
* @type {null}
*/
this.endRow = null;
/**
* Position of the first rendered/visible row (in px)
*
* @type {Number|null}
*/
this.startPosition = null;
this.calculate();
}
/**
* Calculates viewport
*/
_createClass(ViewportRowsCalculator, [{
key: "calculate",
value: function calculate() {
var sum = 0;
var needReverse = true;
var startPositions = [];
var priv = privatePool.get(this);
var onlyFullyVisible = priv.onlyFullyVisible;
var overrideFn = priv.overrideFn;
var rowHeightFn = priv.rowHeightFn;
var scrollOffset = priv.scrollOffset;
var totalRows = priv.totalRows;
var viewportHeight = priv.viewportHeight;
var horizontalScrollbarHeight = priv.horizontalScrollbarHeight || 0;
var rowHeight = void 0;
// Calculate the number (start and end index) of rows needed
for (var i = 0; i < totalRows; i++) {
rowHeight = rowHeightFn(i);
if (rowHeight === undefined) {
rowHeight = ViewportRowsCalculator.DEFAULT_HEIGHT;
}
if (sum <= scrollOffset && !onlyFullyVisible) {
this.startRow = i;
}
// the row is within the "visible range"
if (sum >= scrollOffset && sum + rowHeight <= scrollOffset + viewportHeight - horizontalScrollbarHeight) {
if (this.startRow === null) {
this.startRow = i;
}
this.endRow = i;
}
startPositions.push(sum);
sum += rowHeight;
if (!onlyFullyVisible) {
this.endRow = i;
}
if (sum >= scrollOffset + viewportHeight - horizontalScrollbarHeight) {
needReverse = false;
break;
}
}
// If the estimation has reached the last row and there is still some space available in the viewport,
// we need to render in reverse in order to fill the whole viewport with rows
if (this.endRow === totalRows - 1 && needReverse) {
this.startRow = this.endRow;
while (this.startRow > 0) {
// rowHeight is the height of the last row
var viewportSum = startPositions[this.endRow] + rowHeight - startPositions[this.startRow - 1];
if (viewportSum <= viewportHeight - horizontalScrollbarHeight || !onlyFullyVisible) {
this.startRow--;
}
if (viewportSum >= viewportHeight - horizontalScrollbarHeight) {
break;
}
}
}
if (this.startRow !== null && overrideFn) {
overrideFn(this);
}
this.startPosition = startPositions[this.startRow];
if (this.startPosition == void 0) {
this.startPosition = null;
}
if (this.startRow !== null) {
this.count = this.endRow - this.startRow + 1;
}
}
}]);
return ViewportRowsCalculator;
}();
exports.default = ViewportRowsCalculator;
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class ColumnFilter
*/
var ColumnFilter = function () {
/**
* @param {Number} offset
* @param {Number} total
* @param {Number} countTH
*/
function ColumnFilter(offset, total, countTH) {
_classCallCheck(this, ColumnFilter);
this.offset = offset;
this.total = total;
this.countTH = countTH;
}
/**
* @param index
* @returns {Number}
*/
_createClass(ColumnFilter, [{
key: "offsetted",
value: function offsetted(index) {
return index + this.offset;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "unOffsetted",
value: function unOffsetted(index) {
return index - this.offset;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "renderedToSource",
value: function renderedToSource(index) {
return this.offsetted(index);
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "sourceToRendered",
value: function sourceToRendered(index) {
return this.unOffsetted(index);
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "offsettedTH",
value: function offsettedTH(index) {
return index - this.countTH;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "unOffsettedTH",
value: function unOffsettedTH(index) {
return index + this.countTH;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "visibleRowHeadedColumnToSourceColumn",
value: function visibleRowHeadedColumnToSourceColumn(index) {
return this.renderedToSource(this.offsettedTH(index));
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "sourceColumnToVisibleRowHeadedColumn",
value: function sourceColumnToVisibleRowHeadedColumn(index) {
return this.unOffsettedTH(this.sourceToRendered(index));
}
}]);
return ColumnFilter;
}();
exports.default = ColumnFilter;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class RowFilter
*/
var RowFilter = function () {
/**
* @param {Number} offset
* @param {Number} total
* @param {Number} countTH
*/
function RowFilter(offset, total, countTH) {
_classCallCheck(this, RowFilter);
this.offset = offset;
this.total = total;
this.countTH = countTH;
}
/**
* @param index
* @returns {Number}
*/
_createClass(RowFilter, [{
key: "offsetted",
value: function offsetted(index) {
return index + this.offset;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "unOffsetted",
value: function unOffsetted(index) {
return index - this.offset;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "renderedToSource",
value: function renderedToSource(index) {
return this.offsetted(index);
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "sourceToRendered",
value: function sourceToRendered(index) {
return this.unOffsetted(index);
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "offsettedTH",
value: function offsettedTH(index) {
return index - this.countTH;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "unOffsettedTH",
value: function unOffsettedTH(index) {
return index + this.countTH;
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "visibleColHeadedRowToSourceRow",
value: function visibleColHeadedRowToSourceRow(index) {
return this.renderedToSource(this.offsettedTH(index));
}
/**
* @param index
* @returns {Number}
*/
}, {
key: "sourceRowToVisibleColHeadedRow",
value: function sourceRowToVisibleColHeadedRow(index) {
return this.unOffsettedTH(this.sourceToRendered(index));
}
}]);
return RowFilter;
}();
exports.default = RowFilter;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _object = __webpack_require__(1);
var _string = __webpack_require__(31);
var _event = __webpack_require__(314);
var _event2 = _interopRequireDefault(_event);
var _overlays = __webpack_require__(315);
var _overlays2 = _interopRequireDefault(_overlays);
var _scroll = __webpack_require__(316);
var _scroll2 = _interopRequireDefault(_scroll);
var _settings = __webpack_require__(317);
var _settings2 = _interopRequireDefault(_settings);
var _table = __webpack_require__(318);
var _table2 = _interopRequireDefault(_table);
var _viewport = __webpack_require__(320);
var _viewport2 = _interopRequireDefault(_viewport);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Walkontable
*/
var Walkontable = function () {
/**
* @param {Object} settings
*/
function Walkontable(settings) {
_classCallCheck(this, Walkontable);
var originalHeaders = [];
// this is the namespace for global events
this.guid = 'wt_' + (0, _string.randomString)();
// bootstrap from settings
if (settings.cloneSource) {
this.cloneSource = settings.cloneSource;
this.cloneOverlay = settings.cloneOverlay;
this.wtSettings = settings.cloneSource.wtSettings;
this.wtTable = new _table2.default(this, settings.table, settings.wtRootElement);
this.wtScroll = new _scroll2.default(this);
this.wtViewport = settings.cloneSource.wtViewport;
this.wtEvent = new _event2.default(this);
this.selections = this.cloneSource.selections;
} else {
this.wtSettings = new _settings2.default(this, settings);
this.wtTable = new _table2.default(this, settings.table);
this.wtScroll = new _scroll2.default(this);
this.wtViewport = new _viewport2.default(this);
this.wtEvent = new _event2.default(this);
this.selections = this.getSetting('selections');
this.wtOverlays = new _overlays2.default(this);
this.exportSettingsAsClassNames();
}
// find original headers
if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
}
if (!this.getSetting('columnHeaders').length) {
this.update('columnHeaders', [function (column, TH) {
(0, _element.fastInnerText)(TH, originalHeaders[column]);
}]);
}
}
this.drawn = false;
this.drawInterrupted = false;
}
/**
* Force rerender of Walkontable
*
* @param {Boolean} [fastDraw=false] When `true`, try to refresh only the positions of borders without rerendering
* the data. It will only work if Table.draw() does not force
* rendering anyway
* @returns {Walkontable}
*/
_createClass(Walkontable, [{
key: 'draw',
value: function draw() {
var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
this.drawInterrupted = false;
if (!fastDraw && !(0, _element.isVisible)(this.wtTable.TABLE)) {
// draw interrupted because TABLE is not visible
this.drawInterrupted = true;
} else {
this.wtTable.draw(fastDraw);
}
return this;
}
/**
* Returns the TD at coords. If topmost is set to true, returns TD from the topmost overlay layer,
* if not set or set to false, returns TD from the master table.
*
* @param {CellCoords} coords
* @param {Boolean} [topmost=false]
* @returns {Object}
*/
}, {
key: 'getCell',
value: function getCell(coords) {
var topmost = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!topmost) {
return this.wtTable.getCell(coords);
}
var totalRows = this.wtSettings.getSetting('totalRows');
var fixedRowsTop = this.wtSettings.getSetting('fixedRowsTop');
var fixedRowsBottom = this.wtSettings.getSetting('fixedRowsBottom');
var fixedColumns = this.wtSettings.getSetting('fixedColumnsLeft');
if (coords.row < fixedRowsTop && coords.col < fixedColumns) {
return this.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell(coords);
} else if (coords.row < fixedRowsTop) {
return this.wtOverlays.topOverlay.clone.wtTable.getCell(coords);
} else if (coords.col < fixedColumns && coords.row >= totalRows - fixedRowsBottom) {
if (this.wtOverlays.bottomLeftCornerOverlay && this.wtOverlays.bottomLeftCornerOverlay.clone) {
return this.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.getCell(coords);
}
} else if (coords.col < fixedColumns) {
return this.wtOverlays.leftOverlay.clone.wtTable.getCell(coords);
} else if (coords.row < totalRows && coords.row > totalRows - fixedRowsBottom) {
if (this.wtOverlays.bottomOverlay && this.wtOverlays.bottomOverlay.clone) {
return this.wtOverlays.bottomOverlay.clone.wtTable.getCell(coords);
}
}
return this.wtTable.getCell(coords);
}
/**
* @param {Object} settings
* @param {*} value
* @returns {Walkontable}
*/
}, {
key: 'update',
value: function update(settings, value) {
return this.wtSettings.update(settings, value);
}
/**
* Scroll the viewport to a row at the given index in the data source
*
* @param {Number} row
* @returns {Walkontable}
*/
}, {
key: 'scrollVertical',
value: function scrollVertical(row) {
this.wtOverlays.topOverlay.scrollTo(row);
this.getSetting('onScrollVertically');
return this;
}
/**
* Scroll the viewport to a column at the given index in the data source
*
* @param {Number} column
* @returns {Walkontable}
*/
}, {
key: 'scrollHorizontal',
value: function scrollHorizontal(column) {
this.wtOverlays.leftOverlay.scrollTo(column);
this.getSetting('onScrollHorizontally');
return this;
}
/**
* Scrolls the viewport to a cell (rerenders if needed)
*
* @param {CellCoords} coords
* @returns {Walkontable}
*/
}, {
key: 'scrollViewport',
value: function scrollViewport(coords) {
this.wtScroll.scrollViewport(coords);
return this;
}
/**
* @returns {Array}
*/
}, {
key: 'getViewport',
value: function getViewport() {
return [this.wtTable.getFirstVisibleRow(), this.wtTable.getFirstVisibleColumn(), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn()];
}
/**
* Get overlay name
*
* @returns {String}
*/
}, {
key: 'getOverlayName',
value: function getOverlayName() {
return this.cloneOverlay ? this.cloneOverlay.type : 'master';
}
/**
* Check overlay type of this Walkontable instance.
*
* @param {String} name Clone type @see {Overlay.CLONE_TYPES}.
* @returns {Boolean}
*/
}, {
key: 'isOverlayName',
value: function isOverlayName(name) {
if (this.cloneOverlay) {
return this.cloneOverlay.type === name;
}
return false;
}
/**
* Export settings as class names added to the parent element of the table.
*/
}, {
key: 'exportSettingsAsClassNames',
value: function exportSettingsAsClassNames() {
var _this = this;
var toExport = {
rowHeaders: ['array'],
columnHeaders: ['array']
};
var allClassNames = [];
var newClassNames = [];
(0, _object.objectEach)(toExport, function (optionType, key) {
if (optionType.indexOf('array') > -1 && _this.getSetting(key).length) {
newClassNames.push('ht' + (0, _string.toUpperCaseFirst)(key));
}
allClassNames.push('ht' + (0, _string.toUpperCaseFirst)(key));
});
(0, _element.removeClass)(this.wtTable.wtRootElement.parentNode, allClassNames);
(0, _element.addClass)(this.wtTable.wtRootElement.parentNode, newClassNames);
}
/**
* Get/Set Walkontable instance setting
*
* @param {String} key
* @param {*} [param1]
* @param {*} [param2]
* @param {*} [param3]
* @param {*} [param4]
* @returns {*}
*/
}, {
key: 'getSetting',
value: function getSetting(key, param1, param2, param3, param4) {
// this is faster than .apply - https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
return this.wtSettings.getSetting(key, param1, param2, param3, param4);
}
/**
* Checks if setting exists
*
* @param {String} key
* @returns {Boolean}
*/
}, {
key: 'hasSetting',
value: function hasSetting(key) {
return this.wtSettings.has(key);
}
/**
* Destroy instance
*/
}, {
key: 'destroy',
value: function destroy() {
this.wtOverlays.destroy();
this.wtEvent.destroy();
}
}]);
return Walkontable;
}();
exports.default = Walkontable;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 195 */
/***/ (function(module, exports) {
/***/ }),
/* 196 */
/***/ (function(module, exports) {
/***/ }),
/* 197 */
/***/ (function(module, exports) {
/***/ }),
/* 198 */
/***/ (function(module, exports) {
/***/ }),
/* 199 */
/***/ (function(module, exports) {
/***/ }),
/* 200 */
/***/ (function(module, exports) {
/***/ }),
/* 201 */
/***/ (function(module, exports) {
/***/ }),
/* 202 */
/***/ (function(module, exports) {
/***/ }),
/* 203 */
/***/ (function(module, exports) {
/***/ }),
/* 204 */
/***/ (function(module, exports) {
/***/ }),
/* 205 */
/***/ (function(module, exports) {
/***/ }),
/* 206 */
/***/ (function(module, exports) {
/***/ }),
/* 207 */
/***/ (function(module, exports) {
/***/ }),
/* 208 */
/***/ (function(module, exports) {
/***/ }),
/* 209 */
/***/ (function(module, exports) {
/***/ }),
/* 210 */
/***/ (function(module, exports) {
/***/ }),
/* 211 */
/***/ (function(module, exports) {
/***/ }),
/* 212 */
/***/ (function(module, exports) {
/***/ }),
/* 213 */
/***/ (function(module, exports) {
/***/ }),
/* 214 */
/***/ (function(module, exports) {
/***/ }),
/* 215 */
/***/ (function(module, exports) {
/***/ }),
/* 216 */
/***/ (function(module, exports) {
/***/ }),
/* 217 */
/***/ (function(module, exports) {
/***/ }),
/* 218 */
/***/ (function(module, exports) {
/***/ }),
/* 219 */
/***/ (function(module, exports) {
/***/ }),
/* 220 */
/***/ (function(module, exports) {
/***/ }),
/* 221 */
/***/ (function(module, exports) {
/***/ }),
/* 222 */
/***/ (function(module, exports) {
/***/ }),
/* 223 */
/***/ (function(module, exports) {
/***/ }),
/* 224 */
/***/ (function(module, exports) {
/***/ }),
/* 225 */
/***/ (function(module, exports) {
/***/ }),
/* 226 */
/***/ (function(module, exports) {
/***/ }),
/* 227 */
/***/ (function(module, exports) {
/***/ }),
/* 228 */
/***/ (function(module, exports) {
/***/ }),
/* 229 */
/***/ (function(module, exports) {
/***/ }),
/* 230 */
/***/ (function(module, exports) {
/***/ }),
/* 231 */
/***/ (function(module, exports) {
/***/ }),
/* 232 */
/***/ (function(module, exports) {
/***/ }),
/* 233 */
/***/ (function(module, exports) {
/***/ }),
/* 234 */
/***/ (function(module, exports) {
/***/ }),
/* 235 */
/***/ (function(module, exports) {
/***/ }),
/* 236 */
/***/ (function(module, exports) {
/***/ }),
/* 237 */
/***/ (function(module, exports) {
/***/ }),
/* 238 */
/***/ (function(module, exports) {
/***/ }),
/* 239 */
/***/ (function(module, exports) {
/***/ }),
/* 240 */
/***/ (function(module, exports) {
/***/ }),
/* 241 */
/***/ (function(module, exports) {
/***/ }),
/* 242 */
/***/ (function(module, exports) {
/***/ }),
/* 243 */
/***/ (function(module, exports) {
/***/ }),
/* 244 */
/***/ (function(module, exports) {
/***/ }),
/* 245 */
/***/ (function(module, exports) {
/***/ }),
/* 246 */
/***/ (function(module, exports) {
/***/ }),
/* 247 */
/***/ (function(module, exports) {
/***/ }),
/* 248 */
/***/ (function(module, exports) {
/***/ }),
/* 249 */
/***/ (function(module, exports) {
/***/ }),
/* 250 */
/***/ (function(module, exports) {
/***/ }),
/* 251 */
/***/ (function(module, exports) {
/***/ }),
/* 252 */
/***/ (function(module, exports) {
/***/ }),
/* 253 */
/***/ (function(module, exports) {
/***/ }),
/* 254 */
/***/ (function(module, exports) {
/***/ }),
/* 255 */
/***/ (function(module, exports) {
/***/ }),
/* 256 */
/***/ (function(module, exports) {
/***/ }),
/* 257 */
/***/ (function(module, exports) {
/***/ }),
/* 258 */
/***/ (function(module, exports) {
/***/ }),
/* 259 */
/***/ (function(module, exports) {
/***/ }),
/* 260 */
/***/ (function(module, exports) {
/***/ }),
/* 261 */
/***/ (function(module, exports) {
/***/ }),
/* 262 */
/***/ (function(module, exports) {
/***/ }),
/* 263 */
/***/ (function(module, exports) {
/***/ }),
/* 264 */
/***/ (function(module, exports) {
/***/ }),
/* 265 */
/***/ (function(module, exports) {
/***/ }),
/* 266 */
/***/ (function(module, exports) {
/***/ }),
/* 267 */
/***/ (function(module, exports) {
/***/ }),
/* 268 */
/***/ (function(module, exports) {
/***/ }),
/* 269 */
/***/ (function(module, exports) {
/***/ }),
/* 270 */
/***/ (function(module, exports) {
/***/ }),
/* 271 */
/***/ (function(module, exports) {
/***/ }),
/* 272 */
/***/ (function(module, exports) {
/***/ }),
/* 273 */
/***/ (function(module, exports) {
/***/ }),
/* 274 */
/***/ (function(module, exports) {
/***/ }),
/* 275 */
/***/ (function(module, exports) {
/***/ }),
/* 276 */
/***/ (function(module, exports) {
/***/ }),
/* 277 */
/***/ (function(module, exports) {
/***/ }),
/* 278 */
/***/ (function(module, exports) {
/***/ }),
/* 279 */
/***/ (function(module, exports) {
/***/ }),
/* 280 */
/***/ (function(module, exports) {
/***/ }),
/* 281 */
/***/ (function(module, exports) {
/***/ }),
/* 282 */
/***/ (function(module, exports) {
/***/ }),
/* 283 */
/***/ (function(module, exports) {
/***/ }),
/* 284 */
/***/ (function(module, exports) {
/***/ }),
/* 285 */
/***/ (function(module, exports) {
/***/ }),
/* 286 */
/***/ (function(module, exports) {
/***/ }),
/* 287 */
/***/ (function(module, exports) {
/***/ }),
/* 288 */
/***/ (function(module, exports) {
/***/ }),
/* 289 */
/***/ (function(module, exports) {
/***/ }),
/* 290 */
/***/ (function(module, exports) {
/***/ }),
/* 291 */
/***/ (function(module, exports) {
/***/ }),
/* 292 */
/***/ (function(module, exports) {
/***/ }),
/* 293 */
/***/ (function(module, exports) {
/***/ }),
/* 294 */
/***/ (function(module, exports) {
/***/ }),
/* 295 */
/***/ (function(module, exports) {
/***/ }),
/* 296 */
/***/ (function(module, exports) {
/***/ }),
/* 297 */
/***/ (function(module, exports) {
/***/ }),
/* 298 */
/***/ (function(module, exports) {
/***/ }),
/* 299 */
/***/ (function(module, exports) {
/***/ }),
/* 300 */
/***/ (function(module, exports) {
/***/ }),
/* 301 */
/***/ (function(module, exports) {
/***/ }),
/* 302 */
/***/ (function(module, exports) {
/***/ }),
/* 303 */
/***/ (function(module, exports) {
/***/ }),
/* 304 */
/***/ (function(module, exports) {
/***/ }),
/* 305 */
/***/ (function(module, exports) {
/***/ }),
/* 306 */
/***/ (function(module, exports) {
/***/ }),
/* 307 */
/***/ (function(module, exports) {
/***/ }),
/* 308 */
/***/ (function(module, exports) {
/***/ }),
/* 309 */
/***/ (function(module, exports) {
/***/ }),
/* 310 */
/***/ (function(module, exports) {
/***/ }),
/* 311 */
/***/ (function(module, exports) {
/***/ }),
/* 312 */
/***/ (function(module, exports) {
/***/ }),
/* 313 */
/***/ (function(module, exports) {
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _element = __webpack_require__(2);
var _function = __webpack_require__(35);
var _browser = __webpack_require__(33);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
*
*/
function Event(instance) {
var that = this;
var eventManager = new _eventManager2.default(instance);
this.instance = instance;
var dblClickOrigin = [null, null];
this.dblClickTimeout = [null, null];
var onMouseDown = function onMouseDown(event) {
var activeElement = document.activeElement;
var getParentNode = (0, _function.partial)(_element.getParent, event.realTarget);
var realTarget = event.realTarget;
// ignore focusable element from mouse down processing (https://github.com/handsontable/handsontable/issues/3555)
if (realTarget === activeElement || getParentNode(0) === activeElement || getParentNode(1) === activeElement) {
return;
}
var cell = that.parentCell(realTarget);
if ((0, _element.hasClass)(realTarget, 'corner')) {
that.instance.getSetting('onCellCornerMouseDown', event, realTarget);
} else if (cell.TD) {
if (that.instance.hasSetting('onCellMouseDown')) {
that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD, that.instance);
}
}
if (event.button !== 2) {
// if not right mouse button
if (cell.TD) {
dblClickOrigin[0] = cell.TD;
clearTimeout(that.dblClickTimeout[0]);
that.dblClickTimeout[0] = setTimeout(function () {
dblClickOrigin[0] = null;
}, 1000);
}
}
};
var onTouchMove = function onTouchMove(event) {
that.instance.touchMoving = true;
};
var longTouchTimeout;
var onTouchStart = function onTouchStart(event) {
var container = this;
eventManager.addEventListener(this, 'touchmove', onTouchMove);
// Prevent cell selection when scrolling with touch event - not the best solution performance-wise
that.checkIfTouchMove = setTimeout(function () {
if (that.instance.touchMoving === true) {
that.instance.touchMoving = void 0;
eventManager.removeEventListener('touchmove', onTouchMove, false);
}
onMouseDown(event);
}, 30);
};
var onMouseOver = function onMouseOver(event) {
var table, td, mainWOT;
if (that.instance.hasSetting('onCellMouseOver')) {
table = that.instance.wtTable.TABLE;
td = (0, _element.closestDown)(event.realTarget, ['TD', 'TH'], table);
mainWOT = that.instance.cloneSource || that.instance;
if (td && td !== mainWOT.lastMouseOver && (0, _element.isChildOf)(td, table)) {
mainWOT.lastMouseOver = td;
that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(td), td, that.instance);
}
}
};
var onMouseOut = function onMouseOut(event) {
var table = void 0;
var lastTD = void 0;
var nextTD = void 0;
if (that.instance.hasSetting('onCellMouseOut')) {
table = that.instance.wtTable.TABLE;
lastTD = (0, _element.closestDown)(event.realTarget, ['TD', 'TH'], table);
nextTD = (0, _element.closestDown)(event.relatedTarget, ['TD', 'TH'], table);
if (lastTD && lastTD !== nextTD && (0, _element.isChildOf)(lastTD, table)) {
that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(lastTD), lastTD, that.instance);
}
}
};
var onMouseUp = function onMouseUp(event) {
if (event.button !== 2) {
// if not right mouse button
var cell = that.parentCell(event.realTarget);
if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
if ((0, _element.hasClass)(event.realTarget, 'corner')) {
that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD, that.instance);
} else {
that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD, that.instance);
}
dblClickOrigin[0] = null;
dblClickOrigin[1] = null;
} else if (cell.TD === dblClickOrigin[0]) {
that.instance.getSetting('onCellMouseUp', event, cell.coords, cell.TD, that.instance);
dblClickOrigin[1] = cell.TD;
clearTimeout(that.dblClickTimeout[1]);
that.dblClickTimeout[1] = setTimeout(function () {
dblClickOrigin[1] = null;
}, 500);
} else if (cell.TD && that.instance.hasSetting('onCellMouseUp')) {
that.instance.getSetting('onCellMouseUp', event, cell.coords, cell.TD, that.instance);
}
}
};
var onTouchEnd = function onTouchEnd(event) {
clearTimeout(longTouchTimeout);
// that.instance.longTouch == void 0;
event.preventDefault();
onMouseUp(event);
// eventManager.removeEventListener(that.instance.wtTable.holder, "mouseup", onMouseUp);
};
eventManager.addEventListener(this.instance.wtTable.holder, 'mousedown', onMouseDown);
eventManager.addEventListener(this.instance.wtTable.TABLE, 'mouseover', onMouseOver);
eventManager.addEventListener(this.instance.wtTable.TABLE, 'mouseout', onMouseOut);
eventManager.addEventListener(this.instance.wtTable.holder, 'mouseup', onMouseUp);
// check if full HOT instance, or detached WOT AND run on mobile device
if (this.instance.wtTable.holder.parentNode.parentNode && (0, _browser.isMobileBrowser)() && !that.instance.wtTable.isWorkingOnClone()) {
var classSelector = '.' + this.instance.wtTable.holder.parentNode.className.split(' ').join('.');
eventManager.addEventListener(this.instance.wtTable.holder, 'touchstart', function (event) {
that.instance.touchApplied = true;
if ((0, _element.isChildOf)(event.target, classSelector)) {
onTouchStart.call(event.target, event);
}
});
eventManager.addEventListener(this.instance.wtTable.holder, 'touchend', function (event) {
that.instance.touchApplied = false;
if ((0, _element.isChildOf)(event.target, classSelector)) {
onTouchEnd.call(event.target, event);
}
});
if (!that.instance.momentumScrolling) {
that.instance.momentumScrolling = {};
}
eventManager.addEventListener(this.instance.wtTable.holder, 'scroll', function (event) {
clearTimeout(that.instance.momentumScrolling._timeout);
if (!that.instance.momentumScrolling.ongoing) {
that.instance.getSetting('onBeforeTouchScroll');
}
that.instance.momentumScrolling.ongoing = true;
that.instance.momentumScrolling._timeout = setTimeout(function () {
if (!that.instance.touchApplied) {
that.instance.momentumScrolling.ongoing = false;
that.instance.getSetting('onAfterMomentumScroll');
}
}, 200);
});
}
eventManager.addEventListener(window, 'resize', function () {
if (that.instance.getSetting('stretchH') !== 'none') {
that.instance.draw();
}
});
this.destroy = function () {
clearTimeout(this.dblClickTimeout[0]);
clearTimeout(this.dblClickTimeout[1]);
eventManager.destroy();
};
}
Event.prototype.parentCell = function (elem) {
var cell = {};
var TABLE = this.instance.wtTable.TABLE;
var TD = (0, _element.closestDown)(elem, ['TD', 'TH'], TABLE);
if (TD) {
cell.coords = this.instance.wtTable.getCoords(TD);
cell.TD = TD;
} else if ((0, _element.hasClass)(elem, 'wtBorder') && (0, _element.hasClass)(elem, 'current')) {
cell.coords = this.instance.selections.getCell().cellRange.highlight;
cell.TD = this.instance.wtTable.getCell(cell.coords);
} else if ((0, _element.hasClass)(elem, 'wtBorder') && (0, _element.hasClass)(elem, 'area')) {
if (this.instance.selections.createOrGetArea().cellRange) {
cell.coords = this.instance.selections.createOrGetArea().cellRange.to;
cell.TD = this.instance.wtTable.getCell(cell.coords);
}
}
return cell;
};
exports.default = Event;
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _array = __webpack_require__(0);
var _unicode = __webpack_require__(18);
var _browser = __webpack_require__(33);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _base = __webpack_require__(30);
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Overlays
*/
var Overlays = function () {
/**
* @param {Walkontable} wotInstance
*/
function Overlays(wotInstance) {
_classCallCheck(this, Overlays);
this.wot = wotInstance;
// legacy support
this.instance = this.wot;
this.eventManager = new _eventManager2.default(this.wot);
this.wot.update('scrollbarWidth', (0, _element.getScrollbarWidth)());
this.wot.update('scrollbarHeight', (0, _element.getScrollbarWidth)());
this.scrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
this.prepareOverlays();
this.destroyed = false;
this.keyPressed = false;
this.spreaderLastSize = {
width: null,
height: null
};
this.overlayScrollPositions = {
master: {
top: 0,
left: 0
},
top: {
top: null,
left: 0
},
bottom: {
top: null,
left: 0
},
left: {
top: 0,
left: null
}
};
this.pendingScrollCallbacks = {
master: {
top: 0,
left: 0
},
top: {
left: 0
},
bottom: {
left: 0
},
left: {
top: 0
}
};
this.verticalScrolling = false;
this.horizontalScrolling = false;
this.delegatedScrollCallback = false;
this.registeredListeners = [];
this.registerListeners();
}
/**
* Prepare overlays based on user settings.
*
* @returns {Boolean} Returns `true` if changes applied to overlay needs scroll synchronization.
*/
_createClass(Overlays, [{
key: 'prepareOverlays',
value: function prepareOverlays() {
var syncScroll = false;
if (this.topOverlay) {
syncScroll = this.topOverlay.updateStateOfRendering() || syncScroll;
} else {
this.topOverlay = _base2.default.createOverlay(_base2.default.CLONE_TOP, this.wot);
}
if (!_base2.default.hasOverlay(_base2.default.CLONE_BOTTOM)) {
this.bottomOverlay = {
needFullRender: false,
updateStateOfRendering: function updateStateOfRendering() {
return false;
}
};
}
if (!_base2.default.hasOverlay(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
this.bottomLeftCornerOverlay = {
needFullRender: false,
updateStateOfRendering: function updateStateOfRendering() {
return false;
}
};
}
if (this.bottomOverlay) {
syncScroll = this.bottomOverlay.updateStateOfRendering() || syncScroll;
} else {
this.bottomOverlay = _base2.default.createOverlay(_base2.default.CLONE_BOTTOM, this.wot);
}
if (this.leftOverlay) {
syncScroll = this.leftOverlay.updateStateOfRendering() || syncScroll;
} else {
this.leftOverlay = _base2.default.createOverlay(_base2.default.CLONE_LEFT, this.wot);
}
if (this.topOverlay.needFullRender && this.leftOverlay.needFullRender) {
if (this.topLeftCornerOverlay) {
syncScroll = this.topLeftCornerOverlay.updateStateOfRendering() || syncScroll;
} else {
this.topLeftCornerOverlay = _base2.default.createOverlay(_base2.default.CLONE_TOP_LEFT_CORNER, this.wot);
}
}
if (this.bottomOverlay.needFullRender && this.leftOverlay.needFullRender) {
if (this.bottomLeftCornerOverlay) {
syncScroll = this.bottomLeftCornerOverlay.updateStateOfRendering() || syncScroll;
} else {
this.bottomLeftCornerOverlay = _base2.default.createOverlay(_base2.default.CLONE_BOTTOM_LEFT_CORNER, this.wot);
}
}
if (this.wot.getSetting('debug') && !this.debug) {
this.debug = _base2.default.createOverlay(_base2.default.CLONE_DEBUG, this.wot);
}
return syncScroll;
}
/**
* Refresh and redraw table
*/
}, {
key: 'refreshAll',
value: function refreshAll() {
if (!this.wot.drawn) {
return;
}
if (!this.wot.wtTable.holder.parentNode) {
// Walkontable was detached from DOM, but this handler was not removed
this.destroy();
return;
}
this.wot.draw(true);
if (this.verticalScrolling) {
this.leftOverlay.onScroll();
}
if (this.horizontalScrolling) {
this.topOverlay.onScroll();
}
this.verticalScrolling = false;
this.horizontalScrolling = false;
}
/**
* Register all necessary event listeners.
*/
}, {
key: 'registerListeners',
value: function registerListeners() {
var _this = this;
var topOverlayScrollable = this.topOverlay.mainTableScrollableElement;
var leftOverlayScrollable = this.leftOverlay.mainTableScrollableElement;
var listenersToRegister = [];
listenersToRegister.push([document.documentElement, 'keydown', function (event) {
return _this.onKeyDown(event);
}]);
listenersToRegister.push([document.documentElement, 'keyup', function () {
return _this.onKeyUp();
}]);
listenersToRegister.push([document, 'visibilitychange', function () {
return _this.onKeyUp();
}]);
listenersToRegister.push([topOverlayScrollable, 'scroll', function (event) {
return _this.onTableScroll(event);
}]);
if (topOverlayScrollable !== leftOverlayScrollable) {
listenersToRegister.push([leftOverlayScrollable, 'scroll', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.topOverlay.needFullRender) {
listenersToRegister.push([this.topOverlay.clone.wtTable.holder, 'scroll', function (event) {
return _this.onTableScroll(event);
}]);
listenersToRegister.push([this.topOverlay.clone.wtTable.holder, 'wheel', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.bottomOverlay.needFullRender) {
listenersToRegister.push([this.bottomOverlay.clone.wtTable.holder, 'scroll', function (event) {
return _this.onTableScroll(event);
}]);
listenersToRegister.push([this.bottomOverlay.clone.wtTable.holder, 'wheel', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.leftOverlay.needFullRender) {
listenersToRegister.push([this.leftOverlay.clone.wtTable.holder, 'scroll', function (event) {
return _this.onTableScroll(event);
}]);
listenersToRegister.push([this.leftOverlay.clone.wtTable.holder, 'wheel', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.topLeftCornerOverlay && this.topLeftCornerOverlay.needFullRender) {
listenersToRegister.push([this.topLeftCornerOverlay.clone.wtTable.holder, 'wheel', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.needFullRender) {
listenersToRegister.push([this.bottomLeftCornerOverlay.clone.wtTable.holder, 'wheel', function (event) {
return _this.onTableScroll(event);
}]);
}
if (this.topOverlay.trimmingContainer !== window && this.leftOverlay.trimmingContainer !== window) {
// This is necessary?
// eventManager.addEventListener(window, 'scroll', (event) => this.refreshAll(event));
listenersToRegister.push([window, 'wheel', function (event) {
var overlay = void 0;
var deltaY = event.wheelDeltaY || event.deltaY;
var deltaX = event.wheelDeltaX || event.deltaX;
if (_this.topOverlay.clone.wtTable.holder.contains(event.realTarget)) {
overlay = 'top';
} else if (_this.bottomOverlay.clone && _this.bottomOverlay.clone.wtTable.holder.contains(event.realTarget)) {
overlay = 'bottom';
} else if (_this.leftOverlay.clone.wtTable.holder.contains(event.realTarget)) {
overlay = 'left';
} else if (_this.topLeftCornerOverlay && _this.topLeftCornerOverlay.clone && _this.topLeftCornerOverlay.clone.wtTable.holder.contains(event.realTarget)) {
overlay = 'topLeft';
} else if (_this.bottomLeftCornerOverlay && _this.bottomLeftCornerOverlay.clone && _this.bottomLeftCornerOverlay.clone.wtTable.holder.contains(event.realTarget)) {
overlay = 'bottomLeft';
}
if (overlay == 'top' && deltaY !== 0 || overlay == 'left' && deltaX !== 0 || overlay == 'bottom' && deltaY !== 0 || (overlay === 'topLeft' || overlay === 'bottomLeft') && (deltaY !== 0 || deltaX !== 0)) {
event.preventDefault();
}
}]);
}
while (listenersToRegister.length) {
var listener = listenersToRegister.pop();
this.eventManager.addEventListener(listener[0], listener[1], listener[2]);
this.registeredListeners.push(listener);
}
}
/**
* Deregister all previously registered listeners.
*/
}, {
key: 'deregisterListeners',
value: function deregisterListeners() {
while (this.registeredListeners.length) {
var listener = this.registeredListeners.pop();
this.eventManager.removeEventListener(listener[0], listener[1], listener[2]);
}
}
/**
* Scroll listener
*
* @param {Event} event
*/
}, {
key: 'onTableScroll',
value: function onTableScroll(event) {
// There was if statement which controlled flow of this function. It avoided the execution of the next lines
// on mobile devices. It was changed. Broader description of this case is included within issue #4856.
var masterHorizontal = this.leftOverlay.mainTableScrollableElement;
var masterVertical = this.topOverlay.mainTableScrollableElement;
var target = event.target;
// For key press, sync only master -> overlay position because while pressing Walkontable.render is triggered
// by hot.refreshBorder
if (this.keyPressed) {
if (masterVertical !== window && target !== window && !event.target.contains(masterVertical) || masterHorizontal !== window && target !== window && !event.target.contains(masterHorizontal)) {
return;
}
}
if (event.type === 'scroll') {
this.syncScrollPositions(event);
} else {
this.translateMouseWheelToScroll(event);
}
}
/**
* Key down listener
*/
}, {
key: 'onKeyDown',
value: function onKeyDown(event) {
this.keyPressed = (0, _unicode.isKey)(event.keyCode, 'ARROW_UP|ARROW_RIGHT|ARROW_DOWN|ARROW_LEFT');
}
/**
* Key up listener
*/
}, {
key: 'onKeyUp',
value: function onKeyUp() {
this.keyPressed = false;
}
/**
* Translate wheel event into scroll event and sync scroll overlays position
*
* @private
* @param {Event} event
* @returns {Boolean}
*/
}, {
key: 'translateMouseWheelToScroll',
value: function translateMouseWheelToScroll(event) {
var topOverlay = this.topOverlay.clone.wtTable.holder;
var bottomOverlay = this.bottomOverlay.clone ? this.bottomOverlay.clone.wtTable.holder : null;
var leftOverlay = this.leftOverlay.clone.wtTable.holder;
var topLeftCornerOverlay = this.topLeftCornerOverlay && this.topLeftCornerOverlay.clone ? this.topLeftCornerOverlay.clone.wtTable.holder : null;
var bottomLeftCornerOverlay = this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone ? this.bottomLeftCornerOverlay.clone.wtTable.holder : null;
var mouseWheelSpeedRatio = -0.2;
var deltaY = event.wheelDeltaY || -1 * event.deltaY;
var deltaX = event.wheelDeltaX || -1 * event.deltaX;
var parentHolder = null;
var eventMockup = { type: 'wheel' };
var tempElem = event.target;
var delta = null;
// Fix for extremely slow header scrolling with a mousewheel on Firefox
if (event.deltaMode === 1) {
deltaY *= 120;
deltaX *= 120;
}
while (tempElem != document && tempElem != null) {
if (tempElem.className.indexOf('wtHolder') > -1) {
parentHolder = tempElem;
break;
}
tempElem = tempElem.parentNode;
}
eventMockup.target = parentHolder;
if (parentHolder === topLeftCornerOverlay || parentHolder === bottomLeftCornerOverlay) {
this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * deltaX, 'x');
this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * deltaY, 'y');
} else {
if (parentHolder === topOverlay || parentHolder === bottomOverlay) {
delta = deltaY;
} else if (parentHolder === leftOverlay) {
delta = deltaX;
}
this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * delta);
}
return false;
}
/**
* Synchronize scroll position between master table and overlay table.
*
* @private
* @param {Event|Object} event
* @param {Number} [fakeScrollValue=null]
* @param {String} [fakeScrollDirection=null] `x` or `y`.
*/
}, {
key: 'syncScrollPositions',
value: function syncScrollPositions(event) {
var fakeScrollValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var fakeScrollDirection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (this.destroyed) {
return;
}
if (arguments.length === 0) {
this.syncScrollWithMaster();
return;
}
var masterHorizontal = this.leftOverlay.mainTableScrollableElement;
var masterVertical = this.topOverlay.mainTableScrollableElement;
var target = event.target;
var tempScrollValue = 0;
var scrollValueChanged = false;
var topOverlay = void 0;
var leftOverlay = void 0;
var topLeftCornerOverlay = void 0;
var bottomLeftCornerOverlay = void 0;
var bottomOverlay = void 0;
var delegatedScroll = false;
var preventOverflow = this.wot.getSetting('preventOverflow');
if (this.topOverlay.needFullRender) {
topOverlay = this.topOverlay.clone.wtTable.holder;
}
if (this.bottomOverlay.needFullRender) {
bottomOverlay = this.bottomOverlay.clone.wtTable.holder;
}
if (this.leftOverlay.needFullRender) {
leftOverlay = this.leftOverlay.clone.wtTable.holder;
}
if (this.leftOverlay.needFullRender && this.topOverlay.needFullRender) {
topLeftCornerOverlay = this.topLeftCornerOverlay.clone.wtTable.holder;
}
if (this.leftOverlay.needFullRender && this.bottomOverlay.needFullRender) {
bottomLeftCornerOverlay = this.bottomLeftCornerOverlay.clone.wtTable.holder;
}
if (target === document) {
target = window;
}
if (target === masterHorizontal || target === masterVertical) {
if (preventOverflow) {
tempScrollValue = (0, _element.getScrollLeft)(this.scrollableElement);
} else {
tempScrollValue = (0, _element.getScrollLeft)(target);
}
// if scrolling the master table - populate the scroll values to both top and left overlays
this.horizontalScrolling = this.overlayScrollPositions.master.left !== tempScrollValue;
this.overlayScrollPositions.master.left = tempScrollValue;
scrollValueChanged = true;
if (this.pendingScrollCallbacks.master.left > 0) {
this.pendingScrollCallbacks.master.left--;
} else {
if (topOverlay && topOverlay.scrollLeft !== tempScrollValue) {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.top.left++;
}
topOverlay.scrollLeft = tempScrollValue;
delegatedScroll = masterHorizontal !== window;
}
if (bottomOverlay && bottomOverlay.scrollLeft !== tempScrollValue) {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.bottom.left++;
}
bottomOverlay.scrollLeft = tempScrollValue;
delegatedScroll = masterHorizontal !== window;
}
}
tempScrollValue = (0, _element.getScrollTop)(target);
this.verticalScrolling = this.overlayScrollPositions.master.top !== tempScrollValue;
this.overlayScrollPositions.master.top = tempScrollValue;
scrollValueChanged = true;
if (this.pendingScrollCallbacks.master.top > 0) {
this.pendingScrollCallbacks.master.top--;
} else if (leftOverlay && leftOverlay.scrollTop !== tempScrollValue) {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.left.top++;
}
leftOverlay.scrollTop = tempScrollValue;
delegatedScroll = masterVertical !== window;
}
} else if (target === bottomOverlay) {
tempScrollValue = (0, _element.getScrollLeft)(target);
// if scrolling the bottom overlay - populate the horizontal scroll to the master table
this.overlayScrollPositions.bottom.left = tempScrollValue;
scrollValueChanged = true;
if (this.pendingScrollCallbacks.bottom.left > 0) {
this.pendingScrollCallbacks.bottom.left--;
} else {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.master.left++;
}
masterHorizontal.scrollLeft = tempScrollValue;
if (topOverlay && topOverlay.scrollLeft !== tempScrollValue) {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.top.left++;
}
topOverlay.scrollLeft = tempScrollValue;
delegatedScroll = masterVertical !== window;
}
}
// "fake" scroll value calculated from the mousewheel event
if (fakeScrollValue !== null) {
scrollValueChanged = true;
masterVertical.scrollTop += fakeScrollValue;
}
} else if (target === topOverlay) {
tempScrollValue = (0, _element.getScrollLeft)(target);
// if scrolling the top overlay - populate the horizontal scroll to the master table
this.overlayScrollPositions.top.left = tempScrollValue;
scrollValueChanged = true;
if (this.pendingScrollCallbacks.top.left > 0) {
this.pendingScrollCallbacks.top.left--;
} else {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.master.left++;
}
masterHorizontal.scrollLeft = tempScrollValue;
}
// "fake" scroll value calculated from the mousewheel event
if (fakeScrollValue !== null) {
scrollValueChanged = true;
masterVertical.scrollTop += fakeScrollValue;
}
if (bottomOverlay && bottomOverlay.scrollLeft !== tempScrollValue) {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.bottom.left++;
}
bottomOverlay.scrollLeft = tempScrollValue;
delegatedScroll = masterVertical !== window;
}
} else if (target === leftOverlay) {
tempScrollValue = (0, _element.getScrollTop)(target);
// if scrolling the left overlay - populate the vertical scroll to the master table
if (this.overlayScrollPositions.left.top !== tempScrollValue) {
this.overlayScrollPositions.left.top = tempScrollValue;
scrollValueChanged = true;
if (this.pendingScrollCallbacks.left.top > 0) {
this.pendingScrollCallbacks.left.top--;
} else {
if (fakeScrollValue == null) {
this.pendingScrollCallbacks.master.top++;
}
masterVertical.scrollTop = tempScrollValue;
}
}
// "fake" scroll value calculated from the mousewheel event
if (fakeScrollValue !== null) {
scrollValueChanged = true;
masterVertical.scrollLeft += fakeScrollValue;
}
} else if (target === topLeftCornerOverlay || target === bottomLeftCornerOverlay) {
if (fakeScrollValue !== null) {
scrollValueChanged = true;
if (fakeScrollDirection === 'x') {
masterVertical.scrollLeft += fakeScrollValue;
} else if (fakeScrollDirection === 'y') {
masterVertical.scrollTop += fakeScrollValue;
}
}
}
if (!this.keyPressed && scrollValueChanged && event.type === 'scroll') {
if (this.delegatedScrollCallback) {
this.delegatedScrollCallback = false;
} else {
this.refreshAll();
}
if (delegatedScroll) {
this.delegatedScrollCallback = true;
}
}
}
/**
* Synchronize overlay scrollbars with the master scrollbar
*/
}, {
key: 'syncScrollWithMaster',
value: function syncScrollWithMaster() {
var master = this.topOverlay.mainTableScrollableElement;
var scrollLeft = master.scrollLeft,
scrollTop = master.scrollTop;
if (this.topOverlay.needFullRender) {
this.topOverlay.clone.wtTable.holder.scrollLeft = scrollLeft;
}
if (this.bottomOverlay.needFullRender) {
this.bottomOverlay.clone.wtTable.holder.scrollLeft = scrollLeft;
}
if (this.leftOverlay.needFullRender) {
this.leftOverlay.clone.wtTable.holder.scrollTop = scrollTop;
}
}
/**
* Update the main scrollable elements for all the overlays.
*/
}, {
key: 'updateMainScrollableElements',
value: function updateMainScrollableElements() {
this.deregisterListeners();
this.leftOverlay.updateMainScrollableElement();
this.topOverlay.updateMainScrollableElement();
if (this.bottomOverlay.needFullRender) {
this.bottomOverlay.updateMainScrollableElement();
}
this.scrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
this.registerListeners();
}
/**
*
*/
}, {
key: 'destroy',
value: function destroy() {
this.eventManager.destroy();
this.topOverlay.destroy();
if (this.bottomOverlay.clone) {
this.bottomOverlay.destroy();
}
this.leftOverlay.destroy();
if (this.topLeftCornerOverlay) {
this.topLeftCornerOverlay.destroy();
}
if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone) {
this.bottomLeftCornerOverlay.destroy();
}
if (this.debug) {
this.debug.destroy();
}
this.destroyed = true;
}
/**
* @param {Boolean} [fastDraw=false]
*/
}, {
key: 'refresh',
value: function refresh() {
var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (this.topOverlay.areElementSizesAdjusted && this.leftOverlay.areElementSizesAdjusted) {
var container = this.wot.wtTable.wtRootElement.parentNode || this.wot.wtTable.wtRootElement;
var width = container.clientWidth;
var height = container.clientHeight;
if (width !== this.spreaderLastSize.width || height !== this.spreaderLastSize.height) {
this.spreaderLastSize.width = width;
this.spreaderLastSize.height = height;
this.adjustElementsSize();
}
}
if (this.bottomOverlay.clone) {
this.bottomOverlay.refresh(fastDraw);
}
this.leftOverlay.refresh(fastDraw);
this.topOverlay.refresh(fastDraw);
if (this.topLeftCornerOverlay) {
this.topLeftCornerOverlay.refresh(fastDraw);
}
if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone) {
this.bottomLeftCornerOverlay.refresh(fastDraw);
}
if (this.debug) {
this.debug.refresh(fastDraw);
}
}
/**
* Adjust overlays elements size and master table size
*
* @param {Boolean} [force=false]
*/
}, {
key: 'adjustElementsSize',
value: function adjustElementsSize() {
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var totalColumns = this.wot.getSetting('totalColumns');
var totalRows = this.wot.getSetting('totalRows');
var headerRowSize = this.wot.wtViewport.getRowHeaderWidth();
var headerColumnSize = this.wot.wtViewport.getColumnHeaderHeight();
var hiderStyle = this.wot.wtTable.hider.style;
hiderStyle.width = headerRowSize + this.leftOverlay.sumCellSizes(0, totalColumns) + 'px';
hiderStyle.height = headerColumnSize + this.topOverlay.sumCellSizes(0, totalRows) + 1 + 'px';
this.topOverlay.adjustElementsSize(force);
this.leftOverlay.adjustElementsSize(force);
if (this.bottomOverlay.clone) {
this.bottomOverlay.adjustElementsSize(force);
}
}
/**
*
*/
}, {
key: 'applyToDOM',
value: function applyToDOM() {
if (!this.topOverlay.areElementSizesAdjusted || !this.leftOverlay.areElementSizesAdjusted) {
this.adjustElementsSize();
}
this.topOverlay.applyToDOM();
if (this.bottomOverlay.clone) {
this.bottomOverlay.applyToDOM();
}
this.leftOverlay.applyToDOM();
}
/**
* Get the parent overlay of the provided element.
*
* @param {HTMLElement} element
* @returns {Object|null}
*/
}, {
key: 'getParentOverlay',
value: function getParentOverlay(element) {
if (!element) {
return null;
}
var overlays = [this.topOverlay, this.leftOverlay, this.bottomOverlay, this.topLeftCornerOverlay, this.bottomLeftCornerOverlay];
var result = null;
(0, _array.arrayEach)(overlays, function (elem, i) {
if (!elem) {
return;
}
if (elem.clone && elem.clone.wtTable.TABLE.contains(element)) {
result = elem.clone;
}
});
return result;
}
}]);
return Overlays;
}();
exports.default = Overlays;
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _number = __webpack_require__(4);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Scroll
*/
var Scroll = function () {
/**
* @param {Walkontable} wotInstance
*/
function Scroll(wotInstance) {
_classCallCheck(this, Scroll);
this.wot = wotInstance;
// legacy support
this.instance = wotInstance;
}
/**
* Scrolls viewport to a cell by minimum number of cells
*
* @param {CellCoords} coords
*/
_createClass(Scroll, [{
key: 'scrollViewport',
value: function scrollViewport(coords) {
if (!this.wot.drawn) {
return;
}
var _getVariables2 = this._getVariables(),
topOverlay = _getVariables2.topOverlay,
leftOverlay = _getVariables2.leftOverlay,
totalRows = _getVariables2.totalRows,
totalColumns = _getVariables2.totalColumns,
fixedRowsTop = _getVariables2.fixedRowsTop,
fixedRowsBottom = _getVariables2.fixedRowsBottom,
fixedColumnsLeft = _getVariables2.fixedColumnsLeft;
if (coords.row < 0 || coords.row > Math.max(totalRows - 1, 0)) {
throw new Error('row ' + coords.row + ' does not exist');
}
if (coords.col < 0 || coords.col > Math.max(totalColumns - 1, 0)) {
throw new Error('column ' + coords.col + ' does not exist');
}
if (coords.row >= fixedRowsTop && coords.row < this.getFirstVisibleRow()) {
topOverlay.scrollTo(coords.row);
} else if (coords.row > this.getLastVisibleRow() && coords.row < totalRows - fixedRowsBottom) {
topOverlay.scrollTo(coords.row, true);
}
if (coords.col >= fixedColumnsLeft && coords.col < this.getFirstVisibleColumn()) {
leftOverlay.scrollTo(coords.col);
} else if (coords.col > this.getLastVisibleColumn()) {
leftOverlay.scrollTo(coords.col, true);
}
}
/**
* Get first visible row based on virtual dom and how table is visible in browser window viewport.
*
* @returns {Number}
*/
}, {
key: 'getFirstVisibleRow',
value: function getFirstVisibleRow() {
var _getVariables3 = this._getVariables(),
topOverlay = _getVariables3.topOverlay,
wtTable = _getVariables3.wtTable,
wtViewport = _getVariables3.wtViewport,
totalRows = _getVariables3.totalRows,
fixedRowsTop = _getVariables3.fixedRowsTop;
var firstVisibleRow = wtTable.getFirstVisibleRow();
if (topOverlay.mainTableScrollableElement === window) {
var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
var totalTableHeight = (0, _element.innerHeight)(wtTable.hider);
var windowHeight = (0, _element.innerHeight)(window);
var windowScrollTop = (0, _element.getScrollTop)(window);
// Only calculate firstVisibleRow when table didn't filled (from up) whole viewport space
if (rootElementOffset.top + totalTableHeight - windowHeight <= windowScrollTop) {
var rowsHeight = wtViewport.getColumnHeaderHeight();
rowsHeight += topOverlay.sumCellSizes(0, fixedRowsTop);
(0, _number.rangeEachReverse)(totalRows, 1, function (row) {
rowsHeight += topOverlay.sumCellSizes(row - 1, row);
if (rootElementOffset.top + totalTableHeight - rowsHeight <= windowScrollTop) {
// Return physical row + 1
firstVisibleRow = row;
return false;
}
});
}
}
return firstVisibleRow;
}
/**
* Get last visible row based on virtual dom and how table is visible in browser window viewport.
*
* @returns {Number}
*/
}, {
key: 'getLastVisibleRow',
value: function getLastVisibleRow() {
var _getVariables4 = this._getVariables(),
topOverlay = _getVariables4.topOverlay,
wtTable = _getVariables4.wtTable,
wtViewport = _getVariables4.wtViewport,
totalRows = _getVariables4.totalRows;
var lastVisibleRow = wtTable.getLastVisibleRow();
if (topOverlay.mainTableScrollableElement === window) {
var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
var windowHeight = (0, _element.innerHeight)(window);
var windowScrollTop = (0, _element.getScrollTop)(window);
// Only calculate lastVisibleRow when table didn't filled (from bottom) whole viewport space
if (rootElementOffset.top > windowScrollTop) {
var rowsHeight = wtViewport.getColumnHeaderHeight();
(0, _number.rangeEach)(1, totalRows, function (row) {
rowsHeight += topOverlay.sumCellSizes(row - 1, row);
if (rootElementOffset.top + rowsHeight - windowScrollTop >= windowHeight) {
// Return physical row - 1 (-2 because rangeEach gives row index + 1 - sumCellSizes requirements)
lastVisibleRow = row - 2;
return false;
}
});
}
}
return lastVisibleRow;
}
/**
* Get first visible column based on virtual dom and how table is visible in browser window viewport.
*
* @returns {Number}
*/
}, {
key: 'getFirstVisibleColumn',
value: function getFirstVisibleColumn() {
var _getVariables5 = this._getVariables(),
leftOverlay = _getVariables5.leftOverlay,
wtTable = _getVariables5.wtTable,
wtViewport = _getVariables5.wtViewport,
totalColumns = _getVariables5.totalColumns,
fixedColumnsLeft = _getVariables5.fixedColumnsLeft;
var firstVisibleColumn = wtTable.getFirstVisibleColumn();
if (leftOverlay.mainTableScrollableElement === window) {
var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
var totalTableWidth = (0, _element.innerWidth)(wtTable.hider);
var windowWidth = (0, _element.innerWidth)(window);
var windowScrollLeft = (0, _element.getScrollLeft)(window);
// Only calculate firstVisibleColumn when table didn't filled (from left) whole viewport space
if (rootElementOffset.left + totalTableWidth - windowWidth <= windowScrollLeft) {
var columnsWidth = wtViewport.getRowHeaderWidth();
(0, _number.rangeEachReverse)(totalColumns, 1, function (column) {
columnsWidth += leftOverlay.sumCellSizes(column - 1, column);
if (rootElementOffset.left + totalTableWidth - columnsWidth <= windowScrollLeft) {
// Return physical column + 1
firstVisibleColumn = column;
return false;
}
});
}
}
return firstVisibleColumn;
}
/**
* Get last visible column based on virtual dom and how table is visible in browser window viewport.
*
* @returns {Number}
*/
}, {
key: 'getLastVisibleColumn',
value: function getLastVisibleColumn() {
var _getVariables6 = this._getVariables(),
leftOverlay = _getVariables6.leftOverlay,
wtTable = _getVariables6.wtTable,
wtViewport = _getVariables6.wtViewport,
totalColumns = _getVariables6.totalColumns;
var lastVisibleColumn = wtTable.getLastVisibleColumn();
if (leftOverlay.mainTableScrollableElement === window) {
var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
var windowWidth = (0, _element.innerWidth)(window);
var windowScrollLeft = (0, _element.getScrollLeft)(window);
// Only calculate lastVisibleColumn when table didn't filled (from right) whole viewport space
if (rootElementOffset.left > windowScrollLeft) {
var columnsWidth = wtViewport.getRowHeaderWidth();
(0, _number.rangeEach)(1, totalColumns, function (column) {
columnsWidth += leftOverlay.sumCellSizes(column - 1, column);
if (rootElementOffset.left + columnsWidth - windowScrollLeft >= windowWidth) {
// Return physical column - 1 (-2 because rangeEach gives column index + 1 - sumCellSizes requirements)
lastVisibleColumn = column - 2;
return false;
}
});
}
}
return lastVisibleColumn;
}
/**
* Returns collection of variables used to rows and columns visibility calculations.
*
* @returns {Object}
* @private
*/
}, {
key: '_getVariables',
value: function _getVariables() {
var wot = this.wot;
var topOverlay = wot.wtOverlays.topOverlay;
var leftOverlay = wot.wtOverlays.leftOverlay;
var wtTable = wot.wtTable;
var wtViewport = wot.wtViewport;
var totalRows = wot.getSetting('totalRows');
var totalColumns = wot.getSetting('totalColumns');
var fixedRowsTop = wot.getSetting('fixedRowsTop');
var fixedRowsBottom = wot.getSetting('fixedRowsBottom');
var fixedColumnsLeft = wot.getSetting('fixedColumnsLeft');
return {
topOverlay: topOverlay,
leftOverlay: leftOverlay,
wtTable: wtTable,
wtViewport: wtViewport,
totalRows: totalRows,
totalColumns: totalColumns,
fixedRowsTop: fixedRowsTop,
fixedRowsBottom: fixedRowsBottom,
fixedColumnsLeft: fixedColumnsLeft
};
}
}]);
return Scroll;
}();
exports.default = Scroll;
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _object = __webpack_require__(1);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Settings
*/
var Settings = function () {
/**
* @param {Walkontable} wotInstance
* @param {Object} settings
*/
function Settings(wotInstance, settings) {
var _this = this;
_classCallCheck(this, Settings);
this.wot = wotInstance;
// legacy support
this.instance = wotInstance;
// default settings. void 0 means it is required, null means it can be empty
this.defaults = {
table: void 0,
debug: false, // shows WalkontableDebugOverlay
// presentation mode
externalRowCalculator: false,
stretchH: 'none', // values: all, last, none
currentRowClassName: null,
currentColumnClassName: null,
preventOverflow: function preventOverflow() {
return false;
},
// data source
data: void 0,
freezeOverlays: false,
fixedColumnsLeft: 0,
fixedRowsTop: 0,
fixedRowsBottom: 0,
minSpareRows: 0,
// this must be array of functions: [function (row, TH) {}]
rowHeaders: function rowHeaders() {
return [];
},
// this must be array of functions: [function (column, TH) {}]
columnHeaders: function columnHeaders() {
return [];
},
totalRows: void 0,
totalColumns: void 0,
cellRenderer: function cellRenderer(row, column, TD) {
var cellData = _this.getSetting('data', row, column);
(0, _element.fastInnerText)(TD, cellData === void 0 || cellData === null ? '' : cellData);
},
// columnWidth: 50,
columnWidth: function columnWidth(col) {
// return undefined means use default size for the rendered cell content
},
rowHeight: function rowHeight(row) {
// return undefined means use default size for the rendered cell content
},
defaultRowHeight: 23,
defaultColumnWidth: 50,
selections: null,
hideBorderOnMouseDownOver: false,
viewportRowCalculatorOverride: null,
viewportColumnCalculatorOverride: null,
// callbacks
onCellMouseDown: null,
onCellMouseOver: null,
onCellMouseOut: null,
onCellMouseUp: null,
// onCellMouseOut: null,
onCellDblClick: null,
onCellCornerMouseDown: null,
onCellCornerDblClick: null,
beforeDraw: null,
onDraw: null,
onBeforeDrawBorders: null,
onScrollVertically: null,
onScrollHorizontally: null,
onBeforeTouchScroll: null,
onAfterMomentumScroll: null,
onBeforeStretchingColumnWidth: function onBeforeStretchingColumnWidth(width) {
return width;
},
onModifyRowHeaderWidth: null,
onModifyGetCellCoords: null,
// constants
scrollbarWidth: 10,
scrollbarHeight: 10,
renderAllRows: false,
groups: false,
rowHeaderWidth: null,
columnHeaderHeight: null,
headerClassName: null
};
// reference to settings
this.settings = {};
for (var i in this.defaults) {
if ((0, _object.hasOwnProperty)(this.defaults, i)) {
if (settings[i] !== void 0) {
this.settings[i] = settings[i];
} else if (this.defaults[i] === void 0) {
throw new Error('A required setting "' + i + '" was not provided');
} else {
this.settings[i] = this.defaults[i];
}
}
}
}
/**
* Update settings
*
* @param {Object} settings
* @param {*} value
* @returns {Walkontable}
*/
_createClass(Settings, [{
key: 'update',
value: function update(settings, value) {
if (value === void 0) {
// settings is object
for (var i in settings) {
if ((0, _object.hasOwnProperty)(settings, i)) {
this.settings[i] = settings[i];
}
}
} else {
// if value is defined then settings is the key
this.settings[settings] = value;
}
return this.wot;
}
/**
* Get setting by name
*
* @param {String} key
* @param {*} param1
* @param {*} param2
* @param {*} param3
* @param {*} param4
* @returns {*}
*/
}, {
key: 'getSetting',
value: function getSetting(key, param1, param2, param3, param4) {
if (typeof this.settings[key] === 'function') {
// this is faster than .apply - https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
return this.settings[key](param1, param2, param3, param4);
} else if (param1 !== void 0 && Array.isArray(this.settings[key])) {
// perhaps this can be removed, it is only used in tests
return this.settings[key][param1];
}
return this.settings[key];
}
/**
* Checks if setting exists
*
* @param {Boolean} key
* @returns {Boolean}
*/
}, {
key: 'has',
value: function has(key) {
return !!this.settings[key];
}
}]);
return Settings;
}();
exports.default = Settings;
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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 _element = __webpack_require__(2);
var _function = __webpack_require__(35);
var _coords = __webpack_require__(61);
var _coords2 = _interopRequireDefault(_coords);
var _range = __webpack_require__(150);
var _range2 = _interopRequireDefault(_range);
var _column = __webpack_require__(191);
var _column2 = _interopRequireDefault(_column);
var _row = __webpack_require__(192);
var _row2 = _interopRequireDefault(_row);
var _tableRenderer = __webpack_require__(319);
var _tableRenderer2 = _interopRequireDefault(_tableRenderer);
var _base = __webpack_require__(30);
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(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); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
*
*/
var Table = function () {
/**
* @param {Walkontable} wotInstance
* @param {HTMLTableElement} table
*/
function Table(wotInstance, table) {
var _this = this;
_classCallCheck(this, Table);
this.wot = wotInstance;
// legacy support
this.instance = this.wot;
this.TABLE = table;
this.TBODY = null;
this.THEAD = null;
this.COLGROUP = null;
this.tableOffset = 0;
this.holderOffset = 0;
(0, _element.removeTextNodes)(this.TABLE);
this.spreader = this.createSpreader(this.TABLE);
this.hider = this.createHider(this.spreader);
this.holder = this.createHolder(this.hider);
this.wtRootElement = this.holder.parentNode;
this.alignOverlaysWithTrimmingContainer();
this.fixTableDomTree();
this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
this.tbodyChildrenLength = this.TBODY.childNodes.length;
this.rowFilter = null;
this.columnFilter = null;
this.correctHeaderWidth = false;
var origRowHeaderWidth = this.wot.wtSettings.settings.rowHeaderWidth;
// Fix for jumping row headers (https://github.com/handsontable/handsontable/issues/3850)
this.wot.wtSettings.settings.rowHeaderWidth = function () {
return _this._modifyRowHeaderWidth(origRowHeaderWidth);
};
}
/**
*
*/
_createClass(Table, [{
key: 'fixTableDomTree',
value: function fixTableDomTree() {
this.TBODY = this.TABLE.querySelector('tbody');
if (!this.TBODY) {
this.TBODY = document.createElement('tbody');
this.TABLE.appendChild(this.TBODY);
}
this.THEAD = this.TABLE.querySelector('thead');
if (!this.THEAD) {
this.THEAD = document.createElement('thead');
this.TABLE.insertBefore(this.THEAD, this.TBODY);
}
this.COLGROUP = this.TABLE.querySelector('colgroup');
if (!this.COLGROUP) {
this.COLGROUP = document.createElement('colgroup');
this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
}
if (this.wot.getSetting('columnHeaders').length && !this.THEAD.childNodes.length) {
this.THEAD.appendChild(document.createElement('TR'));
}
}
/**
* @param table
* @returns {HTMLElement}
*/
}, {
key: 'createSpreader',
value: function createSpreader(table) {
var parent = table.parentNode;
var spreader = void 0;
if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
spreader = document.createElement('div');
spreader.className = 'wtSpreader';
if (parent) {
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
parent.insertBefore(spreader, table);
}
spreader.appendChild(table);
}
spreader.style.position = 'relative';
return spreader;
}
/**
* @param spreader
* @returns {HTMLElement}
*/
}, {
key: 'createHider',
value: function createHider(spreader) {
var parent = spreader.parentNode;
var hider = void 0;
if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
hider = document.createElement('div');
hider.className = 'wtHider';
if (parent) {
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
parent.insertBefore(hider, spreader);
}
hider.appendChild(spreader);
}
return hider;
}
/**
*
* @param hider
* @returns {HTMLElement}
*/
}, {
key: 'createHolder',
value: function createHolder(hider) {
var parent = hider.parentNode;
var holder = void 0;
if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
holder = document.createElement('div');
holder.style.position = 'relative';
holder.className = 'wtHolder';
if (parent) {
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
parent.insertBefore(holder, hider);
}
if (!this.isWorkingOnClone()) {
holder.parentNode.className += 'ht_master handsontable';
}
holder.appendChild(hider);
}
return holder;
}
}, {
key: 'alignOverlaysWithTrimmingContainer',
value: function alignOverlaysWithTrimmingContainer() {
var trimmingElement = (0, _element.getTrimmingContainer)(this.wtRootElement);
if (!this.isWorkingOnClone()) {
this.holder.parentNode.style.position = 'relative';
if (trimmingElement === window) {
var preventOverflow = this.wot.getSetting('preventOverflow');
if (!preventOverflow) {
this.holder.style.overflow = 'visible';
this.wtRootElement.style.overflow = 'visible';
}
} else {
this.holder.style.width = (0, _element.getStyle)(trimmingElement, 'width');
this.holder.style.height = (0, _element.getStyle)(trimmingElement, 'height');
this.holder.style.overflow = '';
}
}
}
}, {
key: 'isWorkingOnClone',
value: function isWorkingOnClone() {
return !!this.wot.cloneSource;
}
/**
* Redraws the table
*
* @param {Boolean} fastDraw If TRUE, will try to avoid full redraw and only update the border positions. If FALSE or UNDEFINED, will perform a full redraw
* @returns {Table}
*/
}, {
key: 'draw',
value: function draw(fastDraw) {
var _wot = this.wot,
wtOverlays = _wot.wtOverlays,
wtViewport = _wot.wtViewport;
var totalRows = this.instance.getSetting('totalRows');
var rowHeaders = this.wot.getSetting('rowHeaders').length;
var columnHeaders = this.wot.getSetting('columnHeaders').length;
var syncScroll = false;
if (!this.isWorkingOnClone()) {
this.holderOffset = (0, _element.offset)(this.holder);
fastDraw = wtViewport.createRenderCalculators(fastDraw);
if (rowHeaders && !this.wot.getSetting('fixedColumnsLeft')) {
var leftScrollPos = wtOverlays.leftOverlay.getScrollPosition();
var previousState = this.correctHeaderWidth;
this.correctHeaderWidth = leftScrollPos > 0;
if (previousState !== this.correctHeaderWidth) {
fastDraw = false;
}
}
}
if (!this.isWorkingOnClone()) {
syncScroll = wtOverlays.prepareOverlays();
}
if (fastDraw) {
if (!this.isWorkingOnClone()) {
// in case we only scrolled without redraw, update visible rows information in oldRowsCalculator
wtViewport.createVisibleCalculators();
}
if (wtOverlays) {
wtOverlays.refresh(true);
}
} else {
if (this.isWorkingOnClone()) {
this.tableOffset = this.wot.cloneSource.wtTable.tableOffset;
} else {
this.tableOffset = (0, _element.offset)(this.TABLE);
}
var startRow = void 0;
if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_DEBUG) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP_LEFT_CORNER)) {
startRow = 0;
} else if (_base2.default.isOverlayTypeOf(this.instance.cloneOverlay, _base2.default.CLONE_BOTTOM) || _base2.default.isOverlayTypeOf(this.instance.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
startRow = Math.max(totalRows - this.wot.getSetting('fixedRowsBottom'), 0);
} else {
startRow = wtViewport.rowsRenderCalculator.startRow;
}
var startColumn = void 0;
if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_DEBUG) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_LEFT) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP_LEFT_CORNER) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
startColumn = 0;
} else {
startColumn = wtViewport.columnsRenderCalculator.startColumn;
}
this.rowFilter = new _row2.default(startRow, totalRows, columnHeaders);
this.columnFilter = new _column2.default(startColumn, this.wot.getSetting('totalColumns'), rowHeaders);
this.alignOverlaysWithTrimmingContainer();
this._doDraw(); // creates calculator after draw
}
this.refreshSelections(fastDraw);
if (!this.isWorkingOnClone()) {
wtOverlays.topOverlay.resetFixedPosition();
if (wtOverlays.bottomOverlay.clone) {
wtOverlays.bottomOverlay.resetFixedPosition();
}
wtOverlays.leftOverlay.resetFixedPosition();
if (wtOverlays.topLeftCornerOverlay) {
wtOverlays.topLeftCornerOverlay.resetFixedPosition();
}
if (wtOverlays.bottomLeftCornerOverlay && wtOverlays.bottomLeftCornerOverlay.clone) {
wtOverlays.bottomLeftCornerOverlay.resetFixedPosition();
}
}
if (syncScroll) {
wtOverlays.syncScrollWithMaster();
}
this.wot.drawn = true;
return this;
}
}, {
key: '_doDraw',
value: function _doDraw() {
var wtRenderer = new _tableRenderer2.default(this);
wtRenderer.render();
}
}, {
key: 'removeClassFromCells',
value: function removeClassFromCells(className) {
var nodes = this.TABLE.querySelectorAll('.' + className);
for (var i = 0, len = nodes.length; i < len; i++) {
(0, _element.removeClass)(nodes[i], className);
}
}
/**
* Refresh the table selection by re-rendering Selection instances connected with that instance.
*
* @param {Boolean} fastDraw If fast drawing is enabled than additionally className clearing is applied.
*/
}, {
key: 'refreshSelections',
value: function refreshSelections(fastDraw) {
if (!this.wot.selections) {
return;
}
var highlights = Array.from(this.wot.selections);
var len = highlights.length;
if (fastDraw) {
var classesToRemove = [];
for (var i = 0; i < len; i++) {
var _highlights$i$setting = highlights[i].settings,
highlightHeaderClassName = _highlights$i$setting.highlightHeaderClassName,
highlightRowClassName = _highlights$i$setting.highlightRowClassName,
highlightColumnClassName = _highlights$i$setting.highlightColumnClassName;
var classNames = highlights[i].classNames;
var classNamesLength = classNames.length;
for (var j = 0; j < classNamesLength; j++) {
if (!classesToRemove.includes(classNames[j])) {
classesToRemove.push(classNames[j]);
}
}
if (highlightHeaderClassName && !classesToRemove.includes(highlightHeaderClassName)) {
classesToRemove.push(highlightHeaderClassName);
}
if (highlightRowClassName && !classesToRemove.includes(highlightRowClassName)) {
classesToRemove.push(highlightRowClassName);
}
if (highlightColumnClassName && !classesToRemove.includes(highlightColumnClassName)) {
classesToRemove.push(highlightColumnClassName);
}
}
var classesToRemoveLength = classesToRemove.length;
for (var _i = 0; _i < classesToRemoveLength; _i++) {
// there was no rerender, so we need to remove classNames by ourselves
this.removeClassFromCells(classesToRemove[_i]);
}
}
for (var _i2 = 0; _i2 < len; _i2++) {
highlights[_i2].draw(this.wot, fastDraw);
}
}
/**
* Get cell element at coords.
*
* @param {CellCoords} coords
* @returns {HTMLElement|Number} HTMLElement on success or Number one of the exit codes on error:
* -1 row before viewport
* -2 row after viewport
*/
}, {
key: 'getCell',
value: function getCell(coords) {
var row = coords.row;
var column = coords.col;
var hookResult = this.wot.getSetting('onModifyGetCellCoords', row, column);
if (hookResult && Array.isArray(hookResult)) {
var _hookResult = _slicedToArray(hookResult, 2);
row = _hookResult[0];
column = _hookResult[1];
}
if (this.isRowBeforeRenderedRows(row)) {
// row before rendered rows
return -1;
} else if (this.isRowAfterRenderedRows(row)) {
// row after rendered rows
return -2;
}
var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)];
if (TR) {
return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(column)];
}
}
/**
* getColumnHeader
*
* @param {Number} col Column index
* @param {Number} [level=0] Header level (0 = most distant to the table)
* @returns {Object} HTMLElement on success or undefined on error
*/
}, {
key: 'getColumnHeader',
value: function getColumnHeader(col) {
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var TR = this.THEAD.childNodes[level];
if (TR) {
return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(col)];
}
}
/**
* getRowHeader
*
* @param {Number} row Row index
* @returns {HTMLElement} HTMLElement on success or Number one of the exit codes on error: `null table doesn't have row headers`
*/
}, {
key: 'getRowHeader',
value: function getRowHeader(row) {
if (this.columnFilter.sourceColumnToVisibleRowHeadedColumn(0) === 0) {
return null;
}
var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)];
if (TR) {
return TR.childNodes[0];
}
}
/**
* Returns cell coords object for a given TD (or a child element of a TD element).
*
* @param {HTMLTableCellElement} TD A cell DOM element (or a child of one).
* @returns {CellCoords|null} The coordinates of the provided TD element (or the closest TD element) or null, if the provided element is not applicable.
*/
}, {
key: 'getCoords',
value: function getCoords(TD) {
if (TD.nodeName !== 'TD' && TD.nodeName !== 'TH') {
TD = (0, _element.closest)(TD, ['TD', 'TH']);
}
if (TD === null) {
return null;
}
var TR = TD.parentNode;
var CONTAINER = TR.parentNode;
var row = (0, _element.index)(TR);
var col = TD.cellIndex;
if ((0, _element.overlayContainsElement)(_base2.default.CLONE_TOP_LEFT_CORNER, TD) || (0, _element.overlayContainsElement)(_base2.default.CLONE_TOP, TD)) {
if (CONTAINER.nodeName === 'THEAD') {
row -= CONTAINER.childNodes.length;
}
} else if (CONTAINER === this.THEAD) {
row = this.rowFilter.visibleColHeadedRowToSourceRow(row);
} else {
row = this.rowFilter.renderedToSource(row);
}
if ((0, _element.overlayContainsElement)(_base2.default.CLONE_TOP_LEFT_CORNER, TD) || (0, _element.overlayContainsElement)(_base2.default.CLONE_LEFT, TD)) {
col = this.columnFilter.offsettedTH(col);
} else {
col = this.columnFilter.visibleRowHeadedColumnToSourceColumn(col);
}
return new _coords2.default(row, col);
}
}, {
key: 'getTrForRow',
value: function getTrForRow(row) {
return this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)];
}
}, {
key: 'getFirstRenderedRow',
value: function getFirstRenderedRow() {
return this.wot.wtViewport.rowsRenderCalculator.startRow;
}
}, {
key: 'getFirstVisibleRow',
value: function getFirstVisibleRow() {
return this.wot.wtViewport.rowsVisibleCalculator.startRow;
}
}, {
key: 'getFirstRenderedColumn',
value: function getFirstRenderedColumn() {
return this.wot.wtViewport.columnsRenderCalculator.startColumn;
}
/**
* @returns {Number} Returns -1 if no row is visible
*/
}, {
key: 'getFirstVisibleColumn',
value: function getFirstVisibleColumn() {
return this.wot.wtViewport.columnsVisibleCalculator.startColumn;
}
/**
* @returns {Number} Returns -1 if no row is visible
*/
}, {
key: 'getLastRenderedRow',
value: function getLastRenderedRow() {
return this.wot.wtViewport.rowsRenderCalculator.endRow;
}
}, {
key: 'getLastVisibleRow',
value: function getLastVisibleRow() {
return this.wot.wtViewport.rowsVisibleCalculator.endRow;
}
}, {
key: 'getLastRenderedColumn',
value: function getLastRenderedColumn() {
return this.wot.wtViewport.columnsRenderCalculator.endColumn;
}
/**
* @returns {Number} Returns -1 if no column is visible
*/
}, {
key: 'getLastVisibleColumn',
value: function getLastVisibleColumn() {
return this.wot.wtViewport.columnsVisibleCalculator.endColumn;
}
}, {
key: 'isRowBeforeRenderedRows',
value: function isRowBeforeRenderedRows(row) {
return this.rowFilter && this.rowFilter.sourceToRendered(row) < 0 && row >= 0;
}
}, {
key: 'isRowAfterViewport',
value: function isRowAfterViewport(row) {
return this.rowFilter && this.rowFilter.sourceToRendered(row) > this.getLastVisibleRow();
}
}, {
key: 'isRowAfterRenderedRows',
value: function isRowAfterRenderedRows(row) {
return this.rowFilter && this.rowFilter.sourceToRendered(row) > this.getLastRenderedRow();
}
}, {
key: 'isColumnBeforeViewport',
value: function isColumnBeforeViewport(column) {
return this.columnFilter && this.columnFilter.sourceToRendered(column) < 0 && column >= 0;
}
}, {
key: 'isColumnAfterViewport',
value: function isColumnAfterViewport(column) {
return this.columnFilter && this.columnFilter.sourceToRendered(column) > this.getLastVisibleColumn();
}
}, {
key: 'isLastRowFullyVisible',
value: function isLastRowFullyVisible() {
return this.getLastVisibleRow() === this.getLastRenderedRow();
}
}, {
key: 'isLastColumnFullyVisible',
value: function isLastColumnFullyVisible() {
return this.getLastVisibleColumn() === this.getLastRenderedColumn();
}
}, {
key: 'getRenderedColumnsCount',
value: function getRenderedColumnsCount() {
var columnsCount = this.wot.wtViewport.columnsRenderCalculator.count;
var totalColumns = this.wot.getSetting('totalColumns');
if (this.wot.isOverlayName(_base2.default.CLONE_DEBUG)) {
columnsCount = totalColumns;
} else if (this.wot.isOverlayName(_base2.default.CLONE_LEFT) || this.wot.isOverlayName(_base2.default.CLONE_TOP_LEFT_CORNER) || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
return Math.min(this.wot.getSetting('fixedColumnsLeft'), totalColumns);
}
return columnsCount;
}
}, {
key: 'getRenderedRowsCount',
value: function getRenderedRowsCount() {
var rowsCount = this.wot.wtViewport.rowsRenderCalculator.count;
var totalRows = this.wot.getSetting('totalRows');
if (this.wot.isOverlayName(_base2.default.CLONE_DEBUG)) {
rowsCount = totalRows;
} else if (this.wot.isOverlayName(_base2.default.CLONE_TOP) || this.wot.isOverlayName(_base2.default.CLONE_TOP_LEFT_CORNER)) {
rowsCount = Math.min(this.wot.getSetting('fixedRowsTop'), totalRows);
} else if (this.wot.isOverlayName(_base2.default.CLONE_BOTTOM) || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
rowsCount = Math.min(this.wot.getSetting('fixedRowsBottom'), totalRows);
}
return rowsCount;
}
}, {
key: 'getVisibleRowsCount',
value: function getVisibleRowsCount() {
return this.wot.wtViewport.rowsVisibleCalculator.count;
}
}, {
key: 'allRowsInViewport',
value: function allRowsInViewport() {
return this.wot.getSetting('totalRows') == this.getVisibleRowsCount();
}
/**
* Checks if any of the row's cells content exceeds its initial height, and if so, returns the oversized height
*
* @param {Number} sourceRow
* @returns {Number}
*/
}, {
key: 'getRowHeight',
value: function getRowHeight(sourceRow) {
var height = this.wot.wtSettings.settings.rowHeight(sourceRow);
var oversizedHeight = this.wot.wtViewport.oversizedRows[sourceRow];
if (oversizedHeight !== void 0) {
height = height === void 0 ? oversizedHeight : Math.max(height, oversizedHeight);
}
return height;
}
}, {
key: 'getColumnHeaderHeight',
value: function getColumnHeaderHeight(level) {
var height = this.wot.wtSettings.settings.defaultRowHeight;
var oversizedHeight = this.wot.wtViewport.oversizedColumnHeaders[level];
if (oversizedHeight !== void 0) {
height = height ? Math.max(height, oversizedHeight) : oversizedHeight;
}
return height;
}
}, {
key: 'getVisibleColumnsCount',
value: function getVisibleColumnsCount() {
return this.wot.wtViewport.columnsVisibleCalculator.count;
}
}, {
key: 'allColumnsInViewport',
value: function allColumnsInViewport() {
return this.wot.getSetting('totalColumns') == this.getVisibleColumnsCount();
}
}, {
key: 'getColumnWidth',
value: function getColumnWidth(sourceColumn) {
var width = this.wot.wtSettings.settings.columnWidth;
if (typeof width === 'function') {
width = width(sourceColumn);
} else if ((typeof width === 'undefined' ? 'undefined' : _typeof(width)) === 'object') {
width = width[sourceColumn];
}
return width || this.wot.wtSettings.settings.defaultColumnWidth;
}
}, {
key: 'getStretchedColumnWidth',
value: function getStretchedColumnWidth(sourceColumn) {
var columnWidth = this.getColumnWidth(sourceColumn);
var width = columnWidth == null ? this.instance.wtSettings.settings.defaultColumnWidth : columnWidth;
var calculator = this.wot.wtViewport.columnsRenderCalculator;
if (calculator) {
var stretchedWidth = calculator.getStretchedColumnWidth(sourceColumn, width);
if (stretchedWidth) {
width = stretchedWidth;
}
}
return width;
}
/**
* Modify row header widths provided by user in class contructor.
*
* @private
*/
}, {
key: '_modifyRowHeaderWidth',
value: function _modifyRowHeaderWidth(rowHeaderWidthFactory) {
var widths = (0, _function.isFunction)(rowHeaderWidthFactory) ? rowHeaderWidthFactory() : null;
if (Array.isArray(widths)) {
widths = [].concat(_toConsumableArray(widths));
widths[widths.length - 1] = this._correctRowHeaderWidth(widths[widths.length - 1]);
} else {
widths = this._correctRowHeaderWidth(widths);
}
return widths;
}
/**
* Correct row header width if necessary.
*
* @private
*/
}, {
key: '_correctRowHeaderWidth',
value: function _correctRowHeaderWidth(width) {
if (typeof width !== 'number') {
width = this.wot.getSetting('defaultColumnWidth');
}
if (this.correctHeaderWidth) {
width++;
}
return width;
}
}]);
return Table;
}();
exports.default = Table;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _base = __webpack_require__(30);
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var performanceWarningAppeared = false;
/**
* @class TableRenderer
*/
var TableRenderer = function () {
/**
* @param {WalkontableTable} wtTable
*/
function TableRenderer(wtTable) {
_classCallCheck(this, TableRenderer);
this.wtTable = wtTable;
this.wot = wtTable.instance;
// legacy support
this.instance = wtTable.instance;
this.rowFilter = wtTable.rowFilter;
this.columnFilter = wtTable.columnFilter;
this.TABLE = wtTable.TABLE;
this.THEAD = wtTable.THEAD;
this.TBODY = wtTable.TBODY;
this.COLGROUP = wtTable.COLGROUP;
this.rowHeaders = [];
this.rowHeaderCount = 0;
this.columnHeaders = [];
this.columnHeaderCount = 0;
this.fixedRowsTop = 0;
this.fixedRowsBottom = 0;
}
/**
*
*/
_createClass(TableRenderer, [{
key: 'render',
value: function render() {
if (!this.wtTable.isWorkingOnClone()) {
var skipRender = {};
this.wot.getSetting('beforeDraw', true, skipRender);
if (skipRender.skipRender === true) {
return;
}
}
this.rowHeaders = this.wot.getSetting('rowHeaders');
this.rowHeaderCount = this.rowHeaders.length;
this.fixedRowsTop = this.wot.getSetting('fixedRowsTop');
this.fixedRowsBottom = this.wot.getSetting('fixedRowsBottom');
this.columnHeaders = this.wot.getSetting('columnHeaders');
this.columnHeaderCount = this.columnHeaders.length;
var columnsToRender = this.wtTable.getRenderedColumnsCount();
var rowsToRender = this.wtTable.getRenderedRowsCount();
var totalColumns = this.wot.getSetting('totalColumns');
var totalRows = this.wot.getSetting('totalRows');
var workspaceWidth = void 0;
var adjusted = false;
if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
// do NOT render headers on the bottom or bottom-left corner overlay
this.columnHeaders = [];
this.columnHeaderCount = 0;
}
if (totalColumns >= 0) {
// prepare COL and TH elements for rendering
this.adjustAvailableNodes();
adjusted = true;
// adjust column widths according to user widths settings
this.renderColumnHeaders();
// Render table rows
this.renderRows(totalRows, rowsToRender, columnsToRender);
if (!this.wtTable.isWorkingOnClone()) {
workspaceWidth = this.wot.wtViewport.getWorkspaceWidth();
this.wot.wtViewport.containerWidth = null;
}
this.adjustColumnWidths(columnsToRender);
this.markOversizedColumnHeaders();
this.adjustColumnHeaderHeights();
}
if (!adjusted) {
this.adjustAvailableNodes();
}
this.removeRedundantRows(rowsToRender);
if (!this.wtTable.isWorkingOnClone() || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
this.markOversizedRows();
}
if (!this.wtTable.isWorkingOnClone()) {
this.wot.wtViewport.createVisibleCalculators();
this.wot.wtOverlays.refresh(false);
this.wot.wtOverlays.applyToDOM();
var hiderWidth = (0, _element.outerWidth)(this.wtTable.hider);
var tableWidth = (0, _element.outerWidth)(this.wtTable.TABLE);
if (hiderWidth !== 0 && tableWidth !== hiderWidth) {
// Recalculate the column widths, if width changes made in the overlays removed the scrollbar, thus changing the viewport width.
this.adjustColumnWidths(columnsToRender);
}
if (workspaceWidth !== this.wot.wtViewport.getWorkspaceWidth()) {
// workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
this.wot.wtViewport.containerWidth = null;
var firstRendered = this.wtTable.getFirstRenderedColumn();
var lastRendered = this.wtTable.getLastRenderedColumn();
var defaultColumnWidth = this.wot.getSetting('defaultColumnWidth');
var rowHeaderWidthSetting = this.wot.getSetting('rowHeaderWidth');
rowHeaderWidthSetting = this.instance.getSetting('onModifyRowHeaderWidth', rowHeaderWidthSetting);
if (rowHeaderWidthSetting != null) {
for (var i = 0; i < this.rowHeaderCount; i++) {
var width = Array.isArray(rowHeaderWidthSetting) ? rowHeaderWidthSetting[i] : rowHeaderWidthSetting;
width = width == null ? defaultColumnWidth : width;
this.COLGROUP.childNodes[i].style.width = width + 'px';
}
}
for (var _i = firstRendered; _i < lastRendered; _i++) {
var _width = this.wtTable.getStretchedColumnWidth(_i);
var renderedIndex = this.columnFilter.sourceToRendered(_i);
this.COLGROUP.childNodes[renderedIndex + this.rowHeaderCount].style.width = _width + 'px';
}
}
this.wot.getSetting('onDraw', true);
} else if (this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
this.wot.cloneSource.wtOverlays.adjustElementsSize();
}
}
/**
* @param {Number} renderedRowsCount
*/
}, {
key: 'removeRedundantRows',
value: function removeRedundantRows(renderedRowsCount) {
while (this.wtTable.tbodyChildrenLength > renderedRowsCount) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.wtTable.tbodyChildrenLength--;
}
}
/**
* @param {Number} totalRows
* @param {Number} rowsToRender
* @param {Number} columnsToRender
*/
}, {
key: 'renderRows',
value: function renderRows(totalRows, rowsToRender, columnsToRender) {
var lastTD = void 0,
TR = void 0;
var visibleRowIndex = 0;
var sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex);
var isWorkingOnClone = this.wtTable.isWorkingOnClone();
while (sourceRowIndex < totalRows && sourceRowIndex >= 0) {
if (!performanceWarningAppeared && visibleRowIndex > 1000) {
performanceWarningAppeared = true;
console.warn('Performance tip: Handsontable rendered more than 1000 visible rows. Consider limiting the number ' + 'of rendered rows by specifying the table height and/or turning off the "renderAllRows" option.');
}
if (rowsToRender !== void 0 && visibleRowIndex === rowsToRender) {
// We have as much rows as needed for this clone
break;
}
TR = this.getOrCreateTrForRow(visibleRowIndex, TR);
// Render row headers
this.renderRowHeaders(sourceRowIndex, TR);
// Add and/or remove TDs to TR to match the desired number
this.adjustColumns(TR, columnsToRender + this.rowHeaderCount);
lastTD = this.renderCells(sourceRowIndex, TR, columnsToRender);
if (!isWorkingOnClone ||
// Necessary to refresh oversized row heights after editing cell in overlays
this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
// Reset the oversized row cache for this row
this.resetOversizedRow(sourceRowIndex);
}
if (TR.firstChild) {
// if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is
// the way to make sure that the overlay will has same row height
var height = this.wot.wtTable.getRowHeight(sourceRowIndex);
if (height) {
// Decrease height. 1 pixel will be "replaced" by 1px border top
height--;
TR.firstChild.style.height = height + 'px';
} else {
TR.firstChild.style.height = '';
}
}
visibleRowIndex++;
sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex);
}
}
/**
* Reset the oversized row cache for the provided index
*
* @param {Number} sourceRow Row index
*/
}, {
key: 'resetOversizedRow',
value: function resetOversizedRow(sourceRow) {
if (this.wot.getSetting('externalRowCalculator')) {
return;
}
if (this.wot.wtViewport.oversizedRows && this.wot.wtViewport.oversizedRows[sourceRow]) {
this.wot.wtViewport.oversizedRows[sourceRow] = void 0;
}
}
/**
* Check if any of the rendered rows is higher than expected, and if so, cache them
*/
}, {
key: 'markOversizedRows',
value: function markOversizedRows() {
if (this.wot.getSetting('externalRowCalculator')) {
return;
}
var rowCount = this.instance.wtTable.TBODY.childNodes.length;
var expectedTableHeight = rowCount * this.instance.wtSettings.settings.defaultRowHeight;
var actualTableHeight = (0, _element.innerHeight)(this.instance.wtTable.TBODY) - 1;
var previousRowHeight = void 0;
var rowInnerHeight = void 0;
var sourceRowIndex = void 0;
var currentTr = void 0;
var rowHeader = void 0;
var totalRows = this.instance.getSetting('totalRows');
if (expectedTableHeight === actualTableHeight && !this.instance.getSetting('fixedRowsBottom')) {
// If the actual table height equals rowCount * default single row height, no row is oversized -> no need to iterate over them
return;
}
while (rowCount) {
rowCount--;
sourceRowIndex = this.instance.wtTable.rowFilter.renderedToSource(rowCount);
previousRowHeight = this.instance.wtTable.getRowHeight(sourceRowIndex);
currentTr = this.instance.wtTable.getTrForRow(sourceRowIndex);
rowHeader = currentTr.querySelector('th');
if (rowHeader) {
rowInnerHeight = (0, _element.innerHeight)(rowHeader);
} else {
rowInnerHeight = (0, _element.innerHeight)(currentTr) - 1;
}
if (!previousRowHeight && this.instance.wtSettings.settings.defaultRowHeight < rowInnerHeight || previousRowHeight < rowInnerHeight) {
this.instance.wtViewport.oversizedRows[sourceRowIndex] = ++rowInnerHeight;
}
}
}
/**
* Check if any of the rendered columns is higher than expected, and if so, cache them.
*/
}, {
key: 'markOversizedColumnHeaders',
value: function markOversizedColumnHeaders() {
var overlayName = this.wot.getOverlayName();
if (!this.columnHeaderCount || this.wot.wtViewport.hasOversizedColumnHeadersMarked[overlayName] || this.wtTable.isWorkingOnClone()) {
return;
}
var columnCount = this.wtTable.getRenderedColumnsCount();
for (var i = 0; i < this.columnHeaderCount; i++) {
for (var renderedColumnIndex = -1 * this.rowHeaderCount; renderedColumnIndex < columnCount; renderedColumnIndex++) {
this.markIfOversizedColumnHeader(renderedColumnIndex);
}
}
this.wot.wtViewport.hasOversizedColumnHeadersMarked[overlayName] = true;
}
/**
*
*/
}, {
key: 'adjustColumnHeaderHeights',
value: function adjustColumnHeaderHeights() {
var columnHeaders = this.wot.getSetting('columnHeaders');
var children = this.wot.wtTable.THEAD.childNodes;
var oversizedColumnHeaders = this.wot.wtViewport.oversizedColumnHeaders;
for (var i = 0, len = columnHeaders.length; i < len; i++) {
if (oversizedColumnHeaders[i]) {
if (!children[i] || children[i].childNodes.length === 0) {
return;
}
children[i].childNodes[0].style.height = oversizedColumnHeaders[i] + 'px';
}
}
}
/**
* Check if column header for the specified column is higher than expected, and if so, cache it
*
* @param {Number} col Index of column
*/
}, {
key: 'markIfOversizedColumnHeader',
value: function markIfOversizedColumnHeader(col) {
var sourceColIndex = this.wot.wtTable.columnFilter.renderedToSource(col);
var level = this.columnHeaderCount;
var defaultRowHeight = this.wot.wtSettings.settings.defaultRowHeight;
var previousColHeaderHeight = void 0;
var currentHeader = void 0;
var currentHeaderHeight = void 0;
var columnHeaderHeightSetting = this.wot.getSetting('columnHeaderHeight') || [];
while (level) {
level--;
previousColHeaderHeight = this.wot.wtTable.getColumnHeaderHeight(level);
currentHeader = this.wot.wtTable.getColumnHeader(sourceColIndex, level);
if (!currentHeader) {
/* eslint-disable no-continue */
continue;
}
currentHeaderHeight = (0, _element.innerHeight)(currentHeader);
if (!previousColHeaderHeight && defaultRowHeight < currentHeaderHeight || previousColHeaderHeight < currentHeaderHeight) {
this.wot.wtViewport.oversizedColumnHeaders[level] = currentHeaderHeight;
}
if (Array.isArray(columnHeaderHeightSetting)) {
if (columnHeaderHeightSetting[level] != null) {
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level];
}
} else if (!isNaN(columnHeaderHeightSetting)) {
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting;
}
if (this.wot.wtViewport.oversizedColumnHeaders[level] < (columnHeaderHeightSetting[level] || columnHeaderHeightSetting)) {
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level] || columnHeaderHeightSetting;
}
}
}
/**
* @param {Number} sourceRowIndex
* @param {HTMLTableRowElement} TR
* @param {Number} columnsToRender
* @returns {HTMLTableCellElement}
*/
}, {
key: 'renderCells',
value: function renderCells(sourceRowIndex, TR, columnsToRender) {
var TD = void 0;
var sourceColIndex = void 0;
for (var visibleColIndex = 0; visibleColIndex < columnsToRender; visibleColIndex++) {
sourceColIndex = this.columnFilter.renderedToSource(visibleColIndex);
if (visibleColIndex === 0) {
TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(sourceColIndex)];
} else {
TD = TD.nextSibling; // http://jsperf.com/nextsibling-vs-indexed-childnodes
}
// If the number of headers has been reduced, we need to replace excess TH with TD
if (TD.nodeName == 'TH') {
TD = replaceThWithTd(TD, TR);
}
if (!(0, _element.hasClass)(TD, 'hide')) {
TD.className = '';
}
TD.removeAttribute('style');
this.wot.wtSettings.settings.cellRenderer(sourceRowIndex, sourceColIndex, TD);
}
return TD;
}
/**
* @param {Number} columnsToRender Number of columns to render.
*/
}, {
key: 'adjustColumnWidths',
value: function adjustColumnWidths(columnsToRender) {
var scrollbarCompensation = 0;
var sourceInstance = this.wot.cloneSource ? this.wot.cloneSource : this.wot;
var mainHolder = sourceInstance.wtTable.holder;
var defaultColumnWidth = this.wot.getSetting('defaultColumnWidth');
var rowHeaderWidthSetting = this.wot.getSetting('rowHeaderWidth');
if (mainHolder.offsetHeight < mainHolder.scrollHeight) {
scrollbarCompensation = (0, _element.getScrollbarWidth)();
}
this.wot.wtViewport.columnsRenderCalculator.refreshStretching(this.wot.wtViewport.getViewportWidth() - scrollbarCompensation);
rowHeaderWidthSetting = this.instance.getSetting('onModifyRowHeaderWidth', rowHeaderWidthSetting);
if (rowHeaderWidthSetting != null) {
for (var i = 0; i < this.rowHeaderCount; i++) {
var width = Array.isArray(rowHeaderWidthSetting) ? rowHeaderWidthSetting[i] : rowHeaderWidthSetting;
width = width == null ? defaultColumnWidth : width;
this.COLGROUP.childNodes[i].style.width = width + 'px';
}
}
for (var renderedColIndex = 0; renderedColIndex < columnsToRender; renderedColIndex++) {
var _width2 = this.wtTable.getStretchedColumnWidth(this.columnFilter.renderedToSource(renderedColIndex));
this.COLGROUP.childNodes[renderedColIndex + this.rowHeaderCount].style.width = _width2 + 'px';
}
}
/**
* @param {HTMLTableCellElement} TR
*/
}, {
key: 'appendToTbody',
value: function appendToTbody(TR) {
this.TBODY.appendChild(TR);
this.wtTable.tbodyChildrenLength++;
}
/**
* @param {Number} rowIndex
* @param {HTMLTableRowElement} currentTr
* @returns {HTMLTableCellElement}
*/
}, {
key: 'getOrCreateTrForRow',
value: function getOrCreateTrForRow(rowIndex, currentTr) {
var TR = void 0;
if (rowIndex >= this.wtTable.tbodyChildrenLength) {
TR = this.createRow();
this.appendToTbody(TR);
} else if (rowIndex === 0) {
TR = this.TBODY.firstChild;
} else {
// http://jsperf.com/nextsibling-vs-indexed-childnodes
TR = currentTr.nextSibling;
}
if (TR.className) {
TR.removeAttribute('class');
}
return TR;
}
/**
* @returns {HTMLTableCellElement}
*/
}, {
key: 'createRow',
value: function createRow() {
var TR = document.createElement('TR');
for (var visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
TR.appendChild(document.createElement('TH'));
}
return TR;
}
/**
* @param {Number} row
* @param {Number} col
* @param {HTMLTableCellElement} TH
*/
}, {
key: 'renderRowHeader',
value: function renderRowHeader(row, col, TH) {
TH.className = '';
TH.removeAttribute('style');
this.rowHeaders[col](row, TH, col);
}
/**
* @param {Number} row
* @param {HTMLTableCellElement} TR
*/
}, {
key: 'renderRowHeaders',
value: function renderRowHeaders(row, TR) {
for (var TH = TR.firstChild, visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
// If the number of row headers increased we need to create TH or replace an existing TD node with TH
if (!TH) {
TH = document.createElement('TH');
TR.appendChild(TH);
} else if (TH.nodeName == 'TD') {
TH = replaceTdWithTh(TH, TR);
}
this.renderRowHeader(row, visibleColIndex, TH);
// http://jsperf.com/nextsibling-vs-indexed-childnodes
TH = TH.nextSibling;
}
}
/**
* Adjust the number of COL and TH elements to match the number of columns and headers that need to be rendered
*/
}, {
key: 'adjustAvailableNodes',
value: function adjustAvailableNodes() {
this.adjustColGroups();
this.adjustThead();
}
/**
* Renders the column headers
*/
}, {
key: 'renderColumnHeaders',
value: function renderColumnHeaders() {
if (!this.columnHeaderCount) {
return;
}
var columnCount = this.wtTable.getRenderedColumnsCount();
for (var i = 0; i < this.columnHeaderCount; i++) {
var TR = this.getTrForColumnHeaders(i);
for (var renderedColumnIndex = -1 * this.rowHeaderCount; renderedColumnIndex < columnCount; renderedColumnIndex++) {
var sourceCol = this.columnFilter.renderedToSource(renderedColumnIndex);
this.renderColumnHeader(i, sourceCol, TR.childNodes[renderedColumnIndex + this.rowHeaderCount]);
}
}
}
/**
* Adjusts the number of COL elements to match the number of columns that need to be rendered
*/
}, {
key: 'adjustColGroups',
value: function adjustColGroups() {
var columnCount = this.wtTable.getRenderedColumnsCount();
while (this.wtTable.colgroupChildrenLength < columnCount + this.rowHeaderCount) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.wtTable.colgroupChildrenLength++;
}
while (this.wtTable.colgroupChildrenLength > columnCount + this.rowHeaderCount) {
this.COLGROUP.removeChild(this.COLGROUP.lastChild);
this.wtTable.colgroupChildrenLength--;
}
if (this.rowHeaderCount) {
(0, _element.addClass)(this.COLGROUP.childNodes[0], 'rowHeader');
}
}
/**
* Adjusts the number of TH elements in THEAD to match the number of headers and columns that need to be rendered
*/
}, {
key: 'adjustThead',
value: function adjustThead() {
var columnCount = this.wtTable.getRenderedColumnsCount();
var TR = this.THEAD.firstChild;
if (this.columnHeaders.length) {
for (var i = 0, len = this.columnHeaders.length; i < len; i++) {
TR = this.THEAD.childNodes[i];
if (!TR) {
TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
this.theadChildrenLength = TR.childNodes.length;
while (this.theadChildrenLength < columnCount + this.rowHeaderCount) {
TR.appendChild(document.createElement('TH'));
this.theadChildrenLength++;
}
while (this.theadChildrenLength > columnCount + this.rowHeaderCount) {
TR.removeChild(TR.lastChild);
this.theadChildrenLength--;
}
}
var theadChildrenLength = this.THEAD.childNodes.length;
if (theadChildrenLength > this.columnHeaders.length) {
for (var _i2 = this.columnHeaders.length; _i2 < theadChildrenLength; _i2++) {
this.THEAD.removeChild(this.THEAD.lastChild);
}
}
} else if (TR) {
(0, _element.empty)(TR);
}
}
/**
* @param {Number} index
* @returns {HTMLTableCellElement}
*/
}, {
key: 'getTrForColumnHeaders',
value: function getTrForColumnHeaders(index) {
return this.THEAD.childNodes[index];
}
/**
* @param {Number} row
* @param {Number} col
* @param {HTMLTableCellElement} TH
* @returns {*}
*/
}, {
key: 'renderColumnHeader',
value: function renderColumnHeader(row, col, TH) {
TH.className = '';
TH.removeAttribute('style');
return this.columnHeaders[row](col, TH, row);
}
/**
* Add and/or remove the TDs to match the desired number
*
* @param {HTMLTableCellElement} TR Table row in question
* @param {Number} desiredCount The desired number of TDs in the TR
*/
}, {
key: 'adjustColumns',
value: function adjustColumns(TR, desiredCount) {
var count = TR.childNodes.length;
while (count < desiredCount) {
var TD = document.createElement('TD');
TR.appendChild(TD);
count++;
}
while (count > desiredCount) {
TR.removeChild(TR.lastChild);
count--;
}
}
/**
* @param {Number} columnsToRender
*/
}, {
key: 'removeRedundantColumns',
value: function removeRedundantColumns(columnsToRender) {
while (this.wtTable.tbodyChildrenLength > columnsToRender) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.wtTable.tbodyChildrenLength--;
}
}
}]);
return TableRenderer;
}();
function replaceTdWithTh(TD, TR) {
var TH = document.createElement('TH');
TR.insertBefore(TH, TD);
TR.removeChild(TD);
return TH;
}
function replaceThWithTd(TH, TR) {
var TD = document.createElement('TD');
TR.insertBefore(TD, TH);
TR.removeChild(TH);
return TD;
}
exports.default = TableRenderer;
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
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 _element = __webpack_require__(2);
var _object = __webpack_require__(1);
var _eventManager = __webpack_require__(9);
var _eventManager2 = _interopRequireDefault(_eventManager);
var _viewportColumns = __webpack_require__(189);
var _viewportColumns2 = _interopRequireDefault(_viewportColumns);
var _viewportRows = __webpack_require__(190);
var _viewportRows2 = _interopRequireDefault(_viewportRows);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class Viewport
*/
var Viewport = function () {
/**
* @param wotInstance
*/
function Viewport(wotInstance) {
var _this = this;
_classCallCheck(this, Viewport);
this.wot = wotInstance;
// legacy support
this.instance = this.wot;
this.oversizedRows = [];
this.oversizedColumnHeaders = [];
this.hasOversizedColumnHeadersMarked = {};
this.clientHeight = 0;
this.containerWidth = NaN;
this.rowHeaderWidth = NaN;
this.rowsVisibleCalculator = null;
this.columnsVisibleCalculator = null;
this.eventManager = new _eventManager2.default(this.wot);
this.eventManager.addEventListener(window, 'resize', function () {
_this.clientHeight = _this.getWorkspaceHeight();
});
}
/**
* @returns {number}
*/
_createClass(Viewport, [{
key: 'getWorkspaceHeight',
value: function getWorkspaceHeight() {
var trimmingContainer = this.instance.wtOverlays.topOverlay.trimmingContainer;
var elemHeight = void 0;
var height = 0;
if (trimmingContainer === window) {
height = document.documentElement.clientHeight;
} else {
elemHeight = (0, _element.outerHeight)(trimmingContainer);
// returns height without DIV scrollbar
height = elemHeight > 0 && trimmingContainer.clientHeight > 0 ? trimmingContainer.clientHeight : Infinity;
}
return height;
}
}, {
key: 'getWorkspaceWidth',
value: function getWorkspaceWidth() {
var width = void 0;
var totalColumns = this.wot.getSetting('totalColumns');
var trimmingContainer = this.instance.wtOverlays.leftOverlay.trimmingContainer;
var overflow = void 0;
var stretchSetting = this.wot.getSetting('stretchH');
var docOffsetWidth = document.documentElement.offsetWidth;
var preventOverflow = this.wot.getSetting('preventOverflow');
if (preventOverflow) {
return (0, _element.outerWidth)(this.instance.wtTable.wtRootElement);
}
if (this.wot.getSetting('freezeOverlays')) {
width = Math.min(docOffsetWidth - this.getWorkspaceOffset().left, docOffsetWidth);
} else {
width = Math.min(this.getContainerFillWidth(), docOffsetWidth - this.getWorkspaceOffset().left, docOffsetWidth);
}
if (trimmingContainer === window && totalColumns > 0 && this.sumColumnWidths(0, totalColumns - 1) > width) {
// in case sum of column widths is higher than available stylesheet width, let's assume using the whole window
// otherwise continue below, which will allow stretching
// this is used in `scroll_window.html`
// TODO test me
return document.documentElement.clientWidth;
}
if (trimmingContainer !== window) {
overflow = (0, _element.getStyle)(this.instance.wtOverlays.leftOverlay.trimmingContainer, 'overflow');
if (overflow == 'scroll' || overflow == 'hidden' || overflow == 'auto') {
// this is used in `scroll.html`
// TODO test me
return Math.max(width, trimmingContainer.clientWidth);
}
}
if (stretchSetting === 'none' || !stretchSetting) {
// if no stretching is used, return the maximum used workspace width
return Math.max(width, (0, _element.outerWidth)(this.instance.wtTable.TABLE));
}
// if stretching is used, return the actual container width, so the columns can fit inside it
return width;
}
/**
* Checks if viewport has vertical scroll
*
* @returns {Boolean}
*/
}, {
key: 'hasVerticalScroll',
value: function hasVerticalScroll() {
return this.getWorkspaceActualHeight() > this.getWorkspaceHeight();
}
/**
* Checks if viewport has horizontal scroll
*
* @returns {Boolean}
*/
}, {
key: 'hasHorizontalScroll',
value: function hasHorizontalScroll() {
return this.getWorkspaceActualWidth() > this.getWorkspaceWidth();
}
/**
* @param from
* @param length
* @returns {Number}
*/
}, {
key: 'sumColumnWidths',
value: function sumColumnWidths(from, length) {
var sum = 0;
while (from < length) {
sum += this.wot.wtTable.getColumnWidth(from);
from++;
}
return sum;
}
/**
* @returns {Number}
*/
}, {
key: 'getContainerFillWidth',
value: function getContainerFillWidth() {
if (this.containerWidth) {
return this.containerWidth;
}
var mainContainer = this.instance.wtTable.holder;
var fillWidth = void 0;
var dummyElement = void 0;
dummyElement = document.createElement('div');
dummyElement.style.width = '100%';
dummyElement.style.height = '1px';
mainContainer.appendChild(dummyElement);
fillWidth = dummyElement.offsetWidth;
this.containerWidth = fillWidth;
mainContainer.removeChild(dummyElement);
return fillWidth;
}
/**
* @returns {Number}
*/
}, {
key: 'getWorkspaceOffset',
value: function getWorkspaceOffset() {
return (0, _element.offset)(this.wot.wtTable.TABLE);
}
/**
* @returns {Number}
*/
}, {
key: 'getWorkspaceActualHeight',
value: function getWorkspaceActualHeight() {
return (0, _element.outerHeight)(this.wot.wtTable.TABLE);
}
/**
* @returns {Number}
*/
}, {
key: 'getWorkspaceActualWidth',
value: function getWorkspaceActualWidth() {
return (0, _element.outerWidth)(this.wot.wtTable.TABLE) || (0, _element.outerWidth)(this.wot.wtTable.TBODY) || (0, _element.outerWidth)(this.wot.wtTable.THEAD); // IE8 reports 0 as